blob: ab555532a102a16c82a32113b5850434ee47606f [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070031import static android.content.pm.PackageManager.MATCH_ANY_USER;
32import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
33import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
34import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
35import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
Erik Klinef851d6d2015-04-20 16:03:48 +090036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080037import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
38import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
39import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060040import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060041import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey9252b342018-01-19 07:58:35 +090042import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070043import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070044import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070045import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070046import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070047import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080048import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070049import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
50import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070051import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070052import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060053import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070055import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070056import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070058import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070061import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070063import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080064import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
65import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060066import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070067import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070068import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070069import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070070import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070071import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080072import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070073import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070074import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060075import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090076import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070084import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
85import static com.android.internal.util.XmlUtils.writeIntAttribute;
86import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060087import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070088import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070089import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
90import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
91import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
92import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
93import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
94import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
95import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060097
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080099import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700101
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700102import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700103import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900104import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700105import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700106import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800107import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700109import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700111import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700113import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700115import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700116import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700117import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700119import android.content.Intent;
120import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700121import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700122import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700123import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700124import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700125import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600128import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700130import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700131import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700132import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700133import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700134import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600135import android.net.Network;
136import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700137import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600139import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700140import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900142import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700143import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700144import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700145import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900146import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700148import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700149import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700150import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700151import android.os.Binder;
Jeff Sharkeya7f50462018-02-14 14:26:10 -0700152import android.os.Build;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700153import android.os.Environment;
154import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700155import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700156import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700157import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700158import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700159import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700160import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700161import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700162import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700163import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600164import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800165import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700166import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700167import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600168import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700169import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700170import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700171import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600172import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700173import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700174import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700175import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700176import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100177import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700178import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600179import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800180import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600181import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700182import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400183import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700184import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700185import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700186import android.util.ArrayMap;
187import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700188import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900189import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700190import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700191import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600192import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700193import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600194import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195import android.util.SparseBooleanArray;
196import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900197import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700199
Jeff Sharkey497e4432011-06-14 17:27:29 -0700200import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700201import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800202import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400203import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500204import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700205import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800206import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800207import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600208import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700210import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600211import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700212import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700213import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700214import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800215import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600216
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600217import libcore.io.IoUtils;
218
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220import org.xmlpull.v1.XmlSerializer;
221
222import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700223import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224import java.io.FileInputStream;
225import java.io.FileNotFoundException;
226import java.io.FileOutputStream;
227import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700228import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700229import java.lang.annotation.Retention;
230import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100231import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700232import java.time.Clock;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600233import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700234import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600235import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700237import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600238import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400239import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800240import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800241import java.util.concurrent.CountDownLatch;
242import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700244/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700245 * Service that maintains low-level network policy rules, using
246 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700247 * <p>
248 * Derives active rules by combining a given policy with other system status,
249 * and delivers to listeners, such as {@link ConnectivityManager}, for
250 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700251 *
252 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000253 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700254 * <ul>
255 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
256 * rules).
257 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
258 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000259 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
260 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700261 * </ul>
262 *
263 * <p>
264 * As such, methods that require synchronization have the following prefixes:
265 * <ul>
266 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
267 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000268 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
269 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700270 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700271 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700272public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700273 static final String TAG = NetworkPolicyLogger.TAG;
274 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
275 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700276
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700277 private static final int VERSION_INIT = 1;
278 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700279 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800280 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800281 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800282 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700283 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700284 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700285 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700286 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600287 private static final int VERSION_ADDED_CYCLE = 11;
288 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700289
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800290 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400291 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800292 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400293 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800294 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400295 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900296 @VisibleForTesting
297 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700298
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700299 private static final String TAG_POLICY_LIST = "policy-list";
300 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600301 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700303 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800304 private static final String TAG_WHITELIST = "whitelist";
305 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800306 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307
308 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700309 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
311 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700312 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600313 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
314 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
315 private static final String ATTR_CYCLE_START = "cycleStart";
316 private static final String ATTR_CYCLE_END = "cycleEnd";
317 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700318 private static final String ATTR_WARNING_BYTES = "warningBytes";
319 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700320 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800321 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
322 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800323 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700324 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700326 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600328 private static final String ATTR_SUB_ID = "subId";
329 private static final String ATTR_TITLE = "title";
330 private static final String ATTR_SUMMARY = "summary";
331 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
332 private static final String ATTR_USAGE_BYTES = "usageBytes";
333 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600334 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800336 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800337 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800338 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800339 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700340 private static final String ACTION_SNOOZE_RAPID =
341 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700342
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800343 /**
344 * Indicates the maximum wait time for admin data to be available;
345 */
346 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
347
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700348 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700349 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800350 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800351 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700352 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700353 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
354 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700355 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700356 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900357 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800358 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700359
Makoto Onuki8e777332017-03-28 11:25:47 -0700360 private static final int UID_MSG_STATE_CHANGED = 100;
361 private static final int UID_MSG_GONE = 101;
362
Jeff Sharkey75279902011-05-24 18:39:45 -0700363 private final Context mContext;
364 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700365 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700366 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700367 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700368 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700369 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700370 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700371
372 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700373 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700374 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800375 @GuardedBy("mUidRulesFirstLock")
376 private PowerSaveState mRestrictBackgroundPowerState;
377
378 // Store the status of restrict background before turning on battery saver.
379 // Used to restore mRestrictBackground when battery saver is turned off.
380 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700381
Sudheer Shanka543339f2017-07-28 15:18:07 -0700382 // Denotes the status of restrict background read from disk.
383 private boolean mLoadedRestrictBackground;
384
Felipe Lemef0823852016-06-08 13:43:08 -0700385 // See main javadoc for instructions on how to use these locks.
386 final Object mUidRulesFirstLock = new Object();
387 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700388
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("allLocks") volatile boolean mSystemReady;
390
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
392 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
393 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800394 // Store whether user flipped restrict background in battery saver mode
395 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700396
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700397 private final boolean mSuppressDefaultPolicy;
398
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800399 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
400
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700401 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600402 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800403 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700404
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600405 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600406 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600407 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600408 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600409 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600410 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600411
Jeff Sharkey9252b342018-01-19 07:58:35 +0900412 /** Map from subId to daily opportunistic quota. */
413 @GuardedBy("mNetworkPoliciesSecondLock")
414 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
415
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700416 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700418 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700419 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700420
Felipe Lemef0823852016-06-08 13:43:08 -0700421 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700422 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700424 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800426 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700427
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700428 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700429 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700430 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
431
Jeff Sharkey32566012014-12-02 18:30:14 -0800432 /**
433 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700434 * in power save mode, except device idle (doze) still applies.
435 * TODO: An int array might be sufficient
436 */
Felipe Lemef0823852016-06-08 13:43:08 -0700437 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700438 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
439
440 /**
441 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800442 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700443 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800444 */
Felipe Lemef0823852016-06-08 13:43:08 -0700445 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700446 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700447
Felipe Lemef0823852016-06-08 13:43:08 -0700448 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700449 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
450
Felipe Lemeb85a6372016-01-14 16:16:16 -0800451 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800452 * UIDs that have been initially white-listed by system to avoid restricted background.
453 */
Felipe Lemef0823852016-06-08 13:43:08 -0700454 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800455 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
456 new SparseBooleanArray();
457
458 /**
459 * UIDs that have been initially white-listed by system to avoid restricted background,
460 * but later revoked by user.
461 */
Felipe Lemef0823852016-06-08 13:43:08 -0700462 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800463 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
464 new SparseBooleanArray();
465
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700466 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700467 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800468 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700469 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700470 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800471 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700472
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700473 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400475 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700476
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700477 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700478 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800479 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700480
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600481 /** Map from network ID to last observed meteredness state */
482 @GuardedBy("mNetworkPoliciesSecondLock")
483 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
484
Jeff Sharkey9252b342018-01-19 07:58:35 +0900485 /** Map from netId to subId as of last update */
486 @GuardedBy("mNetworkPoliciesSecondLock")
487 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
488
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800489 /**
490 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
491 * userId to restricted uids which belong to that user.
492 */
493 @GuardedBy("mUidRulesFirstLock")
494 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
495
Jeff Sharkey32566012014-12-02 18:30:14 -0800496 private final RemoteCallbackList<INetworkPolicyListener>
497 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700498
Dianne Hackborn497175b2014-07-01 12:56:08 -0700499 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700500 @VisibleForTesting
501 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700502
503 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700504
Felipe Lemef0823852016-06-08 13:43:08 -0700505 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700507
Svet Ganov16a16892015-04-16 10:32:04 -0700508 private final AppOpsManager mAppOps;
509
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800510 private final IPackageManager mIPm;
511
Sudheer Shankae7361852017-03-07 11:51:46 -0800512 private ActivityManagerInternal mActivityManagerInternal;
513
Sudheer Shanka352dc572017-09-22 17:09:38 -0700514 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800515
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700516 // TODO: keep whitelist of system-critical services that should never have
517 // rules enforced, such as system, phone, and radio UIDs.
518
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700519 // TODO: migrate notifications to SystemUI
520
Jeff Sharkey75279902011-05-24 18:39:45 -0700521 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700522 INetworkManagementService networkManagement) {
523 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
524 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700525 }
526
Jeff Sharkey9911a282018-02-14 22:29:11 -0700527 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700528 return new File(Environment.getDataDirectory(), "system");
529 }
530
Jeff Sharkey9911a282018-02-14 22:29:11 -0700531 private static @NonNull Clock getDefaultClock() {
532 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
533 Clock.systemUTC());
534 }
535
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700536 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700537 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
538 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700539 mContext = checkNotNull(context, "missing context");
540 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700541 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700542 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700543 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700544 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700545 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700546 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700547 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700548
Amith Yamasani450a16b2013-09-18 16:28:50 -0700549 HandlerThread thread = new HandlerThread(TAG);
550 thread.start();
551 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700552
Makoto Onuki8e777332017-03-28 11:25:47 -0700553 // We create another thread for the UID events, which are more time-critical.
554 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
555 /*allowIo=*/ false);
556 mUidEventThread.start();
557 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
558
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700559 mSuppressDefaultPolicy = suppressDefaultPolicy;
560
Dianne Hackborne17b4452018-01-10 13:15:40 -0800561 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700562
563 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800564
Felipe Lemed17fda42016-04-29 11:12:45 -0700565 // Expose private service for system components to use.
566 LocalServices.addService(NetworkPolicyManagerInternal.class,
567 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700568 }
569
570 public void bindConnectivityManager(IConnectivityManager connManager) {
571 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700573
Felipe Lemef0823852016-06-08 13:43:08 -0700574 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700575 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700576 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
577 mPowerSaveWhitelistExceptIdleAppIds.clear();
578 if (whitelist != null) {
579 for (int uid : whitelist) {
580 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
581 }
582 }
583 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700584 mPowerSaveWhitelistAppIds.clear();
585 if (whitelist != null) {
586 for (int uid : whitelist) {
587 mPowerSaveWhitelistAppIds.put(uid, true);
588 }
589 }
590 } catch (RemoteException e) {
591 }
592 }
593
Felipe Lemea9505cc2016-02-26 10:28:41 -0800594 /**
595 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
596 * revoke the whitelist.
597 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700598 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800599 */
Felipe Lemef0823852016-06-08 13:43:08 -0700600 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800601 final List<UserInfo> users = mUserManager.getUsers();
602 final int numberUsers = users.size();
603
Felipe Lemea110eec2016-04-29 09:58:06 -0700604 boolean changed = false;
605 for (int i = 0; i < numberUsers; i++) {
606 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700607 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700608 }
609 return changed;
610 }
611
Felipe Lemef0823852016-06-08 13:43:08 -0700612 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700613 final SystemConfig sysConfig = SystemConfig.getInstance();
614 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800615 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
616 boolean changed = false;
617 for (int i = 0; i < allowDataUsage.size(); i++) {
618 final String pkg = allowDataUsage.valueAt(i);
619 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700620 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
621 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800622 final ApplicationInfo app;
623 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700624 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800625 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700626 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
627 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800628 continue;
629 }
630 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700631 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
632 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800633 continue;
634 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700635 final int uid = UserHandle.getUid(userId, app.uid);
636 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
637 if (LOGD)
638 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
639 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800640 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700641 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700642 if (LOGD)
643 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
644 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700645 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700646 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800647 }
648 }
649 return changed;
650 }
651
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800652 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700653 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800654 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700655 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800656 // Boost thread's priority during system server init
657 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700658 if (!isBandwidthControlEnabled()) {
659 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
660 return;
661 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700662
Felipe Leme873a83a2016-09-07 11:34:10 -0700663 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700664 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700665
Felipe Leme873a83a2016-09-07 11:34:10 -0700666 synchronized (mUidRulesFirstLock) {
667 synchronized (mNetworkPoliciesSecondLock) {
668 updatePowerSaveWhitelistUL();
669 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
670 mPowerManagerInternal.registerLowPowerModeObserver(
671 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800672 @Override
673 public int getServiceType() {
674 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700675 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800676
677 @Override
678 public void onLowPowerModeChanged(PowerSaveState result) {
679 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800680 if (LOGD) {
681 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
682 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800683 synchronized (mUidRulesFirstLock) {
684 if (mRestrictPower != enabled) {
685 mRestrictPower = enabled;
686 updateRulesForRestrictPowerUL();
687 }
688 }
689 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800690 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800691 mRestrictPower = mPowerManagerInternal.getLowPowerState(
692 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700693
694 mSystemReady = true;
695
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800696 waitForAdminData();
697
Felipe Leme873a83a2016-09-07 11:34:10 -0700698 // read policy from disk
699 readPolicyAL();
700
jackqdyulei29c82ab2017-03-10 14:09:16 -0800701 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700702 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800703 mRestrictBackgroundPowerState = mPowerManagerInternal
704 .getLowPowerState(ServiceType.DATA_SAVER);
705 final boolean localRestrictBackground =
706 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700707 if (localRestrictBackground && !mLoadedRestrictBackground) {
708 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800709 }
710 mPowerManagerInternal.registerLowPowerModeObserver(
711 new PowerManagerInternal.LowPowerModeListener() {
712 @Override
713 public int getServiceType() {
714 return ServiceType.DATA_SAVER;
715 }
716
717 @Override
718 public void onLowPowerModeChanged(PowerSaveState result) {
719 synchronized (mUidRulesFirstLock) {
720 updateRestrictBackgroundByLowPowerModeUL(result);
721 }
722 }
723 });
724
Felipe Leme873a83a2016-09-07 11:34:10 -0700725 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
726 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700727 }
Felipe Lemef0823852016-06-08 13:43:08 -0700728
Sudheer Shanka543339f2017-07-28 15:18:07 -0700729 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700730 updateRulesForGlobalChangeAL(false);
731 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700732 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800733 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700734
Sudheer Shankae7361852017-03-07 11:51:46 -0800735 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700736 try {
737 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000738 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800739 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700740 mNetworkManager.registerObserver(mAlertObserver);
741 } catch (RemoteException e) {
742 // ignored; both services live in system_server
743 }
744
745 // listen for changes to power save whitelist
746 final IntentFilter whitelistFilter = new IntentFilter(
747 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
748 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
749
Felipe Leme873a83a2016-09-07 11:34:10 -0700750 // watch for network interfaces to be claimed
751 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
752 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
753
754 // listen for package changes to update policy
755 final IntentFilter packageFilter = new IntentFilter();
756 packageFilter.addAction(ACTION_PACKAGE_ADDED);
757 packageFilter.addDataScheme("package");
758 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
759
760 // listen for UID changes to update policy
761 mContext.registerReceiver(
762 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
763
764 // listen for user changes to update policy
765 final IntentFilter userFilter = new IntentFilter();
766 userFilter.addAction(ACTION_USER_ADDED);
767 userFilter.addAction(ACTION_USER_REMOVED);
768 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
769
770 // listen for stats update events
771 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
772 mContext.registerReceiver(
773 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
774
775 // listen for restrict background changes from notifications
776 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
777 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
778
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700779 // Listen for snooze from notifications
780 mContext.registerReceiver(mSnoozeReceiver,
781 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
782 mContext.registerReceiver(mSnoozeReceiver,
783 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700784
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600785 // listen for configured wifi networks to be loaded
786 final IntentFilter wifiFilter =
787 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
788 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700789
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700790 // listen for carrier config changes to update data cycle information
791 final IntentFilter carrierConfigFilter = new IntentFilter(
792 ACTION_CARRIER_CONFIG_CHANGED);
793 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
794
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600795 // listen for meteredness changes
796 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
797 new NetworkRequest.Builder().build(), mNetworkCallback);
798
Felipe Leme873a83a2016-09-07 11:34:10 -0700799 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800800 // tell systemReady() that the service has been initialized
801 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700802 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800803 // Restore the default priority after init is done
804 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700805 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700806 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700807 }
808
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800809 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
810 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
811 mHandler.post(() -> initService(initCompleteSignal));
812 return initCompleteSignal;
813 }
814
815 public void systemReady(CountDownLatch initCompleteSignal) {
816 // wait for initService to complete
817 try {
818 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
819 throw new IllegalStateException("Service " + TAG +" init timeout");
820 }
821 } catch (InterruptedException e) {
822 Thread.currentThread().interrupt();
823 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
824 }
825 }
826
Sudheer Shankac9d94072017-02-22 22:13:55 +0000827 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700828 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700829 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
830 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700831 }
832
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700833 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700834 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700835 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700837 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700838 }
839
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700840 @Override public void onUidIdle(int uid, boolean disabled) {
841 }
842
843 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700844 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700845 };
846
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700847 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700848 @Override
849 public void onReceive(Context context, Intent intent) {
850 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700851 synchronized (mUidRulesFirstLock) {
852 updatePowerSaveWhitelistUL();
853 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700854 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700855 }
856 }
857 };
858
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700859 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700860 @Override
861 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700862 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700863
864 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700865 final int uid = intent.getIntExtra(EXTRA_UID, -1);
866 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700867
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700868 if (ACTION_PACKAGE_ADDED.equals(action)) {
869 // update rules for UID, since it might be subject to
870 // global background data policy
871 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700872 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700873 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700874 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700875 }
876 }
877 };
878
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700879 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700880 @Override
881 public void onReceive(Context context, Intent intent) {
882 // on background handler thread, and UID_REMOVED is protected
883
884 final int uid = intent.getIntExtra(EXTRA_UID, -1);
885 if (uid == -1) return;
886
887 // remove any policy and update rules to clean up
888 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700889 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700890 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700891 synchronized (mNetworkPoliciesSecondLock) {
892 writePolicyAL();
893 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700894 }
895 }
896 };
897
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700898 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700899 @Override
900 public void onReceive(Context context, Intent intent) {
901 // on background handler thread, and USER_ADDED and USER_REMOVED
902 // broadcasts are protected
903
904 final String action = intent.getAction();
905 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
906 if (userId == -1) return;
907
Amith Yamasani15e472352015-04-24 19:06:07 -0700908 switch (action) {
909 case ACTION_USER_REMOVED:
910 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700911 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800912 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700913 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700914 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800915 // Removing outside removeUserStateUL since that can also be called when
916 // user resets app preferences.
917 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700918 if (action == ACTION_USER_ADDED) {
919 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700920 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700921 }
922 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700923 synchronized (mNetworkPoliciesSecondLock) {
924 updateRulesForGlobalChangeAL(true);
925 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700926 }
927 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700928 }
929 }
930 };
931
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700932 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700933 * Receiver that watches for {@link INetworkStatsService} updates, which we
934 * use to check against {@link NetworkPolicy#warningBytes}.
935 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700936 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700937 @Override
938 public void onReceive(Context context, Intent intent) {
939 // on background handler thread, and verified
940 // READ_NETWORK_USAGE_HISTORY permission above.
941
Felipe Lemef0823852016-06-08 13:43:08 -0700942 synchronized (mNetworkPoliciesSecondLock) {
943 updateNetworkEnabledNL();
944 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700945 }
946 }
947 };
948
949 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700950 * Receiver that watches for {@link Notification} control of
951 * {@link #mRestrictBackground}.
952 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700953 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700954 @Override
955 public void onReceive(Context context, Intent intent) {
956 // on background handler thread, and verified MANAGE_NETWORK_POLICY
957 // permission above.
958
959 setRestrictBackground(false);
960 }
961 };
962
963 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800964 * Receiver that watches for {@link Notification} control of
965 * {@link NetworkPolicy#lastWarningSnooze}.
966 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700967 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800968 @Override
969 public void onReceive(Context context, Intent intent) {
970 // on background handler thread, and verified MANAGE_NETWORK_POLICY
971 // permission above.
972
973 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700974 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
975 performSnooze(template, TYPE_WARNING);
976 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
977 performSnooze(template, TYPE_RAPID);
978 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800979 }
980 };
981
982 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600983 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600984 * we can perform upgrade logic. After initial upgrade logic, it updates
985 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700986 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600987 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700988 @Override
989 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900990 synchronized (mUidRulesFirstLock) {
991 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600992 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600993 }
994 }
995 // Only need to perform upgrade logic once
996 mContext.unregisterReceiver(this);
997 }
998 };
999
1000 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1001 @Override
1002 public void onCapabilitiesChanged(Network network,
1003 NetworkCapabilities networkCapabilities) {
1004 if (network == null || networkCapabilities == null) return;
1005
1006 synchronized (mNetworkPoliciesSecondLock) {
1007 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1008 final boolean newMetered = !networkCapabilities
1009 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1010
1011 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001012 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001013 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001014 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001015 }
1016 }
1017 }
1018 };
1019
1020 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001021 * Observer that watches for {@link INetworkManagementService} alerts.
1022 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001023 final private INetworkManagementEventObserver mAlertObserver
1024 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 @Override
1026 public void limitReached(String limitName, String iface) {
1027 // only someone like NMS should be calling us
1028 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1029
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001030 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1031 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 }
1033 }
1034 };
1035
1036 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001037 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1038 * to show visible notifications as needed.
1039 */
Felipe Lemef0823852016-06-08 13:43:08 -07001040 void updateNotificationsNL() {
1041 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001043 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001044 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046
1047 // TODO: when switching to kernel notifications, compute next future
1048 // cycle boundary to recompute notifications.
1049
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001050 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001051 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001052 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1053 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 // ignore policies that aren't relevant to user
1055 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001056 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001057
Jeff Sharkey53313d72017-07-13 16:47:32 -06001058 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1059 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001060 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1061 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1062 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001064 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001065 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001066 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1067 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001068 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001070 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001071 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001072 }
1073
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001075 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001076
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001077 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1078 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001079 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001080 }
1081 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001082
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001083 // Warn if average usage over last 4 days is on track to blow pretty
1084 // far past the plan limits.
1085 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001086 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001087 final long recentStart = now - recentDuration;
1088 final long recentEnd = now;
1089 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001090
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001091 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001092 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001093 final long alertBytes = (policy.limitBytes * 3) / 2;
1094
1095 if (LOGD) {
1096 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1097 + projectedBytes + " alert " + alertBytes);
1098 }
1099
1100 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1101 - DateUtils.DAY_IN_MILLIS;
1102 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001103 enqueueNotification(policy, TYPE_RAPID, 0,
1104 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001105 }
1106 }
1107 }
1108
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001109 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001110 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001111 final NotificationId notificationId = beforeNotifs.valueAt(i);
1112 if (!mActiveNotifs.contains(notificationId)) {
1113 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 }
1115 }
1116 }
1117
1118 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001119 * Attempt to find a specific app to blame for rapid data usage during the
1120 * given time period.
1121 */
1122 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1123 long start, long end) {
1124 long totalBytes = 0;
1125 long maxBytes = 0;
1126 int maxUid = 0;
1127
1128 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1129 NetworkStats.Entry entry = null;
1130 for (int i = 0; i < stats.size(); i++) {
1131 entry = stats.getValues(i, entry);
1132 final long bytes = entry.rxBytes + entry.txBytes;
1133 totalBytes += bytes;
1134 if (bytes > maxBytes) {
1135 maxBytes = bytes;
1136 maxUid = entry.uid;
1137 }
1138 }
1139
1140 // Only point blame if the majority of usage was done by a single app.
1141 // TODO: support shared UIDs
1142 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1143 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
1144 if (packageNames.length == 1) {
1145 try {
1146 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1147 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1148 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1149 } catch (NameNotFoundException ignored) {
1150 }
1151 }
1152 }
1153
1154 return null;
1155 }
1156
1157 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001158 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001159 * current device state, such as when
1160 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1161 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001162 */
1163 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001164 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001165 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1166 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001167
Jeff Sharkey32566012014-12-02 18:30:14 -08001168 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001169 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001170 for (int subId : subIds) {
1171 final String subscriberId = tele.getSubscriberId(subId);
1172 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001173 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1174 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001175 if (template.matches(probeIdent)) {
1176 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001177 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001178 }
1179 return false;
1180 } else {
1181 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001182 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001183 }
1184
1185 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001186 * Notify that given {@link NetworkTemplate} is over
1187 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1188 */
Felipe Lemef0823852016-06-08 13:43:08 -07001189 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001191 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192 mOverLimitNotified.add(template);
1193 }
1194 }
1195
Felipe Lemef0823852016-06-08 13:43:08 -07001196 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 mOverLimitNotified.remove(template);
1198 }
1199
1200 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001201 * Show notification for combined {@link NetworkPolicy} and specific type,
1202 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1203 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001204 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1205 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001206 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001207 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001209 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001210 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001211 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001212 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001213
1214 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001215 final CharSequence title;
1216 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001217 switch (type) {
1218 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001219 title = res.getText(R.string.data_usage_warning_title);
1220 body = res.getString(R.string.data_usage_warning_body,
1221 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001222
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001223 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001224
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001225 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1226 builder.setDeleteIntent(PendingIntent.getBroadcast(
1227 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1228
Wei Liu546cb772016-07-21 16:19:01 -07001229 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001230 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001231 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1232
Jeff Sharkey497e4432011-06-14 17:27:29 -07001233 break;
1234 }
1235 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001236 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001237 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001238 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001239 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 case MATCH_WIFI:
1241 title = res.getText(R.string.data_usage_wifi_limit_title);
1242 break;
1243 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001244 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001245 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001247
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001248 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001249 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001250
Wei Liu546cb772016-07-21 16:19:01 -07001251 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001252 builder.setContentIntent(PendingIntent.getActivity(
1253 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1254 break;
1255 }
1256 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001257 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001258 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001259 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1260 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001261 case MATCH_WIFI:
1262 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1263 break;
1264 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001265 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001266 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001267 final long overBytes = totalBytes - policy.limitBytes;
1268 body = res.getString(R.string.data_usage_limit_snoozed_body,
1269 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001270
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001271 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001272 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001273 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001274
Wei Liu546cb772016-07-21 16:19:01 -07001275 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001276 builder.setContentIntent(PendingIntent.getActivity(
1277 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001278 break;
1279 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001280 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001281 title = res.getText(R.string.data_usage_rapid_title);
1282 if (rapidBlame != null) {
1283 body = res.getString(R.string.data_usage_rapid_app_body,
1284 rapidBlame.loadLabel(mContext.getPackageManager()));
1285 } else {
1286 body = res.getString(R.string.data_usage_rapid_body);
1287 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001288
Jeff Sharkey2e471452018-01-19 18:02:47 +09001289 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001290
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001291 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1292 builder.setDeleteIntent(PendingIntent.getBroadcast(
1293 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1294
1295 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001296 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001297 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001298 break;
1299 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001300 default: {
1301 return;
1302 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001303 }
1304
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001305 builder.setTicker(title);
1306 builder.setContentTitle(title);
1307 builder.setContentText(body);
1308 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001309
1310 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1311 notificationId.getId(), builder.build(), UserHandle.ALL);
1312 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001313 }
1314
Chris Wren193ae6b2017-03-31 15:17:11 -04001315 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001316 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1317 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001318 }
1319
1320 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001322 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001323 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001324 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 @Override
1326 public void onReceive(Context context, Intent intent) {
1327 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1328 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001329
Hugo Benichi446c9c92017-04-10 09:41:10 +09001330 synchronized (mUidRulesFirstLock) {
1331 synchronized (mNetworkPoliciesSecondLock) {
1332 ensureActiveMobilePolicyAL();
1333 normalizePoliciesNL();
1334 updateNetworkEnabledNL();
1335 updateNetworkRulesNL();
1336 updateNotificationsNL();
1337 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001338 }
1339 }
1340 };
1341
Jeff Sharkey2e471452018-01-19 18:02:47 +09001342 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001343 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001344 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001345 final CountDownLatch latch = new CountDownLatch(1);
1346 mHandler.post(() -> {
1347 latch.countDown();
1348 });
1349 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001350 }
1351
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001352 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001353 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1354 * if necessary.
1355 *
1356 * @param subId that has its associated NetworkPolicy updated if necessary
1357 * @return if any policies were updated
1358 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001359 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1360 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001361
1362 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001363 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1364 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001365
1366 // find and update the mobile NetworkPolicy for this subscriber id
1367 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001368 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001369 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1370 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1371 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001372 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1373 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001374 }
1375 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001376 return policyUpdated;
1377 }
1378
1379 /**
1380 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1381 *
1382 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1383 * to do so, it returns the fallback value.
1384 *
1385 * @param config The CarrierConfig to read the value from.
1386 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1387 * @return cycleDay to use in the mobile NetworkPolicy.
1388 */
1389 @VisibleForTesting
1390 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1391 int fallbackCycleDay) {
1392 if (config == null) {
1393 return fallbackCycleDay;
1394 }
1395 int cycleDay =
1396 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1397 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1398 return fallbackCycleDay;
1399 }
1400 // validate cycleDay value
1401 final Calendar cal = Calendar.getInstance();
1402 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1403 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1404 Slog.e(TAG, "Invalid date in "
1405 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1406 return fallbackCycleDay;
1407 }
1408 return cycleDay;
1409 }
1410
1411 /**
1412 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1413 *
1414 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1415 * to do so, it returns the fallback value.
1416 *
1417 * @param config The CarrierConfig to read the value from.
1418 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1419 * @return warningBytes to use in the mobile NetworkPolicy.
1420 */
1421 @VisibleForTesting
1422 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1423 long fallbackWarningBytes) {
1424 if (config == null) {
1425 return fallbackWarningBytes;
1426 }
1427 long warningBytes =
1428 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1429
1430 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1431 return WARNING_DISABLED;
1432 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1433 return getPlatformDefaultWarningBytes();
1434 } else if (warningBytes < 0) {
1435 Slog.e(TAG, "Invalid value in "
1436 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1437 + "non-negative value but got: " + warningBytes);
1438 return fallbackWarningBytes;
1439 }
1440
1441 return warningBytes;
1442 }
1443
1444 /**
1445 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1446 *
1447 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1448 * to do so, it returns the fallback value.
1449 *
1450 * @param config The CarrierConfig to read the value from.
1451 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1452 * @return limitBytes to use in the mobile NetworkPolicy.
1453 */
1454 @VisibleForTesting
1455 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1456 long fallbackLimitBytes) {
1457 if (config == null) {
1458 return fallbackLimitBytes;
1459 }
1460 long limitBytes =
1461 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1462
1463 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1464 return LIMIT_DISABLED;
1465 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1466 return getPlatformDefaultLimitBytes();
1467 } else if (limitBytes < 0) {
1468 Slog.e(TAG, "Invalid value in "
1469 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1470 + "non-negative value but got: " + limitBytes);
1471 return fallbackLimitBytes;
1472 }
1473 return limitBytes;
1474 }
1475
1476 /**
1477 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1478 */
1479 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1480 @Override
1481 public void onReceive(Context context, Intent intent) {
1482 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1483 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1484
1485 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1486 return;
1487 }
1488 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001489 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001490 final String subscriberId = tele.getSubscriberId(subId);
1491
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001492 synchronized (mUidRulesFirstLock) {
1493 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001494 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001495 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001496 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001497 if (!updated) return;
1498 // update network and notification rules, as the data cycle changed and it's
1499 // possible that we should be triggering warnings/limits now
1500 handleNetworkPoliciesUpdateAL(true);
1501 }
1502 }
1503 }
1504 };
1505
1506 /**
1507 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1508 * one has been updated.
1509 *
1510 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1511 * update.
1512 */
1513 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1514 if (shouldNormalizePolicies) {
1515 normalizePoliciesNL();
1516 }
1517 updateNetworkEnabledNL();
1518 updateNetworkRulesNL();
1519 updateNotificationsNL();
1520 writePolicyAL();
1521 }
1522
1523 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001524 * Proactively control network data connections when they exceed
1525 * {@link NetworkPolicy#limitBytes}.
1526 */
Felipe Lemef0823852016-06-08 13:43:08 -07001527 void updateNetworkEnabledNL() {
1528 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001529
1530 // TODO: reset any policy-disabled networks when any policy is removed
1531 // completely, which is currently rare case.
1532
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001533 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1534 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001535 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001536 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001537 setNetworkTemplateEnabled(policy.template, true);
1538 continue;
1539 }
1540
Jeff Sharkey53313d72017-07-13 16:47:32 -06001541 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1542 .cycleIterator(policy).next();
1543 final long start = cycle.first.toInstant().toEpochMilli();
1544 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001545 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001546
1547 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001548 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1549 && policy.lastLimitSnooze < start;
1550 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001551
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001552 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001553 }
1554 }
1555
1556 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001557 * Proactively disable networks that match the given
1558 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001559 */
1560 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001561 // TODO: reach into ConnectivityManager to proactively disable bringing
1562 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001563
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001564 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001565 // If mobile data usage hits the limit or if the user resumes the data, we need to
1566 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001567 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1568 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001569
Jeff Sharkey2e471452018-01-19 18:02:47 +09001570 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001571 for (int subId : subIds) {
1572 final String subscriberId = tm.getSubscriberId(subId);
1573 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001574 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1575 true);
Jack Yu8781b682016-07-08 14:28:51 -07001576 // Template is matched when subscriber id matches.
1577 if (template.matches(probeIdent)) {
1578 tm.setPolicyDataEnabled(enabled, subId);
1579 }
1580 }
1581 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001582 }
1583
1584 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001585 * Collect all ifaces from a {@link NetworkState} into the given set.
1586 */
1587 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1588 final String baseIface = state.linkProperties.getInterfaceName();
1589 if (baseIface != null) {
1590 ifaces.add(baseIface);
1591 }
1592 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1593 final String stackedIface = stackedLink.getInterfaceName();
1594 if (stackedIface != null) {
1595 ifaces.add(stackedIface);
1596 }
1597 }
1598 }
1599
1600 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601 * Examine all connected {@link NetworkState}, looking for
1602 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1603 * remaining quota based on usage cycle and historical stats.
1604 */
Felipe Lemef0823852016-06-08 13:43:08 -07001605 void updateNetworkRulesNL() {
1606 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607
1608 final NetworkState[] states;
1609 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001610 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001612 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 return;
1614 }
1615
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001616 // First, generate identities of all connected networks so we can
1617 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001618 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001619 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001621 if (state.network != null) {
1622 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1623 }
Wei Liub8eaf452016-01-25 10:32:27 -08001624 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001625 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1626 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001627 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001628 }
1629 }
1630
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001631 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001632 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001633
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001634 // For every well-defined policy, compute remaining data based on
1635 // current cycle and historical stats, and push to kernel.
1636 final ArraySet<String> matchingIfaces = new ArraySet<>();
1637 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1638 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1639
1640 // Collect all ifaces that match this policy
1641 matchingIfaces.clear();
1642 for (int j = identified.size() - 1; j >= 0; j--) {
1643 if (policy.template.matches(identified.valueAt(j))) {
1644 collectIfaces(matchingIfaces, identified.keyAt(j));
1645 }
1646 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001649 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001650 }
1651
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001652 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001653 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001654 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001655 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001656 if (hasLimit && policy.hasCycle()) {
1657 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1658 .cycleIterator(policy).next();
1659 final long start = cycle.first.toInstant().toEpochMilli();
1660 final long end = cycle.second.toInstant().toEpochMilli();
1661 final long totalBytes = getTotalBytes(policy.template, start, end);
1662
1663 if (policy.lastLimitSnooze >= start) {
1664 // snoozing past quota, but we still need to restrict apps,
1665 // so push really high quota.
1666 quotaBytes = Long.MAX_VALUE;
1667 } else {
1668 // remaining "quota" bytes are based on total usage in
1669 // current cycle. kernel doesn't like 0-byte rules, so we
1670 // set 1-byte quota and disable the radio later.
1671 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1672 }
1673 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001674 // metered network, but no policy limit; we still need to
1675 // restrict apps, so push really high quota.
1676 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001677 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001678
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001679 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001680 // TODO: switch to shared quota once NMS supports
1681 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001682 }
1683
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001684 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1685 final String iface = matchingIfaces.valueAt(j);
1686 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001687 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001688 }
1689 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001690
1691 // keep track of lowest warning or limit of active policies
1692 if (hasWarning && policy.warningBytes < lowestRule) {
1693 lowestRule = policy.warningBytes;
1694 }
1695 if (hasLimit && policy.limitBytes < lowestRule) {
1696 lowestRule = policy.limitBytes;
1697 }
1698 }
1699
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001700 // One final pass to catch any metered ifaces that don't have explicitly
1701 // defined policies; typically Wi-Fi networks.
1702 for (NetworkState state : states) {
1703 if (state.networkInfo != null && state.networkInfo.isConnected()
1704 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1705 matchingIfaces.clear();
1706 collectIfaces(matchingIfaces, state);
1707 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1708 final String iface = matchingIfaces.valueAt(j);
1709 if (!newMeteredIfaces.contains(iface)) {
1710 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1711 newMeteredIfaces.add(iface);
1712 }
1713 }
1714 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001715 }
1716
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001717 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001718 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1719 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001720 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001721 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001722 }
1723 }
1724 mMeteredIfaces = newMeteredIfaces;
1725
Jeff Sharkey9252b342018-01-19 07:58:35 +09001726 // Finally, calculate our opportunistic quotas
1727 // TODO: add experiments support to disable or tweak ratios
1728 mSubscriptionOpportunisticQuota.clear();
1729 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001730 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001731 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001732 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001733 if (plan == null) continue;
1734
1735 // By default assume we have no quota
Jeff Sharkey9252b342018-01-19 07:58:35 +09001736 long quotaBytes = 0;
1737
Jeff Sharkey2e471452018-01-19 18:02:47 +09001738 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001739 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1740 // Ignore missing limits
Jeff Sharkey2e471452018-01-19 18:02:47 +09001741 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001742 // Unlimited data; let's use 20MiB/day (600MiB/month)
1743 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1744 } else {
1745 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001746 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001747 final long start = cycle.first.toInstant().toEpochMilli();
1748 final long end = cycle.second.toInstant().toEpochMilli();
1749 final long totalBytes = getTotalBytes(
1750 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1751 final long remainingBytes = limitBytes - totalBytes;
Jeff Sharkey9911a282018-02-14 22:29:11 -07001752 final long remainingDays = Math.max(1, (end - mClock.millis())
Jeff Sharkey9252b342018-01-19 07:58:35 +09001753 / TimeUnit.DAYS.toMillis(1));
1754 if (remainingBytes > 0) {
1755 quotaBytes = (remainingBytes / remainingDays) / 10;
1756 }
1757 }
1758
1759 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1760 }
1761
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001762 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001763 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001764
1765 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001766 }
1767
1768 /**
1769 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1770 * have at least a default mobile policy defined.
1771 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001772 private void ensureActiveMobilePolicyAL() {
1773 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001774 if (mSuppressDefaultPolicy) return;
1775
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001776 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1777 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001778
Jeff Sharkey2e471452018-01-19 18:02:47 +09001779 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001780 for (int subId : subIds) {
1781 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001782 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001783 }
1784 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001785
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001786 /**
1787 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1788 * have at least a default mobile policy defined.
1789 *
1790 * @param subId to build a default policy for
1791 * @param subscriberId that we check for an existing policy
1792 * @return true if a mobile network policy was added, or false one already existed.
1793 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001794 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001795 // Poke around to see if we already have a policy
1796 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001797 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001798 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1799 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1800 if (template.matches(probeIdent)) {
1801 if (LOGD) {
1802 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1803 + NetworkIdentity.scrubSubscriberId(subscriberId));
1804 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001805 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001806 }
1807 }
1808
Jeff Sharkey32566012014-12-02 18:30:14 -08001809 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1810 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001811 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001812 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001813 return true;
1814 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001815
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001816 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001817 final int dataWarningConfig = mContext.getResources().getInteger(
1818 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001819 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001820 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001821 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001822 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001823 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001824 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001825
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001826 private long getPlatformDefaultLimitBytes() {
1827 return LIMIT_DISABLED;
1828 }
1829
1830 @VisibleForTesting
1831 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001832 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001833 final RecurrenceRule cycleRule = NetworkPolicy
1834 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001835 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001836 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1837 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1838 synchronized (mUidRulesFirstLock) {
1839 synchronized (mNetworkPoliciesSecondLock) {
1840 updateDefaultMobilePolicyAL(subId, policy);
1841 }
1842 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001843 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001844 }
1845
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001846 /**
1847 * Update the given {@link NetworkPolicy} based on any carrier-provided
1848 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1849 * Leaves policy untouched if the user has modified it.
1850 *
1851 * @return if the policy was modified
1852 */
1853 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1854 if (!policy.inferred) {
1855 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1856 return false;
1857 }
1858
1859 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1860 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1861 policy.lastLimitSnooze, policy.metered, policy.inferred);
1862
1863 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1864 if (!ArrayUtils.isEmpty(plans)) {
1865 final SubscriptionPlan plan = plans[0];
1866 policy.cycleRule = plan.getCycleRule();
1867 final long planLimitBytes = plan.getDataLimitBytes();
1868 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1869 policy.warningBytes = getPlatformDefaultWarningBytes();
1870 policy.limitBytes = getPlatformDefaultLimitBytes();
1871 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1872 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1873 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1874 } else {
1875 policy.warningBytes = (planLimitBytes * 9) / 10;
1876 switch (plan.getDataLimitBehavior()) {
1877 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1878 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1879 policy.limitBytes = planLimitBytes;
1880 break;
1881 default:
1882 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1883 break;
1884 }
1885 }
1886 } else {
1887 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1888 final int currentCycleDay;
1889 if (policy.cycleRule.isMonthly()) {
1890 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1891 } else {
1892 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1893 }
1894 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1895 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1896 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1897 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1898 }
1899
1900 if (policy.equals(original)) {
1901 return false;
1902 } else {
1903 Slog.d(TAG, "Updated " + original + " to " + policy);
1904 return true;
1905 }
1906 }
1907
Felipe Lemef0823852016-06-08 13:43:08 -07001908 private void readPolicyAL() {
1909 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001910
1911 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001912 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001913 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001914 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001915 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001916
1917 FileInputStream fis = null;
1918 try {
1919 fis = mPolicyFile.openRead();
1920 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001921 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001922
Felipe Leme46b451f2016-08-19 08:46:17 -07001923 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1924 // to skip UIDs that were explicitly blacklisted.
1925 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1926
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001927 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001928 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001929 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001930 while ((type = in.next()) != END_DOCUMENT) {
1931 final String tag = in.getName();
1932 if (type == START_TAG) {
1933 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001934 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001935 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001936 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1937 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001938 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1939 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1940 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001941 final String networkId;
1942 if (version >= VERSION_ADDED_NETWORK_ID) {
1943 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1944 } else {
1945 networkId = null;
1946 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001947 final RecurrenceRule cycleRule;
1948 if (version >= VERSION_ADDED_CYCLE) {
1949 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1950 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1951 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1952 cycleRule = new RecurrenceRule(
1953 RecurrenceRule.convertZonedDateTime(start),
1954 RecurrenceRule.convertZonedDateTime(end),
1955 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001956 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001957 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1958 final String cycleTimezone;
1959 if (version >= VERSION_ADDED_TIMEZONE) {
1960 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1961 } else {
1962 cycleTimezone = "UTC";
1963 }
1964 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001965 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001966 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1967 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001968 final long lastLimitSnooze;
1969 if (version >= VERSION_SPLIT_SNOOZE) {
1970 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1971 } else if (version >= VERSION_ADDED_SNOOZE) {
1972 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001973 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001974 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001975 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001976 final boolean metered;
1977 if (version >= VERSION_ADDED_METERED) {
1978 metered = readBooleanAttribute(in, ATTR_METERED);
1979 } else {
1980 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001981 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001982 metered = true;
1983 break;
1984 default:
1985 metered = false;
1986 }
1987 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001988 final long lastWarningSnooze;
1989 if (version >= VERSION_SPLIT_SNOOZE) {
1990 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1991 } else {
1992 lastWarningSnooze = SNOOZE_NEVER;
1993 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001994 final boolean inferred;
1995 if (version >= VERSION_ADDED_INFERRED) {
1996 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1997 } else {
1998 inferred = false;
1999 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002000
Jeff Sharkey32566012014-12-02 18:30:14 -08002001 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2002 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002003 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002004 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2005 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002006 lastLimitSnooze, metered, inferred));
2007 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002008
2009 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2010 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2011 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2012 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2013 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2014 RecurrenceRule.convertZonedDateTime(start),
2015 RecurrenceRule.convertZonedDateTime(end),
2016 RecurrenceRule.convertPeriod(period));
2017 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2018 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2019
2020 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2021 SubscriptionPlan.BYTES_UNKNOWN);
2022 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2023 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2024 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2025 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2026 builder.setDataLimit(limitBytes, limitBehavior);
2027 }
2028
2029 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2030 SubscriptionPlan.BYTES_UNKNOWN);
2031 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2032 SubscriptionPlan.TIME_UNKNOWN);
2033 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2034 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2035 builder.setDataUsage(usageBytes, usageTime);
2036 }
2037
2038 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2039 final SubscriptionPlan plan = builder.build();
2040 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2041 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2042
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002043 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2044 mSubscriptionPlansOwner.put(subId, ownerPackage);
2045
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002046 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002047 final int uid = readIntAttribute(in, ATTR_UID);
2048 final int policy = readIntAttribute(in, ATTR_POLICY);
2049
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002050 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002051 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002052 } else {
2053 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2054 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002055 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002056 final int appId = readIntAttribute(in, ATTR_APP_ID);
2057 final int policy = readIntAttribute(in, ATTR_POLICY);
2058
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002059 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002060 // app policy is deprecated so this is only used in pre system user split.
2061 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002062 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002063 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002064 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002065 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002066 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002067 } else if (TAG_WHITELIST.equals(tag)) {
2068 insideWhitelist = true;
2069 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2070 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002071 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002072 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2073 final int uid = readIntAttribute(in, ATTR_UID);
2074 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002075 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002076 } else if (type == END_TAG) {
2077 if (TAG_WHITELIST.equals(tag)) {
2078 insideWhitelist = false;
2079 }
2080
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002081 }
2082 }
2083
Felipe Leme46b451f2016-08-19 08:46:17 -07002084 final int size = whitelistedRestrictBackground.size();
2085 for (int i = 0; i < size; i++) {
2086 final int uid = whitelistedRestrictBackground.keyAt(i);
2087 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2088 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2089 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2090 + " because its policy is " + uidPoliciesToString(policy));
2091 continue;
2092 }
2093 if (UserHandle.isApp(uid)) {
2094 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2095 if (LOGV)
2096 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2097 setUidPolicyUncheckedUL(uid, newPolicy, false);
2098 } else {
2099 Slog.w(TAG, "unable to update policy on UID " + uid);
2100 }
2101 }
2102
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002103 } catch (FileNotFoundException e) {
2104 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002105 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002106 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002107 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002108 } finally {
2109 IoUtils.closeQuietly(fis);
2110 }
2111 }
2112
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002113 /**
2114 * Upgrade legacy background data flags, notifying listeners of one last
2115 * change to always-true.
2116 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002117 private void upgradeDefaultBackgroundDataUL() {
2118 // This method is only called when we're unable to find the network policy flag, which
2119 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002120
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002121 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002122 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002123 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2124
2125 // NOTE: We used to read the legacy setting here :
2126 //
2127 // final int legacyFlagValue = Settings.Secure.getInt(
2128 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2129 //
2130 // This is no longer necessary because we will never upgrade directly from Gingerbread
2131 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2132 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002133 }
2134
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002135 /**
2136 * Perform upgrade step of moving any user-defined meterness overrides over
2137 * into {@link WifiConfiguration}.
2138 */
2139 private void upgradeWifiMeteredOverrideAL() {
2140 boolean modified = false;
2141 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2142 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2143 for (int i = 0; i < mNetworkPolicy.size(); ) {
2144 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2145 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2146 && !policy.inferred) {
2147 mNetworkPolicy.removeAt(i);
2148 modified = true;
2149
2150 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2151 for (WifiConfiguration config : configs) {
2152 if (Objects.equals(resolveNetworkId(config), networkId)) {
2153 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2154 config.meteredOverride = policy.metered
2155 ? WifiConfiguration.METERED_OVERRIDE_METERED
2156 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2157 wm.updateNetwork(config);
2158 }
2159 }
2160 } else {
2161 i++;
2162 }
2163 }
2164 if (modified) {
2165 writePolicyAL();
2166 }
2167 }
2168
Felipe Lemef0823852016-06-08 13:43:08 -07002169 void writePolicyAL() {
2170 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171
2172 FileOutputStream fos = null;
2173 try {
2174 fos = mPolicyFile.startWrite();
2175
2176 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002177 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002178 out.startDocument(null, true);
2179
2180 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002181 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002182 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002183
2184 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002185 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2186 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002187 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002188 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002189
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002190 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002191 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2192 final String subscriberId = template.getSubscriberId();
2193 if (subscriberId != null) {
2194 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002195 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002196 final String networkId = template.getNetworkId();
2197 if (networkId != null) {
2198 out.attribute(null, ATTR_NETWORK_ID, networkId);
2199 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002200 writeStringAttribute(out, ATTR_CYCLE_START,
2201 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2202 writeStringAttribute(out, ATTR_CYCLE_END,
2203 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2204 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2205 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002206 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2207 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002208 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2209 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002210 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002211 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002212 out.endTag(null, TAG_NETWORK_POLICY);
2213 }
2214
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002215 // write all known subscription plans
2216 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2217 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002218 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002219 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2220 if (ArrayUtils.isEmpty(plans)) continue;
2221
2222 for (SubscriptionPlan plan : plans) {
2223 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2224 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002225 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002226 final RecurrenceRule cycleRule = plan.getCycleRule();
2227 writeStringAttribute(out, ATTR_CYCLE_START,
2228 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2229 writeStringAttribute(out, ATTR_CYCLE_END,
2230 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2231 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2232 RecurrenceRule.convertPeriod(cycleRule.period));
2233 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2234 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2235 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2236 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2237 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2238 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2239 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2240 }
2241 }
2242
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002243 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002244 for (int i = 0; i < mUidPolicy.size(); i++) {
2245 final int uid = mUidPolicy.keyAt(i);
2246 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002247
Jeff Sharkey497e4432011-06-14 17:27:29 -07002248 // skip writing empty policies
2249 if (policy == POLICY_NONE) continue;
2250
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002251 out.startTag(null, TAG_UID_POLICY);
2252 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002253 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002254 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002255 }
2256
2257 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002258
2259 // write all whitelists
2260 out.startTag(null, TAG_WHITELIST);
2261
Felipe Lemea9505cc2016-02-26 10:28:41 -08002262 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002263 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002264 for (int i = 0; i < size; i++) {
2265 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2266 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2267 writeIntAttribute(out, ATTR_UID, uid);
2268 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2269 }
2270
Felipe Lemeb85a6372016-01-14 16:16:16 -08002271 out.endTag(null, TAG_WHITELIST);
2272
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002273 out.endDocument();
2274
2275 mPolicyFile.finishWrite(fos);
2276 } catch (IOException e) {
2277 if (fos != null) {
2278 mPolicyFile.failWrite(fos);
2279 }
2280 }
2281 }
2282
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002283 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002284 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002285 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002286
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002287 if (!UserHandle.isApp(uid)) {
2288 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002289 }
Felipe Lemef0823852016-06-08 13:43:08 -07002290 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002291 final long token = Binder.clearCallingIdentity();
2292 try {
2293 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2294 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002295 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002296 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002297 }
2298 } finally {
2299 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002300 }
2301 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002302 }
2303
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002304 @Override
2305 public void addUidPolicy(int uid, int policy) {
2306 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002307
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002308 if (!UserHandle.isApp(uid)) {
2309 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2310 }
2311
Felipe Lemef0823852016-06-08 13:43:08 -07002312 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002313 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2314 policy |= oldPolicy;
2315 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002316 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002317 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002318 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002319 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002320 }
2321
2322 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002323 public void removeUidPolicy(int uid, int policy) {
2324 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2325
2326 if (!UserHandle.isApp(uid)) {
2327 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2328 }
2329
Felipe Lemef0823852016-06-08 13:43:08 -07002330 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002331 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2332 policy = oldPolicy & ~policy;
2333 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002334 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002335 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002336 }
2337 }
2338 }
2339
Felipe Lemef0823852016-06-08 13:43:08 -07002340 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2341 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002342
Felipe Leme57e3d312016-08-23 14:42:52 -07002343 final boolean notifyApp;
2344 if (!isUidValidForWhitelistRules(uid)) {
2345 notifyApp = false;
2346 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002347 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2348 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2349 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2350 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002351 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2352 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002353 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2354 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2355 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2356 if (LOGD)
2357 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2358 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2359 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002360 notifyApp = wasBlocked != isBlocked;
2361 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002362 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2363 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002364 }
2365
Felipe Lemef0823852016-06-08 13:43:08 -07002366 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002367 if (policy == POLICY_NONE) {
2368 mUidPolicy.delete(uid);
2369 } else {
2370 mUidPolicy.put(uid, policy);
2371 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002372
2373 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002374 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002375 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002376 synchronized (mNetworkPoliciesSecondLock) {
2377 writePolicyAL();
2378 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002379 }
2380 }
2381
2382 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002383 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002384 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2385
Felipe Lemef0823852016-06-08 13:43:08 -07002386 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002387 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002388 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002389 }
2390
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002391 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002392 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002393 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2394
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002395 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002396 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002397 for (int i = 0; i < mUidPolicy.size(); i++) {
2398 final int uid = mUidPolicy.keyAt(i);
2399 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002400 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2401 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002402 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002403 }
2404 }
2405 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002406 return uids;
2407 }
2408
2409 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002410 * Removes any persistable state associated with given {@link UserHandle}, persisting
2411 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002412 */
Felipe Lemef0823852016-06-08 13:43:08 -07002413 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002414
Sudheer Shanka352dc572017-09-22 17:09:38 -07002415 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002416 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002417
Felipe Lemea110eec2016-04-29 09:58:06 -07002418 // Remove entries from revoked default restricted background UID whitelist
2419 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2420 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2421 if (UserHandle.getUserId(uid) == userId) {
2422 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002423 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002424 }
2425 }
2426
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002427 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002428 int[] uids = new int[0];
2429 for (int i = 0; i < mUidPolicy.size(); i++) {
2430 final int uid = mUidPolicy.keyAt(i);
2431 if (UserHandle.getUserId(uid) == userId) {
2432 uids = appendInt(uids, uid);
2433 }
2434 }
2435
2436 if (uids.length > 0) {
2437 for (int uid : uids) {
2438 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002439 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002440 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002441 }
Felipe Lemef0823852016-06-08 13:43:08 -07002442 synchronized (mNetworkPoliciesSecondLock) {
2443 updateRulesForGlobalChangeAL(true);
2444 if (writePolicy && changed) {
2445 writePolicyAL();
2446 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002447 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002448 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002449 }
2450
2451 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002452 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002453 // TODO: create permission for observing network policy
2454 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002455 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002456 }
2457
2458 @Override
2459 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002460 // TODO: create permission for observing network policy
2461 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002462 mListeners.unregister(listener);
2463 }
2464
Jeff Sharkey1b861272011-05-22 00:34:52 -07002465 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002466 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002467 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2468
Felipe Leme6a05eee2016-02-19 14:43:51 -08002469 final long token = Binder.clearCallingIdentity();
2470 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002471 synchronized (mUidRulesFirstLock) {
2472 synchronized (mNetworkPoliciesSecondLock) {
2473 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002474 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002475 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002476 }
2477 } finally {
2478 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002479 }
2480 }
2481
Hugo Benichi446c9c92017-04-10 09:41:10 +09002482 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002483 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002484 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2485 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002486 }
2487
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002488 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002489 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002490 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002491 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002492 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2493 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2494 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002495 } catch (SecurityException e) {
2496 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002497
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002498 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2499 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2500 return new NetworkPolicy[0];
2501 }
Svet Ganov16a16892015-04-16 10:32:04 -07002502 }
2503
Felipe Lemef0823852016-06-08 13:43:08 -07002504 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002505 final int size = mNetworkPolicy.size();
2506 final NetworkPolicy[] policies = new NetworkPolicy[size];
2507 for (int i = 0; i < size; i++) {
2508 policies[i] = mNetworkPolicy.valueAt(i);
2509 }
2510 return policies;
2511 }
2512 }
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 private void normalizePoliciesNL() {
2515 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002516 }
2517
Felipe Lemef0823852016-06-08 13:43:08 -07002518 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002519 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002520 final String[] merged = tele.getMergedSubscriberIds();
2521
2522 mNetworkPolicy.clear();
2523 for (NetworkPolicy policy : policies) {
2524 // When two normalized templates conflict, prefer the most
2525 // restrictive policy
2526 policy.template = NetworkTemplate.normalize(policy.template, merged);
2527 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2528 if (existing == null || existing.compareTo(policy) > 0) {
2529 if (existing != null) {
2530 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2531 }
2532 mNetworkPolicy.put(policy.template, policy);
2533 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002534 }
2535 }
2536
2537 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002538 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002539 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002540
2541 final long token = Binder.clearCallingIdentity();
2542 try {
2543 performSnooze(template, TYPE_LIMIT);
2544 } finally {
2545 Binder.restoreCallingIdentity(token);
2546 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002547 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002548
Dianne Hackborn497175b2014-07-01 12:56:08 -07002549 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002550 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002551 synchronized (mUidRulesFirstLock) {
2552 synchronized (mNetworkPoliciesSecondLock) {
2553 // find and snooze local policy that matches
2554 final NetworkPolicy policy = mNetworkPolicy.get(template);
2555 if (policy == null) {
2556 throw new IllegalArgumentException("unable to find policy for " + template);
2557 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002558
Felipe Lemef0823852016-06-08 13:43:08 -07002559 switch (type) {
2560 case TYPE_WARNING:
2561 policy.lastWarningSnooze = currentTime;
2562 break;
2563 case TYPE_LIMIT:
2564 policy.lastLimitSnooze = currentTime;
2565 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002566 case TYPE_RAPID:
2567 policy.lastRapidSnooze = currentTime;
2568 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002569 default:
2570 throw new IllegalArgumentException("unexpected type");
2571 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002572
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002573 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002574 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002575 }
2576 }
2577
2578 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002579 public void onTetheringChanged(String iface, boolean tethering) {
2580 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002581 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002582 if (mRestrictBackground && tethering) {
2583 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2584 setRestrictBackground(false);
2585 }
2586 }
2587 }
2588
2589 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002590 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002591 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002592 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002593 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2594 final long token = Binder.clearCallingIdentity();
2595 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002596 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002597 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002598 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002599 } finally {
2600 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002601 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002602 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002603 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002604 }
2605 }
2606
Felipe Lemef0823852016-06-08 13:43:08 -07002607 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002608 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002609 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002610 if (restrictBackground == mRestrictBackground) {
2611 // Ideally, UI should never allow this scenario...
2612 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002613 return;
2614 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002615 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2616 final boolean oldRestrictBackground = mRestrictBackground;
2617 mRestrictBackground = restrictBackground;
2618 // Must whitelist foreground apps before turning data saver mode on.
2619 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2620 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2621 updateRulesForRestrictBackgroundUL();
2622 try {
2623 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2624 Slog.e(TAG,
2625 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2626 mRestrictBackground = oldRestrictBackground;
2627 // TODO: if it knew the foreground apps (see TODO above), it could call
2628 // updateRulesForRestrictBackgroundUL() again to restore state.
2629 return;
2630 }
2631 } catch (RemoteException e) {
2632 // ignored; service lives in system_server
2633 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002634
Sudheer Shanka543339f2017-07-28 15:18:07 -07002635 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002636 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002637
2638 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2639 mRestrictBackgroundChangedInBsm = true;
2640 }
2641 synchronized (mNetworkPoliciesSecondLock) {
2642 updateNotificationsNL();
2643 writePolicyAL();
2644 }
2645 } finally {
2646 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002647 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002648 }
2649
2650 private void sendRestrictBackgroundChangedMsg() {
2651 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2652 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2653 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002654 }
2655
Felipe Lemeb85a6372016-01-14 16:16:16 -08002656 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002657 public int getRestrictBackgroundByCaller() {
2658 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2659 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002660
Felipe Lemef0823852016-06-08 13:43:08 -07002661 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002662 // Must clear identity because getUidPolicy() is restricted to system.
2663 final long token = Binder.clearCallingIdentity();
2664 final int policy;
2665 try {
2666 policy = getUidPolicy(uid);
2667 } finally {
2668 Binder.restoreCallingIdentity(token);
2669 }
2670 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2671 // App is blacklisted.
2672 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2673 }
Felipe Leme1b103232016-01-22 09:44:57 -08002674 if (!mRestrictBackground) {
2675 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2676 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002677 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002678 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2679 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2680 }
2681 }
2682
2683 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002684 public boolean getRestrictBackground() {
2685 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2686
Felipe Lemef0823852016-06-08 13:43:08 -07002687 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002688 return mRestrictBackground;
2689 }
2690 }
2691
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002692 @Override
2693 public void setDeviceIdleMode(boolean enabled) {
2694 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002695 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2696 try {
2697 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002698 if (mDeviceIdleMode == enabled) {
2699 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002700 }
Felipe Lemeea014392016-09-06 13:59:54 -07002701 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002702 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002703 if (mSystemReady) {
2704 // Device idle change means we need to rebuild rules for all
2705 // known apps, so do a global refresh.
2706 updateRulesForRestrictPowerUL();
2707 }
2708 }
2709 if (enabled) {
2710 EventLogTags.writeDeviceIdleOnPhase("net");
2711 } else {
2712 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002713 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002714 } finally {
2715 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002716 }
2717 }
2718
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002719 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002720 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002722 final long token = Binder.clearCallingIdentity();
2723 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002724 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2725 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2726 for (WifiConfiguration config : configs) {
2727 if (Objects.equals(resolveNetworkId(config), networkId)) {
2728 config.meteredOverride = meteredOverride;
2729 wm.updateNetwork(config);
2730 }
2731 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002732 } finally {
2733 Binder.restoreCallingIdentity(token);
2734 }
2735 }
2736
Jeff Sharkey46645002011-07-27 21:11:21 -07002737 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002738 @Deprecated
2739 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2740 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2741 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2742 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002743 }
2744
Jeff Sharkey53313d72017-07-13 16:47:32 -06002745 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2746 // Verify they're not lying about package name
2747 mAppOps.checkPackage(callingUid, callingPackage);
2748
Jeff Sharkey53313d72017-07-13 16:47:32 -06002749 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002750 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002751 final long token = Binder.clearCallingIdentity();
2752 try {
2753 si = mContext.getSystemService(SubscriptionManager.class)
2754 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002755 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002756 } finally {
2757 Binder.restoreCallingIdentity(token);
2758 }
2759
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002760 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002761 if (si != null) {
2762 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2763 return;
2764 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002765 }
2766
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002767 // Second check: has the CarrierService delegated access?
2768 if (config != null) {
2769 final String overridePackage = config
2770 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2771 if (!TextUtils.isEmpty(overridePackage)
2772 && Objects.equals(overridePackage, callingPackage)) {
2773 return;
2774 }
2775 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002776
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002777 // Third check: is caller the fallback/default CarrierService?
2778 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2779 if (!TextUtils.isEmpty(defaultPackage)
2780 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002781 return;
2782 }
2783
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002784 // Fourth check: is caller a testing app on a debug build?
2785 final boolean enableDebug = Build.IS_USERDEBUG || Build.IS_ENG;
2786 if (enableDebug && callingPackage
2787 .equals(SystemProperties.get("fw.sub_plan_owner." + subId, null))) {
2788 return;
2789 }
2790
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002791 // Final check: does the caller hold a permission?
2792 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002793 }
2794
2795 @Override
2796 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2797 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2798
Jeff Sharkey53313d72017-07-13 16:47:32 -06002799 final String fake = SystemProperties.get("fw.fake_plan");
2800 if (!TextUtils.isEmpty(fake)) {
2801 final List<SubscriptionPlan> plans = new ArrayList<>();
2802 if ("month_hard".equals(fake)) {
2803 plans.add(SubscriptionPlan.Builder
2804 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2805 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002806 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2807 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2808 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2809 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2810 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002811 plans.add(SubscriptionPlan.Builder
2812 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2813 .setTitle("G-Mobile Happy")
2814 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2815 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2816 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2817 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2818 .build());
2819 plans.add(SubscriptionPlan.Builder
2820 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2821 .setTitle("G-Mobile, Charged after limit")
2822 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2823 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2824 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2825 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2826 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002827 } else if ("month_soft".equals(fake)) {
2828 plans.add(SubscriptionPlan.Builder
2829 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2830 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2831 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2832 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002833 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2834 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2835 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2836 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2837 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002838 plans.add(SubscriptionPlan.Builder
2839 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2840 .setTitle("G-Mobile, Throttled after limit")
2841 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2842 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2843 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2844 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2845 .build());
2846 plans.add(SubscriptionPlan.Builder
2847 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2848 .setTitle("G-Mobile, No data connection after limit")
2849 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2850 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2851 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2852 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2853 .build());
2854
Jeff Sharkey53313d72017-07-13 16:47:32 -06002855 } else if ("month_none".equals(fake)) {
2856 plans.add(SubscriptionPlan.Builder
2857 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2858 .setTitle("G-Mobile")
2859 .build());
2860 } else if ("prepaid".equals(fake)) {
2861 plans.add(SubscriptionPlan.Builder
2862 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2863 ZonedDateTime.now().plusDays(10))
2864 .setTitle("G-Mobile")
2865 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2866 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2867 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2868 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2869 .build());
2870 } else if ("prepaid_crazy".equals(fake)) {
2871 plans.add(SubscriptionPlan.Builder
2872 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2873 ZonedDateTime.now().plusDays(10))
2874 .setTitle("G-Mobile Anytime")
2875 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2876 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2877 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2878 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2879 .build());
2880 plans.add(SubscriptionPlan.Builder
2881 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2882 ZonedDateTime.now().plusDays(20))
2883 .setTitle("G-Mobile Nickel Nights")
2884 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002885 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2886 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002887 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2888 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2889 .build());
2890 plans.add(SubscriptionPlan.Builder
2891 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2892 ZonedDateTime.now().plusDays(20))
2893 .setTitle("G-Mobile Bonus 3G")
2894 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002895 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002896 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2897 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2898 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2899 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002900 } else if ("unlimited".equals(fake)) {
2901 plans.add(SubscriptionPlan.Builder
2902 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2903 ZonedDateTime.now().plusDays(10))
2904 .setTitle("G-Mobile Awesome")
2905 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2906 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2907 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2908 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2909 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002910 }
2911 return plans.toArray(new SubscriptionPlan[plans.size()]);
2912 }
2913
Jeff Sharkey4635f102017-09-01 11:27:13 -06002914 synchronized (mNetworkPoliciesSecondLock) {
2915 // Only give out plan details to the package that defined them,
2916 // so that we don't risk leaking plans between apps. We always
2917 // let in core system components (like the Settings app).
2918 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2919 if (Objects.equals(ownerPackage, callingPackage)
2920 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2921 return mSubscriptionPlans.get(subId);
2922 } else {
2923 Log.w(TAG, "Not returning plans because caller " + callingPackage
2924 + " doesn't match owner " + ownerPackage);
2925 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002926 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002927 }
2928 }
2929
2930 @Override
2931 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2932 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2933
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002934 for (SubscriptionPlan plan : plans) {
2935 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002936 }
2937
2938 final long token = Binder.clearCallingIdentity();
2939 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002940 synchronized (mUidRulesFirstLock) {
2941 synchronized (mNetworkPoliciesSecondLock) {
2942 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002943 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002944
2945 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2946 .getSubscriberId(subId);
2947 ensureActiveMobilePolicyAL(subId, subscriberId);
2948 maybeUpdateMobilePolicyCycleAL(subId);
2949 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002950 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002951 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002952
2953 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2954 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2955 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2956 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002957 } finally {
2958 Binder.restoreCallingIdentity(token);
2959 }
2960 }
2961
2962 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002963 public String getSubscriptionPlansOwner(int subId) {
2964 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2965 throw new SecurityException();
2966 }
2967
2968 synchronized (mNetworkPoliciesSecondLock) {
2969 return mSubscriptionPlansOwner.get(subId);
2970 }
2971 }
2972
2973 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09002974 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
2975 long timeoutMillis, String callingPackage) {
2976 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2977
2978 // We can only override when carrier told us about plans
2979 synchronized (mNetworkPoliciesSecondLock) {
2980 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
2981 throw new IllegalStateException(
2982 "Must provide SubscriptionPlan information before overriding");
2983 }
2984 }
2985
2986 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2987 overrideMask, overrideValue, subId));
2988 if (timeoutMillis > 0) {
2989 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2990 overrideMask, 0, subId), timeoutMillis);
2991 }
2992 }
2993
2994 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002995 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002996 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002997
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002998 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2999
Dianne Hackborn497175b2014-07-01 12:56:08 -07003000 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003001 for (String arg : args) {
3002 argSet.add(arg);
3003 }
3004
Felipe Lemef0823852016-06-08 13:43:08 -07003005 synchronized (mUidRulesFirstLock) {
3006 synchronized (mNetworkPoliciesSecondLock) {
3007 if (argSet.contains("--unsnooze")) {
3008 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3009 mNetworkPolicy.valueAt(i).clearSnooze();
3010 }
3011
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003012 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003013
3014 fout.println("Cleared snooze timestamps");
3015 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003016 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003017
Felipe Lemef0823852016-06-08 13:43:08 -07003018 fout.print("System ready: "); fout.println(mSystemReady);
3019 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3020 fout.print("Restrict power: "); fout.println(mRestrictPower);
3021 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003022 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3023
3024 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003025 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003026 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003027 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3028 fout.println(mNetworkPolicy.valueAt(i).toString());
3029 }
3030 fout.decreaseIndent();
3031
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003032 fout.println();
3033 fout.println("Subscription plans:");
3034 fout.increaseIndent();
3035 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3036 final int subId = mSubscriptionPlans.keyAt(i);
3037 fout.println("Subscriber ID " + subId + ":");
3038 fout.increaseIndent();
3039 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3040 if (!ArrayUtils.isEmpty(plans)) {
3041 for (SubscriptionPlan plan : plans) {
3042 fout.println(plan);
3043 }
3044 }
3045 fout.decreaseIndent();
3046 }
3047 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003048
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003049 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003050 fout.println("Policy for UIDs:");
3051 fout.increaseIndent();
3052 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003053 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003054 final int uid = mUidPolicy.keyAt(i);
3055 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003056 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003057 fout.print(uid);
3058 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003059 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003060 fout.println();
3061 }
3062 fout.decreaseIndent();
3063
3064 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3065 if (size > 0) {
3066 fout.println("Power save whitelist (except idle) app ids:");
3067 fout.increaseIndent();
3068 for (int i = 0; i < size; i++) {
3069 fout.print("UID=");
3070 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3071 fout.print(": ");
3072 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3073 fout.println();
3074 }
3075 fout.decreaseIndent();
3076 }
3077
3078 size = mPowerSaveWhitelistAppIds.size();
3079 if (size > 0) {
3080 fout.println("Power save whitelist app ids:");
3081 fout.increaseIndent();
3082 for (int i = 0; i < size; i++) {
3083 fout.print("UID=");
3084 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3085 fout.print(": ");
3086 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3087 fout.println();
3088 }
3089 fout.decreaseIndent();
3090 }
3091
Felipe Lemef0823852016-06-08 13:43:08 -07003092 size = mDefaultRestrictBackgroundWhitelistUids.size();
3093 if (size > 0) {
3094 fout.println("Default restrict background whitelist uids:");
3095 fout.increaseIndent();
3096 for (int i = 0; i < size; i++) {
3097 fout.print("UID=");
3098 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3099 fout.println();
3100 }
3101 fout.decreaseIndent();
3102 }
3103
3104 size = mRestrictBackgroundWhitelistRevokedUids.size();
3105 if (size > 0) {
3106 fout.println("Default restrict background whitelist uids revoked by users:");
3107 fout.increaseIndent();
3108 for (int i = 0; i < size; i++) {
3109 fout.print("UID=");
3110 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3111 fout.println();
3112 }
3113 fout.decreaseIndent();
3114 }
3115
3116 final SparseBooleanArray knownUids = new SparseBooleanArray();
3117 collectKeys(mUidState, knownUids);
3118 collectKeys(mUidRules, knownUids);
3119
3120 fout.println("Status for all known UIDs:");
3121 fout.increaseIndent();
3122 size = knownUids.size();
3123 for (int i = 0; i < size; i++) {
3124 final int uid = knownUids.keyAt(i);
3125 fout.print("UID=");
3126 fout.print(uid);
3127
3128 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3129 fout.print(" state=");
3130 fout.print(state);
3131 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3132 fout.print(" (fg)");
3133 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003134 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003135 ? " (fg svc)" : " (bg)");
3136 }
3137
3138 final int uidRules = mUidRules.get(uid, RULE_NONE);
3139 fout.print(" rules=");
3140 fout.print(uidRulesToString(uidRules));
3141 fout.println();
3142 }
3143 fout.decreaseIndent();
3144
3145 fout.println("Status for just UIDs with rules:");
3146 fout.increaseIndent();
3147 size = mUidRules.size();
3148 for (int i = 0; i < size; i++) {
3149 final int uid = mUidRules.keyAt(i);
3150 fout.print("UID=");
3151 fout.print(uid);
3152 final int uidRules = mUidRules.get(uid, RULE_NONE);
3153 fout.print(" rules=");
3154 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003155 fout.println();
3156 }
3157 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003158
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003159 fout.println("Admin restricted uids for metered data:");
3160 fout.increaseIndent();
3161 size = mMeteredRestrictedUids.size();
3162 for (int i = 0; i < size; ++i) {
3163 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3164 fout.println(mMeteredRestrictedUids.valueAt(i));
3165 }
3166 fout.decreaseIndent();
3167
Sudheer Shanka352dc572017-09-22 17:09:38 -07003168 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003169 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003170 }
3171 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003172
3173 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003174 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003175 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003176 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003177 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003178 }
3179
3180 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003181 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003182 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3183
Felipe Lemef0823852016-06-08 13:43:08 -07003184 synchronized (mUidRulesFirstLock) {
3185 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003186 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003187 }
3188
Felipe Lemef0823852016-06-08 13:43:08 -07003189 private boolean isUidForegroundUL(int uid) {
3190 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003191 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3192 }
3193
Felipe Lemef0823852016-06-08 13:43:08 -07003194 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003195 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003196 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003197 }
3198
Felipe Lemef0823852016-06-08 13:43:08 -07003199 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003200 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3201 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3202 }
3203
Felipe Lemef0823852016-06-08 13:43:08 -07003204 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003205 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003206 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003207 }
3208
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003209 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003210 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003211 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3212 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003213 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003214 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003215 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3216 try {
3217 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3218 if (oldUidState != uidState) {
3219 // state changed, push updated rules
3220 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003221 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3222 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3223 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003224 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003225 if (mDeviceIdleMode) {
3226 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003227 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003228 if (mRestrictPower) {
3229 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003230 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003231 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003232 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003233 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003234 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003235 } finally {
3236 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003237 }
3238 }
3239
Felipe Lemef0823852016-06-08 13:43:08 -07003240 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003241 final int index = mUidState.indexOfKey(uid);
3242 if (index >= 0) {
3243 final int oldUidState = mUidState.valueAt(index);
3244 mUidState.removeAt(index);
3245 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003246 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003247 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003248 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003249 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003250 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003251 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003252 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003253 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003254 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003255 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003256 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003257 }
3258 }
3259
Felipe Lemef28983d2016-03-25 12:18:23 -07003260 // adjust stats accounting based on foreground status
3261 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003262 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3263 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3264 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3265 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003266 try {
3267 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003268 } finally {
3269 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003270 }
3271 }
3272
Sudheer Shankac9d94072017-02-22 22:13:55 +00003273 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3274 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003275 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003276 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003277 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003278 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003279 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003280 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003281 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003282 }
3283
Felipe Lemef0823852016-06-08 13:43:08 -07003284 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003285 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3286 try {
3287 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3288 mUidFirewallPowerSaveRules);
3289 } finally {
3290 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3291 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003292 }
3293
Felipe Lemef0823852016-06-08 13:43:08 -07003294 void updateRuleForRestrictPowerUL(int uid) {
3295 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003296 }
3297
Felipe Lemef0823852016-06-08 13:43:08 -07003298 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003299 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3300 try {
3301 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3302 mUidFirewallDozableRules);
3303 } finally {
3304 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3305 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003306 }
3307
Felipe Lemef0823852016-06-08 13:43:08 -07003308 void updateRuleForDeviceIdleUL(int uid) {
3309 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003310 }
3311
Felipe Lemef28983d2016-03-25 12:18:23 -07003312 // NOTE: since both fw_dozable and fw_powersave uses the same map
3313 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003314 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003315 SparseIntArray rules) {
3316 if (enabled) {
3317 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003318 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003319 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003320 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003321 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003322 for (int ui = users.size() - 1; ui >= 0; ui--) {
3323 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003324 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3325 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3326 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3327 updateRulesForWhitelistedAppIds(uidRules,
3328 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003329 }
3330 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003331 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003332 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003333 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3334 }
3335 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003336 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003337 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003338 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003339 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003340 }
3341
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003342 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3343 final SparseBooleanArray whitelistedAppIds, int userId) {
3344 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3345 if (whitelistedAppIds.valueAt(i)) {
3346 final int appId = whitelistedAppIds.keyAt(i);
3347 final int uid = UserHandle.getUid(userId, appId);
3348 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3349 }
3350 }
3351 }
3352
3353 /**
3354 * @param deviceIdleMode if true then we don't consider
3355 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3356 * whitelisted.
3357 */
3358 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003359 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003360 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3361 || mPowerSaveWhitelistAppIds.get(appId);
3362 if (!deviceIdleMode) {
3363 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3364 }
3365 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003366 }
3367
Felipe Lemef28983d2016-03-25 12:18:23 -07003368 // NOTE: since both fw_dozable and fw_powersave uses the same map
3369 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003370 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003371 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003372 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3373 chain == FIREWALL_CHAIN_DOZABLE);
3374 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003375 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003376 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003377 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003378 }
3379 }
3380 }
3381
Felipe Lemef0823852016-06-08 13:43:08 -07003382 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003383 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3384 try {
3385 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3386 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003387
Felipe Leme873a83a2016-09-07 11:34:10 -07003388 // Fully update the app idle firewall chain.
3389 final List<UserInfo> users = mUserManager.getUsers();
3390 for (int ui = users.size() - 1; ui >= 0; ui--) {
3391 UserInfo user = users.get(ui);
3392 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3393 for (int uid : idleUids) {
3394 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3395 // quick check: if this uid doesn't have INTERNET permission, it
3396 // doesn't have network access anyway, so it is a waste to mess
3397 // with it here.
3398 if (hasInternetPermissions(uid)) {
3399 uidRules.put(uid, FIREWALL_RULE_DENY);
3400 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003401 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003402 }
3403 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003404
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003405 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003406 } finally {
3407 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3408 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003409 }
3410
Felipe Lemef0823852016-06-08 13:43:08 -07003411 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003412 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003413
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003414 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3415 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3416 }
3417 try {
3418 int appId = UserHandle.getAppId(uid);
3419 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3420 && !isUidForegroundOnRestrictPowerUL(uid)) {
3421 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3422 } else {
3423 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3424 }
3425 } finally {
3426 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003427 }
3428 }
3429
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003430 /**
3431 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3432 * changed.
3433 */
Felipe Lemef0823852016-06-08 13:43:08 -07003434 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003435 boolean paroled = mUsageStats.isAppIdleParoleOn();
3436 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003437 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003438
3439 int ruleCount = mUidFirewallStandbyRules.size();
3440 for (int i = 0; i < ruleCount; i++) {
3441 int uid = mUidFirewallStandbyRules.keyAt(i);
3442 int oldRules = mUidRules.get(uid);
3443 if (enableChain) {
3444 // Chain wasn't enabled before and the other power-related
3445 // chains are whitelists, so we can clear the
3446 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3447 // the effective rules result in blocking network access.
3448 oldRules &= MASK_METERED_NETWORKS;
3449 } else {
3450 // Skip if it had no restrictions to begin with
3451 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3452 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003453 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3454 if (newUidRules == RULE_NONE) {
3455 mUidRules.delete(uid);
3456 } else {
3457 mUidRules.put(uid, newUidRules);
3458 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003459 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003460 }
3461
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003462 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003463 * Update rules that might be changed by {@link #mRestrictBackground},
3464 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003465 */
Felipe Lemef0823852016-06-08 13:43:08 -07003466 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003467 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3468 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3469 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3470 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003471 try {
Felipe Leme09700462016-09-08 09:33:48 -07003472 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003473 updateRulesForRestrictPowerUL();
3474 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003475
Felipe Leme873a83a2016-09-07 11:34:10 -07003476 // If the set of restricted networks may have changed, re-evaluate those.
3477 if (restrictedNetworksChanged) {
3478 normalizePoliciesNL();
3479 updateNetworkRulesNL();
3480 }
3481 } finally {
3482 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003483 }
3484 }
3485
Felipe Leme09700462016-09-08 09:33:48 -07003486 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003487 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003488 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3489 try {
3490 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003491 updateRulesForPowerSaveUL();
3492 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3493 } finally {
3494 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3495 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003496 }
3497
Felipe Lemef0823852016-06-08 13:43:08 -07003498 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003499 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3500 try {
3501 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3502 } finally {
3503 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3504 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003505 }
3506
3507 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3508 private static final int TYPE_RESTRICT_POWER = 2;
3509 @Retention(RetentionPolicy.SOURCE)
3510 @IntDef(flag = false, value = {
3511 TYPE_RESTRICT_BACKGROUND,
3512 TYPE_RESTRICT_POWER,
3513 })
3514 public @interface RestrictType {
3515 }
3516
3517 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003518 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003519 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3520 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3521 }
3522 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003523 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003524
3525 final PackageManager pm = mContext.getPackageManager();
3526 final List<UserInfo> users;
3527 final List<ApplicationInfo> apps;
3528
3529 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3530 try {
3531 users = mUserManager.getUsers();
3532 } finally {
3533 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3534 }
3535 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3536 try {
3537 apps = pm.getInstalledApplications(
3538 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3539 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3540 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3541 } finally {
3542 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3543 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003544
Felipe Leme873a83a2016-09-07 11:34:10 -07003545 final int usersSize = users.size();
3546 final int appsSize = apps.size();
3547 for (int i = 0; i < usersSize; i++) {
3548 final UserInfo user = users.get(i);
3549 for (int j = 0; j < appsSize; j++) {
3550 final ApplicationInfo app = apps.get(j);
3551 final int uid = UserHandle.getUid(user.id, app.uid);
3552 switch (type) {
3553 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003554 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003555 break;
3556 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003557 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003558 break;
3559 default:
3560 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3561 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003562 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003563 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003564 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003565 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003566 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003567 }
3568
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003569 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003570 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003571 final int numUsers = users.size();
3572 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003573 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003574 int uid = UserHandle.getUid(user.id, appId);
3575 // Update external firewall rules.
3576 updateRuleForAppIdleUL(uid);
3577 updateRuleForDeviceIdleUL(uid);
3578 updateRuleForRestrictPowerUL(uid);
3579 // Update internal rules.
3580 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003581 }
3582 }
3583
Felipe Leme70c57c22016-03-29 10:45:13 -07003584 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3585 // methods below could be merged into a isUidValidForRules() method.
3586 private boolean isUidValidForBlacklistRules(int uid) {
3587 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003588 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003589 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003590 return true;
3591 }
3592
3593 return false;
3594 }
3595
Felipe Leme70c57c22016-03-29 10:45:13 -07003596 private boolean isUidValidForWhitelistRules(int uid) {
3597 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3598 }
3599
Amith Yamasani15e472352015-04-24 19:06:07 -07003600 private boolean isUidIdle(int uid) {
3601 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3602 final int userId = UserHandle.getUserId(uid);
3603
songjinshi0655edd2016-05-18 19:55:32 +08003604 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003605 for (String packageName : packages) {
3606 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3607 return false;
3608 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003609 }
3610 }
3611 return true;
3612 }
3613
3614 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003615 * Checks if an uid has INTERNET permissions.
3616 * <p>
3617 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003618 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003619 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003620 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003621 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003622 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003623 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003624 }
3625 } catch (RemoteException e) {
3626 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003627 return true;
3628 }
3629
3630 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003631 * Clears all state - internal and external - associated with an UID.
3632 */
3633 private void onUidDeletedUL(int uid) {
3634 // First cleanup in-memory state synchronously...
3635 mUidRules.delete(uid);
3636 mUidPolicy.delete(uid);
3637 mUidFirewallStandbyRules.delete(uid);
3638 mUidFirewallDozableRules.delete(uid);
3639 mUidFirewallPowerSaveRules.delete(uid);
3640 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3641 mPowerSaveWhitelistAppIds.delete(uid);
3642 mPowerSaveTempWhitelistAppIds.delete(uid);
3643
3644 // ...then update iptables asynchronously.
3645 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3646 }
3647
3648 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003649 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003650 *
Felipe Leme781ba142016-05-09 16:24:48 -07003651 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003652 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003653 * <li>Doze mode
3654 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003655 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003656 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003657 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003658 *
3659 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003660 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003661 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003662 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003663 updateRuleForDeviceIdleUL(uid);
3664 updateRuleForAppIdleUL(uid);
3665 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003666
3667 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003668 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003669
3670 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003671 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003672 }
3673
Felipe Leme70c57c22016-03-29 10:45:13 -07003674 /**
3675 * Applies network rules to bandwidth controllers based on process state and user-defined
3676 * restrictions (blacklist / whitelist).
3677 *
3678 * <p>
3679 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3680 * networks:
3681 * <ul>
3682 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3683 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3684 * also blacklisted.
3685 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3686 * no UIDs other those whitelisted will have access.
3687 * <ul>
3688 *
3689 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3690 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3691 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3692 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003693 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003694 * {@link INetworkManagementService}, but this method should also be called in events (like
3695 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3696 * following rules should also be applied:
3697 *
3698 * <ul>
3699 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3700 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3701 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3702 * {@code bw_penalty_box}.
3703 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3704 * </ul>
3705 *
3706 * <p>For optimization, the rules are only applied on user apps that have internet access
3707 * permission, since there is no need to change the {@code iptables} rule if the app does not
3708 * have permission to use the internet.
3709 *
3710 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003711 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003712 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003713 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003714 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3715 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3716 "updateRulesForDataUsageRestrictionsUL: " + uid);
3717 }
3718 try {
3719 updateRulesForDataUsageRestrictionsULInner(uid);
3720 } finally {
3721 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3722 }
3723 }
3724
3725 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003726 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003727 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003728 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003729 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003730
Dianne Hackborn497175b2014-07-01 12:56:08 -07003731 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003732 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003733 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003734 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003735
Felipe Leme781ba142016-05-09 16:24:48 -07003736 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003737 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003738 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3739 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003740
Felipe Leme70c57c22016-03-29 10:45:13 -07003741 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003742 if (isRestrictedByAdmin) {
3743 newRule = RULE_REJECT_METERED;
3744 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003745 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3746 newRule = RULE_TEMPORARY_ALLOW_METERED;
3747 } else if (isWhitelisted) {
3748 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003749 }
3750 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003751 if (isBlacklisted) {
3752 newRule = RULE_REJECT_METERED;
3753 } else if (mRestrictBackground && isWhitelisted) {
3754 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003755 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003756 }
Felipe Leme781ba142016-05-09 16:24:48 -07003757 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003758
Felipe Lemef28983d2016-03-25 12:18:23 -07003759 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003760 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003761 + ": isForeground=" +isForeground
3762 + ", isBlacklisted=" + isBlacklisted
3763 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003764 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003765 + ", oldRule=" + uidRulesToString(oldRule)
3766 + ", newRule=" + uidRulesToString(newRule)
3767 + ", newUidRules=" + uidRulesToString(newUidRules)
3768 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003769 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003770
Felipe Leme46c4fc32016-05-04 09:21:43 -07003771 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003772 mUidRules.delete(uid);
3773 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003774 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003775 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003776
Felipe Leme70c57c22016-03-29 10:45:13 -07003777 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003778 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003779 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003780 // Temporarily whitelist foreground app, removing from blacklist if necessary
3781 // (since bw_penalty_box prevails over bw_happy_box).
3782
3783 setMeteredNetworkWhitelist(uid, true);
3784 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3785 // but ideally it should be just:
3786 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003787 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003788 setMeteredNetworkBlacklist(uid, false);
3789 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003790 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003791 // Remove temporary whitelist from app that is not on foreground anymore.
3792
3793 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3794 // but ideally they should be just:
3795 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3796 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003797 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003798 setMeteredNetworkWhitelist(uid, false);
3799 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003800 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003801 setMeteredNetworkBlacklist(uid, true);
3802 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003803 } else if (hasRule(newRule, RULE_REJECT_METERED)
3804 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003805 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003806 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003807 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003808 // Since blacklist prevails over whitelist, we need to handle the special case
3809 // where app is whitelisted and blacklisted at the same time (although such
3810 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003811 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003812 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003813 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3814 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003815 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003816 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003817 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003818 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003819 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3820 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003821 + ", whitelisted=" + isWhitelisted
3822 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003823 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003824 + ", newRule=" + uidRulesToString(newUidRules)
3825 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003826 }
Felipe Leme781ba142016-05-09 16:24:48 -07003827
Sudheer Shankac9d94072017-02-22 22:13:55 +00003828 // Dispatch changed rule to existing listeners.
3829 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003830 }
3831 }
3832
3833 /**
3834 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3835 * listeners in case of change.
3836 * <p>
3837 * There are 3 power-related rules that affects whether an app has background access on
3838 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3839 * restriction, it's added to the equivalent firewall chain:
3840 * <ul>
3841 * <li>App is idle: {@code fw_standby} firewall chain.
3842 * <li>Device is idle: {@code fw_dozable} firewall chain.
3843 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3844 * </ul>
3845 * <p>
3846 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3847 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3848 * <p>
3849 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3850 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003851 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003852 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3853
Sudheer Shankac9d94072017-02-22 22:13:55 +00003854 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003855
Sudheer Shankac9d94072017-02-22 22:13:55 +00003856 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003857 mUidRules.delete(uid);
3858 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003859 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003860 }
3861 }
3862
3863 /**
3864 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3865 *
3866 * @param uid the uid of the app to update rules for
3867 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3868 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3869 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003870 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003871 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003872 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003873 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3874 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3875 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3876 + (paroled ? "P" : "-"));
3877 }
3878 try {
3879 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3880 } finally {
3881 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3882 }
3883 }
3884
3885 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003886 if (!isUidValidForBlacklistRules(uid)) {
3887 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003888 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003889 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003890
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003891 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003892 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003893 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003894
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003895 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003896 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3897 int newRule = RULE_NONE;
3898
3899 // First step: define the new rule based on user restrictions and foreground state.
3900
3901 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3902 // by considering the foreground and non-foreground states.
3903 if (isForeground) {
3904 if (restrictMode) {
3905 newRule = RULE_ALLOW_ALL;
3906 }
3907 } else if (restrictMode) {
3908 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3909 }
3910
3911 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3912
3913 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003914 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003915 + ", isIdle: " + isIdle
3916 + ", mRestrictPower: " + mRestrictPower
3917 + ", mDeviceIdleMode: " + mDeviceIdleMode
3918 + ", isForeground=" + isForeground
3919 + ", isWhitelisted=" + isWhitelisted
3920 + ", oldRule=" + uidRulesToString(oldRule)
3921 + ", newRule=" + uidRulesToString(newRule)
3922 + ", newUidRules=" + uidRulesToString(newUidRules)
3923 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3924 }
3925
Felipe Leme781ba142016-05-09 16:24:48 -07003926 // Second step: notify listeners if state changed.
3927 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003928 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003929 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003930 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003931 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3932 } else {
3933 // All scenarios should have been covered above
3934 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3935 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003936 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003937 + ", newRule=" + uidRulesToString(newUidRules)
3938 + ", oldRule=" + uidRulesToString(oldUidRules));
3939 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003940 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003941 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003942
Sudheer Shankac9d94072017-02-22 22:13:55 +00003943 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003944 }
3945
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003946 private class AppIdleStateChangeListener
3947 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3948
3949 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08003950 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
3951 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003952 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003953 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3954 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003955 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003956 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003957 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003958 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003959 }
3960 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003961 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003962 }
3963
3964 @Override
3965 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003966 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003967 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003968 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003969 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003970 }
3971 }
3972
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003973 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3974 if (listener != null) {
3975 try {
3976 listener.onUidRulesChanged(uid, uidRules);
3977 } catch (RemoteException ignored) {
3978 }
3979 }
3980 }
3981
3982 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3983 String[] meteredIfaces) {
3984 if (listener != null) {
3985 try {
3986 listener.onMeteredIfacesChanged(meteredIfaces);
3987 } catch (RemoteException ignored) {
3988 }
3989 }
3990 }
3991
3992 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3993 boolean restrictBackground) {
3994 if (listener != null) {
3995 try {
3996 listener.onRestrictBackgroundChanged(restrictBackground);
3997 } catch (RemoteException ignored) {
3998 }
3999 }
4000 }
4001
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004002 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4003 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004004 if (listener != null) {
4005 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004006 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004007 } catch (RemoteException ignored) {
4008 }
4009 }
4010 }
4011
Jeff Sharkey9252b342018-01-19 07:58:35 +09004012 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4013 int overrideMask, int overrideValue) {
4014 if (listener != null) {
4015 try {
4016 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4017 } catch (RemoteException ignored) {
4018 }
4019 }
4020 }
4021
Makoto Onuki8e777332017-03-28 11:25:47 -07004022 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004023 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004024 public boolean handleMessage(Message msg) {
4025 switch (msg.what) {
4026 case MSG_RULES_CHANGED: {
4027 final int uid = msg.arg1;
4028 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004029 final int length = mListeners.beginBroadcast();
4030 for (int i = 0; i < length; i++) {
4031 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4032 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004033 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004034 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004035 return true;
4036 }
4037 case MSG_METERED_IFACES_CHANGED: {
4038 final String[] meteredIfaces = (String[]) msg.obj;
4039 final int length = mListeners.beginBroadcast();
4040 for (int i = 0; i < length; i++) {
4041 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004042 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004043 }
4044 mListeners.finishBroadcast();
4045 return true;
4046 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004047 case MSG_LIMIT_REACHED: {
4048 final String iface = (String) msg.obj;
4049
Felipe Lemef0823852016-06-08 13:43:08 -07004050 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004051 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004052 // force stats update to make sure we have
4053 // numbers that caused alert to trigger.
4054 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004055
Felipe Lemef0823852016-06-08 13:43:08 -07004056 updateNetworkEnabledNL();
4057 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004058 }
4059 }
4060 return true;
4061 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004062 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4063 final boolean restrictBackground = msg.arg1 != 0;
4064 final int length = mListeners.beginBroadcast();
4065 for (int i = 0; i < length; i++) {
4066 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004067 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004068 }
4069 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004070 final Intent intent =
4071 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4072 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4073 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4074 return true;
4075 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004076 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004077 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004078 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004079 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004080 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004081 final int length = mListeners.beginBroadcast();
4082 for (int i = 0; i < length; i++) {
4083 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004084 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004085 }
4086 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004087 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4088 if (notifyApp.booleanValue()) {
4089 broadcastRestrictBackgroundChanged(uid, notifyApp);
4090 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004091 return true;
4092 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004093 case MSG_ADVISE_PERSIST_THRESHOLD: {
4094 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004095 // make sure stats are recorded frequently enough; we aim
4096 // for 2MB threshold for 2GB/month rules.
4097 final long persistThreshold = lowestRule / 1000;
4098 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004099 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004100 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004101 case MSG_UPDATE_INTERFACE_QUOTA: {
4102 removeInterfaceQuota((String) msg.obj);
4103 // int params need to be stitched back into a long
4104 setInterfaceQuota((String) msg.obj,
4105 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4106 return true;
4107 }
4108 case MSG_REMOVE_INTERFACE_QUOTA: {
4109 removeInterfaceQuota((String) msg.obj);
4110 return true;
4111 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004112 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4113 resetUidFirewallRules(msg.arg1);
4114 return true;
4115 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004116 case MSG_SUBSCRIPTION_OVERRIDE: {
4117 final int overrideMask = msg.arg1;
4118 final int overrideValue = msg.arg2;
4119 final int subId = (int) msg.obj;
4120 final int length = mListeners.beginBroadcast();
4121 for (int i = 0; i < length; i++) {
4122 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4123 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4124 }
4125 mListeners.finishBroadcast();
4126 return true;
4127 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004128 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4129 final int userId = msg.arg1;
4130 final Set<String> packageNames = (Set<String>) msg.obj;
4131 setMeteredRestrictedPackagesInternal(packageNames, userId);
4132 return true;
4133 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004134 default: {
4135 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004136 }
4137 }
4138 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004139 };
4140
4141 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4142 @Override
4143 public boolean handleMessage(Message msg) {
4144 switch (msg.what) {
4145 case UID_MSG_STATE_CHANGED: {
4146 final int uid = msg.arg1;
4147 final int procState = msg.arg2;
4148 final long procStateSeq = (Long) msg.obj;
4149
4150 handleUidChanged(uid, procState, procStateSeq);
4151 return true;
4152 }
4153 case UID_MSG_GONE: {
4154 final int uid = msg.arg1;
4155 handleUidGone(uid);
4156 return true;
4157 }
4158 default: {
4159 return false;
4160 }
4161 }
4162 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004163
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004164 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004165
Makoto Onuki8e777332017-03-28 11:25:47 -07004166 void handleUidChanged(int uid, int procState, long procStateSeq) {
4167 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4168 try {
4169 synchronized (mUidRulesFirstLock) {
4170 // We received a uid state change callback, add it to the history so that it
4171 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004172 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004173 // Now update the network policy rules as per the updated uid state.
4174 updateUidStateUL(uid, procState);
4175 // Updating the network rules is done, so notify AMS about this.
4176 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4177 }
4178 } finally {
4179 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4180 }
4181 }
4182
4183 void handleUidGone(int uid) {
4184 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4185 try {
4186 synchronized (mUidRulesFirstLock) {
4187 removeUidStateUL(uid);
4188 }
4189 } finally {
4190 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4191 }
4192 }
4193
Felipe Leme57e3d312016-08-23 14:42:52 -07004194 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4195 final PackageManager pm = mContext.getPackageManager();
4196 final String[] packages = pm.getPackagesForUid(uid);
4197 if (packages != null) {
4198 final int userId = UserHandle.getUserId(uid);
4199 for (String packageName : packages) {
4200 final Intent intent =
4201 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4202 intent.setPackage(packageName);
4203 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4204 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4205 }
4206 }
4207 }
4208
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004209 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4210 // long quotaBytes split up into two ints to fit in message
4211 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4212 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4213 }
4214
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004215 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004216 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004217 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004218 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004219 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004220 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004221 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004222 }
4223 }
4224
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004225 private void removeInterfaceQuotaAsync(String iface) {
4226 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4227 }
4228
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004229 private void removeInterfaceQuota(String iface) {
4230 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004231 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004232 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004233 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004234 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004235 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004236 }
4237 }
4238
Felipe Leme70c57c22016-03-29 10:45:13 -07004239 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4240 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004241 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004242 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004243 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004244 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4245 } catch (RemoteException e) {
4246 // ignored; service lives in system_server
4247 }
4248 }
4249
4250 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4251 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4252 try {
4253 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4254 } catch (IllegalStateException e) {
4255 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, 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
Felipe Lemebc853dd2016-09-08 13:26:55 -07004261 private static final int CHAIN_TOGGLE_NONE = 0;
4262 private static final int CHAIN_TOGGLE_ENABLE = 1;
4263 private static final int CHAIN_TOGGLE_DISABLE = 2;
4264 @Retention(RetentionPolicy.SOURCE)
4265 @IntDef(flag = false, value = {
4266 CHAIN_TOGGLE_NONE,
4267 CHAIN_TOGGLE_ENABLE,
4268 CHAIN_TOGGLE_DISABLE
4269 })
4270 public @interface ChainToggleType {
4271 }
4272
4273 /**
4274 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004275 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004276 *
4277 * @param chain firewall chain.
4278 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4279 * @param toggle whether the chain should be enabled, disabled, or not changed.
4280 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004281 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004282 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004283 if (uidRules != null) {
4284 setUidFirewallRulesUL(chain, uidRules);
4285 }
4286 if (toggle != CHAIN_TOGGLE_NONE) {
4287 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4288 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004289 }
4290
Amith Yamasani15e472352015-04-24 19:06:07 -07004291 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004292 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4293 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4294 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004295 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004296 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004297 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004298 int size = uidRules.size();
4299 int[] uids = new int[size];
4300 int[] rules = new int[size];
4301 for(int index = size - 1; index >= 0; --index) {
4302 uids[index] = uidRules.keyAt(index);
4303 rules[index] = uidRules.valueAt(index);
4304 }
4305 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004306 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004307 } catch (IllegalStateException e) {
4308 Log.wtf(TAG, "problem setting firewall uid rules", e);
4309 } catch (RemoteException e) {
4310 // ignored; service lives in system_server
4311 }
4312 }
4313
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004314 /**
4315 * Add or remove a uid to the firewall blacklist for all network ifaces.
4316 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004317 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004318 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4319 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4320 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004321 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004322 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004323 if (chain == FIREWALL_CHAIN_DOZABLE) {
4324 mUidFirewallDozableRules.put(uid, rule);
4325 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4326 mUidFirewallStandbyRules.put(uid, rule);
4327 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4328 mUidFirewallPowerSaveRules.put(uid, rule);
4329 }
4330
4331 try {
4332 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004333 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004334 } catch (IllegalStateException e) {
4335 Log.wtf(TAG, "problem setting firewall uid rules", e);
4336 } catch (RemoteException e) {
4337 // ignored; service lives in system_server
4338 }
4339 } finally {
4340 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004341 }
4342 }
4343
4344 /**
4345 * Add or remove a uid to the firewall blacklist for all network ifaces.
4346 */
Felipe Lemef0823852016-06-08 13:43:08 -07004347 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004348 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4349 mFirewallChainStates.get(chain) == enable) {
4350 // All is the same, nothing to do.
4351 return;
4352 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004353 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004354 try {
4355 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004356 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004357 } catch (IllegalStateException e) {
4358 Log.wtf(TAG, "problem enable firewall chain", e);
4359 } catch (RemoteException e) {
4360 // ignored; service lives in system_server
4361 }
4362 }
4363
Felipe Leme03e95e22016-09-09 09:25:31 -07004364 /**
4365 * Resets all firewall rules associated with an UID.
4366 */
4367 private void resetUidFirewallRules(int uid) {
4368 try {
4369 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4370 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4371 mNetworkManager
4372 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4373 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4374 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4375 } catch (IllegalStateException e) {
4376 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4377 } catch (RemoteException e) {
4378 // ignored; service lives in system_server
4379 }
4380 }
4381
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004382 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004383 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004384 return getNetworkTotalBytes(template, start, end);
4385 }
4386
4387 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004388 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004389 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004390 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004391 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004392 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004393 }
4394 }
4395
4396 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4397 try {
4398 return mNetworkStats.getNetworkUidBytes(template, start, end);
4399 } catch (RuntimeException e) {
4400 Slog.w(TAG, "Failed to read network stats: " + e);
4401 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004402 }
4403 }
4404
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004405 private boolean isBandwidthControlEnabled() {
4406 final long token = Binder.clearCallingIdentity();
4407 try {
4408 return mNetworkManager.isBandwidthControlEnabled();
4409 } catch (RemoteException e) {
4410 // ignored; service lives in system_server
4411 return false;
4412 } finally {
4413 Binder.restoreCallingIdentity(token);
4414 }
4415 }
4416
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004417 private static Intent buildAllowBackgroundDataIntent() {
4418 return new Intent(ACTION_ALLOW_BACKGROUND);
4419 }
4420
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004421 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4422 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004423 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4424 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4425 return intent;
4426 }
4427
4428 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4429 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4430 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004431 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4432 return intent;
4433 }
4434
Wei Liu546cb772016-07-21 16:19:01 -07004435 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004436 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004437 intent.setComponent(ComponentName.unflattenFromString(
4438 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004439 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4440 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4441 return intent;
4442 }
4443
Wei Liu546cb772016-07-21 16:19:01 -07004444 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004445 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004446 intent.setComponent(ComponentName.unflattenFromString(
4447 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004448 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4449 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4450 return intent;
4451 }
4452
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004453 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004454 public void addIdleHandler(IdleHandler handler) {
4455 mHandler.getLooper().getQueue().addIdleHandler(handler);
4456 }
4457
jackqdyulei29c82ab2017-03-10 14:09:16 -08004458 @VisibleForTesting
4459 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4460 mRestrictBackgroundPowerState = result;
4461
4462 boolean restrictBackground = result.batterySaverEnabled;
4463 boolean shouldInvokeRestrictBackground;
4464 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4465 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4466
4467 if (result.globalBatterySaverEnabled) {
4468 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4469 // turn it on.
4470 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4471 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4472 localRestrictBgChangedInBsm = false;
4473 } else {
4474 // Try to restore the restrictBackground if it doesn't change in bsm
4475 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4476 restrictBackground = mRestrictBackgroundBeforeBsm;
4477 }
4478
4479 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004480 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004481 }
4482
4483 // Change it at last so setRestrictBackground() won't affect this variable
4484 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4485 }
4486
Jeff Sharkey1b861272011-05-22 00:34:52 -07004487 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4488 final int size = source.size();
4489 for (int i = 0; i < size; i++) {
4490 target.put(source.keyAt(i), true);
4491 }
4492 }
4493
Stuart Scottf1fb3972015-04-02 18:00:02 -07004494 @Override
4495 public void factoryReset(String subscriber) {
4496 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4497
Stuart Scotte3e314d2015-04-20 14:07:45 -07004498 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4499 return;
4500 }
4501
Stuart Scottf1fb3972015-04-02 18:00:02 -07004502 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004503 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004504 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4505 for (NetworkPolicy policy : policies) {
4506 if (policy.template.equals(template)) {
4507 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4508 policy.inferred = false;
4509 policy.clearSnooze();
4510 }
4511 }
4512 setNetworkPolicies(policies);
4513
4514 // Turn restrict background data off
4515 setRestrictBackground(false);
4516
Stuart Scotte3e314d2015-04-20 14:07:45 -07004517 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4518 // Remove app's "restrict background data" flag
4519 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4520 setUidPolicy(uid, POLICY_NONE);
4521 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004522 }
4523 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004524
Sudheer Shankab8f23162017-08-04 13:30:10 -07004525 @Override
4526 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4527 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4528 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4529 }
4530
4531 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4532 final int uidRules;
4533 final boolean isBackgroundRestricted;
4534 synchronized (mUidRulesFirstLock) {
4535 uidRules = mUidRules.get(uid, RULE_NONE);
4536 isBackgroundRestricted = mRestrictBackground;
4537 }
4538 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004539 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004540 return true;
4541 }
4542 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004543 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004544 return false;
4545 }
4546 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004547 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004548 return true;
4549 }
4550 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004551 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004552 return false;
4553 }
4554 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004555 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004556 return false;
4557 }
4558 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004559 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004560 return true;
4561 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004562 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004563 return false;
4564 }
4565
Felipe Lemed17fda42016-04-29 11:12:45 -07004566 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4567
4568 @Override
4569 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004570 synchronized (mUidRulesFirstLock) {
4571 boolean changed = removeUserStateUL(userId, false);
4572 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004573 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004574 synchronized (mNetworkPoliciesSecondLock) {
4575 writePolicyAL();
4576 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004577 }
4578 }
4579 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004580
4581 /**
4582 * @return true if the given uid is restricted from doing networking on metered networks.
4583 */
4584 @Override
4585 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4586 final int uidRules;
4587 final boolean isBackgroundRestricted;
4588 synchronized (mUidRulesFirstLock) {
4589 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4590 isBackgroundRestricted = mRestrictBackground;
4591 }
4592 return isBackgroundRestricted
4593 && !hasRule(uidRules, RULE_ALLOW_METERED)
4594 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4595 }
4596
4597 /**
4598 * @return true if networking is blocked on the given interface for the given uid according
4599 * to current networking policies.
4600 */
4601 @Override
4602 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004603 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004604 synchronized (mNetworkPoliciesSecondLock) {
4605 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004606 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004607 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004608 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004609
4610 @Override
4611 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4612 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004613 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004614 if (added) {
4615 mPowerSaveTempWhitelistAppIds.put(appId, true);
4616 } else {
4617 mPowerSaveTempWhitelistAppIds.delete(appId);
4618 }
4619 updateRulesForTempWhitelistChangeUL(appId);
4620 }
4621 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004622
4623 @Override
4624 public SubscriptionPlan getSubscriptionPlan(Network network) {
4625 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004626 final int subId = getSubIdLocked(network);
4627 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004628 }
4629 }
4630
4631 @Override
4632 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4633 synchronized (mNetworkPoliciesSecondLock) {
4634 // TODO: handle splitting quota between use-cases
4635 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network));
4636 }
4637 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004638
4639 @Override
4640 public void onAdminDataAvailable() {
4641 mAdminDataAvailableLatch.countDown();
4642 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004643
4644 @Override
4645 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4646 setMeteredRestrictedPackagesInternal(packageNames, userId);
4647 }
4648
4649 @Override
4650 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4651 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4652 userId, 0, packageNames).sendToTarget();
4653 }
4654 }
4655
4656 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4657 synchronized (mUidRulesFirstLock) {
4658 final Set<Integer> newRestrictedUids = new ArraySet<>();
4659 for (String packageName : packageNames) {
4660 final int uid = getUidForPackage(packageName, userId);
4661 if (uid >= 0) {
4662 newRestrictedUids.add(uid);
4663 }
4664 }
4665 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4666 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4667 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4668 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4669 }
4670 }
4671
4672 private int getUidForPackage(String packageName, int userId) {
4673 try {
4674 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4675 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4676 } catch (NameNotFoundException e) {
4677 return -1;
4678 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004679 }
4680
4681 private int parseSubId(NetworkState state) {
4682 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4683 int subId = INVALID_SUBSCRIPTION_ID;
4684 if (state != null && state.networkCapabilities != null
4685 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4686 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4687 if (spec instanceof StringNetworkSpecifier) {
4688 try {
4689 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4690 } catch (NumberFormatException e) {
4691 }
4692 }
4693 }
4694 return subId;
4695 }
4696
Andreas Gampea36dc622018-02-05 17:19:22 -08004697 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004698 private int getSubIdLocked(Network network) {
4699 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004700 }
4701
Andreas Gampea36dc622018-02-05 17:19:22 -08004702 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004703 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4704 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4705 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4706 }
4707
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004708 /**
4709 * This will only ever be called once - during device boot.
4710 */
4711 private void waitForAdminData() {
4712 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4713 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4714 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4715 }
4716 }
4717
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004718 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4719 Set<Integer> newRestrictedUids) {
4720 if (oldRestrictedUids == null) {
4721 for (int uid : newRestrictedUids) {
4722 updateRulesForDataUsageRestrictionsUL(uid);
4723 }
4724 return;
4725 }
4726 for (int uid : oldRestrictedUids) {
4727 if (!newRestrictedUids.contains(uid)) {
4728 updateRulesForDataUsageRestrictionsUL(uid);
4729 }
4730 }
4731 for (int uid : newRestrictedUids) {
4732 if (!oldRestrictedUids.contains(uid)) {
4733 updateRulesForDataUsageRestrictionsUL(uid);
4734 }
4735 }
4736 }
4737
4738 private boolean isRestrictedByAdminUL(int uid) {
4739 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4740 UserHandle.getUserId(uid));
4741 return restrictedUids != null && restrictedUids.contains(uid);
4742 }
4743
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004744 private static boolean hasRule(int uidRules, int rule) {
4745 return (uidRules & rule) != 0;
4746 }
4747
Jeff Sharkey2e471452018-01-19 18:02:47 +09004748 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4749 return (val != null) ? val : new NetworkState[0];
4750 }
4751
Chris Wren193ae6b2017-03-31 15:17:11 -04004752 private class NotificationId {
4753 private final String mTag;
4754 private final int mId;
4755
4756 NotificationId(NetworkPolicy policy, int type) {
4757 mTag = buildNotificationTag(policy, type);
4758 mId = type;
4759 }
4760
4761 @Override
4762 public boolean equals(Object o) {
4763 if (this == o) return true;
4764 if (!(o instanceof NotificationId)) return false;
4765 NotificationId that = (NotificationId) o;
4766 return Objects.equals(mTag, that.mTag);
4767 }
4768
4769 @Override
4770 public int hashCode() {
4771 return Objects.hash(mTag);
4772 }
4773
4774 /**
4775 * Build unique tag that identifies an active {@link NetworkPolicy}
4776 * notification of a specific type, like {@link #TYPE_LIMIT}.
4777 */
4778 private String buildNotificationTag(NetworkPolicy policy, int type) {
4779 return TAG + ":" + policy.template.hashCode() + ":" + type;
4780 }
4781
4782 public String getTag() {
4783 return mTag;
4784 }
4785
4786 public int getId() {
4787 return mId;
4788 }
4789 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004790}