blob: 946d22e60ea11314dfdc8588a41657c642f59ff7 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070031import static android.content.pm.PackageManager.MATCH_ANY_USER;
32import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE;
33import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE;
34import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS;
35import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES;
Erik Klinef851d6d2015-04-20 16:03:48 +090036import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080037import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
38import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
39import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060040import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060041import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey9252b342018-01-19 07:58:35 +090042import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070043import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070044import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070045import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070046import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070047import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080048import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070049import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
50import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070051import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070052import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060053import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070055import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070056import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070058import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070061import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070063import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080064import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
65import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060066import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070067import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070068import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070069import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070070import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070071import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080072import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070073import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070074import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060075import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090076import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070084import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
85import static com.android.internal.util.XmlUtils.writeIntAttribute;
86import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060087import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070088import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070089import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
90import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
91import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
92import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
93import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
94import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
95import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060097
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080099import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700100import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700101
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700102import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700103import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900104import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700105import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700106import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800107import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700109import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700111import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700113import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700115import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700116import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700117import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700119import android.content.Intent;
120import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700121import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700122import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700123import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700124import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700125import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700127import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600128import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700130import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700131import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700132import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700133import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700134import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600135import android.net.Network;
136import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700137import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700138import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600139import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700140import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900142import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700143import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700144import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700145import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900146import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700148import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700149import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700150import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700151import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import android.os.Environment;
153import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700154import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700155import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700156import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700157import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700158import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700159import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700160import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700161import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700162import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600163import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800164import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700165import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700166import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600167import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700169import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700170import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600171import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700172import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700173import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700174import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700175import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100176import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700177import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600178import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800179import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600180import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700181import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400182import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700183import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700184import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700185import android.util.ArrayMap;
186import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700187import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900188import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700189import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700190import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600191import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700192import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600193import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700194import android.util.SparseBooleanArray;
195import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900196import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700198
Jeff Sharkey497e4432011-06-14 17:27:29 -0700199import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700200import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800201import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400202import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500203import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700204import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800205import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800206import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600207import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700209import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600210import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700211import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700212import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700213import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800214import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600215
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600216import libcore.io.IoUtils;
217
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219import org.xmlpull.v1.XmlSerializer;
220
221import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700222import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223import java.io.FileInputStream;
224import java.io.FileNotFoundException;
225import java.io.FileOutputStream;
226import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700227import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700228import java.lang.annotation.Retention;
229import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100230import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700231import java.time.Clock;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600232import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700233import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600234import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700236import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600237import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400238import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800239import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800240import java.util.concurrent.CountDownLatch;
241import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700243/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700244 * Service that maintains low-level network policy rules, using
245 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700246 * <p>
247 * Derives active rules by combining a given policy with other system status,
248 * and delivers to listeners, such as {@link ConnectivityManager}, for
249 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700250 *
251 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000252 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700253 * <ul>
254 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
255 * rules).
256 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
257 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000258 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
259 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700260 * </ul>
261 *
262 * <p>
263 * As such, methods that require synchronization have the following prefixes:
264 * <ul>
265 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
266 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000267 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
268 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700269 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700270 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700271public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700272 static final String TAG = NetworkPolicyLogger.TAG;
273 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
274 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700275
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700276 private static final int VERSION_INIT = 1;
277 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700278 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800279 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800280 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800281 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700282 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700284 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700285 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600286 private static final int VERSION_ADDED_CYCLE = 11;
287 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700288
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800289 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400290 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800291 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400292 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800293 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400294 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900295 @VisibleForTesting
296 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700297
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700298 private static final String TAG_POLICY_LIST = "policy-list";
299 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600300 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700302 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800303 private static final String TAG_WHITELIST = "whitelist";
304 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800305 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306
307 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700308 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
310 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700311 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600312 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
313 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
314 private static final String ATTR_CYCLE_START = "cycleStart";
315 private static final String ATTR_CYCLE_END = "cycleEnd";
316 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 private static final String ATTR_WARNING_BYTES = "warningBytes";
318 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700319 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800320 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
321 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800322 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700323 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700325 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700326 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600327 private static final String ATTR_SUB_ID = "subId";
328 private static final String ATTR_TITLE = "title";
329 private static final String ATTR_SUMMARY = "summary";
330 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
331 private static final String ATTR_USAGE_BYTES = "usageBytes";
332 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600333 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800335 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800336 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800337 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800338 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700339 private static final String ACTION_SNOOZE_RAPID =
340 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700341
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800342 /**
343 * Indicates the maximum wait time for admin data to be available;
344 */
345 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
346
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700347 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700348 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800349 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800350 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700351 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700352 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
353 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700354 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700355 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900356 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800357 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700358
Makoto Onuki8e777332017-03-28 11:25:47 -0700359 private static final int UID_MSG_STATE_CHANGED = 100;
360 private static final int UID_MSG_GONE = 101;
361
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600362 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
363
Jeff Sharkey75279902011-05-24 18:39:45 -0700364 private final Context mContext;
365 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700366 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700367 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700368 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700369 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700370 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700371 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700372
373 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700374 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700375 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800376 @GuardedBy("mUidRulesFirstLock")
377 private PowerSaveState mRestrictBackgroundPowerState;
378
379 // Store the status of restrict background before turning on battery saver.
380 // Used to restore mRestrictBackground when battery saver is turned off.
381 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700382
Sudheer Shanka543339f2017-07-28 15:18:07 -0700383 // Denotes the status of restrict background read from disk.
384 private boolean mLoadedRestrictBackground;
385
Felipe Lemef0823852016-06-08 13:43:08 -0700386 // See main javadoc for instructions on how to use these locks.
387 final Object mUidRulesFirstLock = new Object();
388 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700389
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("allLocks") volatile boolean mSystemReady;
391
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
393 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
394 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800395 // Store whether user flipped restrict background in battery saver mode
396 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700397
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700398 private final boolean mSuppressDefaultPolicy;
399
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800400 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
401
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700402 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600403 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800404 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700405
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600406 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600407 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600408 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600409 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600410 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600411 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600412
Jeff Sharkey9252b342018-01-19 07:58:35 +0900413 /** Map from subId to daily opportunistic quota. */
414 @GuardedBy("mNetworkPoliciesSecondLock")
415 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
416
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700417 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700418 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700421
Felipe Lemef0823852016-06-08 13:43:08 -0700422 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700423 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700425 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700426 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800427 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700428
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700429 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700430 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700431 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
432
Jeff Sharkey32566012014-12-02 18:30:14 -0800433 /**
434 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700435 * in power save mode, except device idle (doze) still applies.
436 * TODO: An int array might be sufficient
437 */
Felipe Lemef0823852016-06-08 13:43:08 -0700438 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700439 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
440
441 /**
442 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800443 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700444 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800445 */
Felipe Lemef0823852016-06-08 13:43:08 -0700446 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700447 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700448
Felipe Lemef0823852016-06-08 13:43:08 -0700449 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700450 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
451
Felipe Lemeb85a6372016-01-14 16:16:16 -0800452 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800453 * UIDs that have been initially white-listed by system to avoid restricted background.
454 */
Felipe Lemef0823852016-06-08 13:43:08 -0700455 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800456 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
457 new SparseBooleanArray();
458
459 /**
460 * UIDs that have been initially white-listed by system to avoid restricted background,
461 * but later revoked by user.
462 */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800464 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
465 new SparseBooleanArray();
466
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700467 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700468 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800469 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700470 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800472 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700473
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700474 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700475 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400476 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700477
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700478 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700479 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800480 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700481
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600482 /** Map from network ID to last observed meteredness state */
483 @GuardedBy("mNetworkPoliciesSecondLock")
484 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
485
Jeff Sharkey9252b342018-01-19 07:58:35 +0900486 /** Map from netId to subId as of last update */
487 @GuardedBy("mNetworkPoliciesSecondLock")
488 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
489
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800490 /**
491 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
492 * userId to restricted uids which belong to that user.
493 */
494 @GuardedBy("mUidRulesFirstLock")
495 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
496
Jeff Sharkey32566012014-12-02 18:30:14 -0800497 private final RemoteCallbackList<INetworkPolicyListener>
498 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700499
Dianne Hackborn497175b2014-07-01 12:56:08 -0700500 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700501 @VisibleForTesting
502 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700503
504 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700505
Felipe Lemef0823852016-06-08 13:43:08 -0700506 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700507 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700508
Svet Ganov16a16892015-04-16 10:32:04 -0700509 private final AppOpsManager mAppOps;
510
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800511 private final IPackageManager mIPm;
512
Sudheer Shankae7361852017-03-07 11:51:46 -0800513 private ActivityManagerInternal mActivityManagerInternal;
514
Sudheer Shanka352dc572017-09-22 17:09:38 -0700515 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800516
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700517 // TODO: keep whitelist of system-critical services that should never have
518 // rules enforced, such as system, phone, and radio UIDs.
519
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700520 // TODO: migrate notifications to SystemUI
521
Jeff Sharkey75279902011-05-24 18:39:45 -0700522 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700523 INetworkManagementService networkManagement) {
524 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
525 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700526 }
527
Jeff Sharkey9911a282018-02-14 22:29:11 -0700528 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700529 return new File(Environment.getDataDirectory(), "system");
530 }
531
Jeff Sharkey9911a282018-02-14 22:29:11 -0700532 private static @NonNull Clock getDefaultClock() {
533 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
534 Clock.systemUTC());
535 }
536
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700537 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700538 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
539 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700540 mContext = checkNotNull(context, "missing context");
541 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700542 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700543 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700544 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700545 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700546 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700547 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700548 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700549
Amith Yamasani450a16b2013-09-18 16:28:50 -0700550 HandlerThread thread = new HandlerThread(TAG);
551 thread.start();
552 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700553
Makoto Onuki8e777332017-03-28 11:25:47 -0700554 // We create another thread for the UID events, which are more time-critical.
555 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
556 /*allowIo=*/ false);
557 mUidEventThread.start();
558 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
559
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700560 mSuppressDefaultPolicy = suppressDefaultPolicy;
561
Dianne Hackborne17b4452018-01-10 13:15:40 -0800562 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700563
564 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800565
Felipe Lemed17fda42016-04-29 11:12:45 -0700566 // Expose private service for system components to use.
567 LocalServices.addService(NetworkPolicyManagerInternal.class,
568 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700569 }
570
571 public void bindConnectivityManager(IConnectivityManager connManager) {
572 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700573 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700574
Felipe Lemef0823852016-06-08 13:43:08 -0700575 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700576 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700577 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
578 mPowerSaveWhitelistExceptIdleAppIds.clear();
579 if (whitelist != null) {
580 for (int uid : whitelist) {
581 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
582 }
583 }
584 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700585 mPowerSaveWhitelistAppIds.clear();
586 if (whitelist != null) {
587 for (int uid : whitelist) {
588 mPowerSaveWhitelistAppIds.put(uid, true);
589 }
590 }
591 } catch (RemoteException e) {
592 }
593 }
594
Felipe Lemea9505cc2016-02-26 10:28:41 -0800595 /**
596 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
597 * revoke the whitelist.
598 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700599 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800600 */
Felipe Lemef0823852016-06-08 13:43:08 -0700601 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800602 final List<UserInfo> users = mUserManager.getUsers();
603 final int numberUsers = users.size();
604
Felipe Lemea110eec2016-04-29 09:58:06 -0700605 boolean changed = false;
606 for (int i = 0; i < numberUsers; i++) {
607 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700608 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700609 }
610 return changed;
611 }
612
Felipe Lemef0823852016-06-08 13:43:08 -0700613 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700614 final SystemConfig sysConfig = SystemConfig.getInstance();
615 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800616 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
617 boolean changed = false;
618 for (int i = 0; i < allowDataUsage.size(); i++) {
619 final String pkg = allowDataUsage.valueAt(i);
620 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700621 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
622 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800623 final ApplicationInfo app;
624 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700625 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800626 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700627 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
628 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800629 continue;
630 }
631 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700632 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
633 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800634 continue;
635 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700636 final int uid = UserHandle.getUid(userId, app.uid);
637 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
638 if (LOGD)
639 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
640 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800641 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700642 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700643 if (LOGD)
644 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
645 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700646 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700647 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800648 }
649 }
650 return changed;
651 }
652
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800653 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700654 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800655 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700656 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800657 // Boost thread's priority during system server init
658 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700659 if (!isBandwidthControlEnabled()) {
660 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
661 return;
662 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700663
Felipe Leme873a83a2016-09-07 11:34:10 -0700664 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700665 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700666
Felipe Leme873a83a2016-09-07 11:34:10 -0700667 synchronized (mUidRulesFirstLock) {
668 synchronized (mNetworkPoliciesSecondLock) {
669 updatePowerSaveWhitelistUL();
670 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
671 mPowerManagerInternal.registerLowPowerModeObserver(
672 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800673 @Override
674 public int getServiceType() {
675 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700676 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800677
678 @Override
679 public void onLowPowerModeChanged(PowerSaveState result) {
680 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800681 if (LOGD) {
682 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
683 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800684 synchronized (mUidRulesFirstLock) {
685 if (mRestrictPower != enabled) {
686 mRestrictPower = enabled;
687 updateRulesForRestrictPowerUL();
688 }
689 }
690 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800691 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800692 mRestrictPower = mPowerManagerInternal.getLowPowerState(
693 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700694
695 mSystemReady = true;
696
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800697 waitForAdminData();
698
Felipe Leme873a83a2016-09-07 11:34:10 -0700699 // read policy from disk
700 readPolicyAL();
701
jackqdyulei29c82ab2017-03-10 14:09:16 -0800702 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700703 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800704 mRestrictBackgroundPowerState = mPowerManagerInternal
705 .getLowPowerState(ServiceType.DATA_SAVER);
706 final boolean localRestrictBackground =
707 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700708 if (localRestrictBackground && !mLoadedRestrictBackground) {
709 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800710 }
711 mPowerManagerInternal.registerLowPowerModeObserver(
712 new PowerManagerInternal.LowPowerModeListener() {
713 @Override
714 public int getServiceType() {
715 return ServiceType.DATA_SAVER;
716 }
717
718 @Override
719 public void onLowPowerModeChanged(PowerSaveState result) {
720 synchronized (mUidRulesFirstLock) {
721 updateRestrictBackgroundByLowPowerModeUL(result);
722 }
723 }
724 });
725
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
727 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700728 }
Felipe Lemef0823852016-06-08 13:43:08 -0700729
Sudheer Shanka543339f2017-07-28 15:18:07 -0700730 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700731 updateRulesForGlobalChangeAL(false);
732 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700733 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800734 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700735
Sudheer Shankae7361852017-03-07 11:51:46 -0800736 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700737 try {
738 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000739 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800740 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700741 mNetworkManager.registerObserver(mAlertObserver);
742 } catch (RemoteException e) {
743 // ignored; both services live in system_server
744 }
745
746 // listen for changes to power save whitelist
747 final IntentFilter whitelistFilter = new IntentFilter(
748 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
749 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
750
Felipe Leme873a83a2016-09-07 11:34:10 -0700751 // watch for network interfaces to be claimed
752 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
753 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
754
755 // listen for package changes to update policy
756 final IntentFilter packageFilter = new IntentFilter();
757 packageFilter.addAction(ACTION_PACKAGE_ADDED);
758 packageFilter.addDataScheme("package");
759 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
760
761 // listen for UID changes to update policy
762 mContext.registerReceiver(
763 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
764
765 // listen for user changes to update policy
766 final IntentFilter userFilter = new IntentFilter();
767 userFilter.addAction(ACTION_USER_ADDED);
768 userFilter.addAction(ACTION_USER_REMOVED);
769 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
770
771 // listen for stats update events
772 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
773 mContext.registerReceiver(
774 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
775
776 // listen for restrict background changes from notifications
777 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
778 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
779
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700780 // Listen for snooze from notifications
781 mContext.registerReceiver(mSnoozeReceiver,
782 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
783 mContext.registerReceiver(mSnoozeReceiver,
784 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700785
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600786 // listen for configured wifi networks to be loaded
787 final IntentFilter wifiFilter =
788 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
789 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700790
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700791 // listen for carrier config changes to update data cycle information
792 final IntentFilter carrierConfigFilter = new IntentFilter(
793 ACTION_CARRIER_CONFIG_CHANGED);
794 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
795
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600796 // listen for meteredness changes
797 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
798 new NetworkRequest.Builder().build(), mNetworkCallback);
799
Felipe Leme873a83a2016-09-07 11:34:10 -0700800 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800801 // tell systemReady() that the service has been initialized
802 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700803 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800804 // Restore the default priority after init is done
805 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700806 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700808 }
809
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800810 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
811 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
812 mHandler.post(() -> initService(initCompleteSignal));
813 return initCompleteSignal;
814 }
815
816 public void systemReady(CountDownLatch initCompleteSignal) {
817 // wait for initService to complete
818 try {
819 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
820 throw new IllegalStateException("Service " + TAG +" init timeout");
821 }
822 } catch (InterruptedException e) {
823 Thread.currentThread().interrupt();
824 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
825 }
826 }
827
Sudheer Shankac9d94072017-02-22 22:13:55 +0000828 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700829 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700830 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
831 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700832 }
833
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700834 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700835 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700836 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700837
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700838 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700839 }
840
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700841 @Override public void onUidIdle(int uid, boolean disabled) {
842 }
843
844 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700845 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700846 };
847
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700848 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700849 @Override
850 public void onReceive(Context context, Intent intent) {
851 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700852 synchronized (mUidRulesFirstLock) {
853 updatePowerSaveWhitelistUL();
854 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700855 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700856 }
857 }
858 };
859
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700860 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700861 @Override
862 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700863 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700864
865 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700866 final int uid = intent.getIntExtra(EXTRA_UID, -1);
867 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700868
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700869 if (ACTION_PACKAGE_ADDED.equals(action)) {
870 // update rules for UID, since it might be subject to
871 // global background data policy
872 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700873 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700874 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700875 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700876 }
877 }
878 };
879
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700880 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700881 @Override
882 public void onReceive(Context context, Intent intent) {
883 // on background handler thread, and UID_REMOVED is protected
884
885 final int uid = intent.getIntExtra(EXTRA_UID, -1);
886 if (uid == -1) return;
887
888 // remove any policy and update rules to clean up
889 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700890 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700891 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700892 synchronized (mNetworkPoliciesSecondLock) {
893 writePolicyAL();
894 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700895 }
896 }
897 };
898
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700899 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700900 @Override
901 public void onReceive(Context context, Intent intent) {
902 // on background handler thread, and USER_ADDED and USER_REMOVED
903 // broadcasts are protected
904
905 final String action = intent.getAction();
906 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
907 if (userId == -1) return;
908
Amith Yamasani15e472352015-04-24 19:06:07 -0700909 switch (action) {
910 case ACTION_USER_REMOVED:
911 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700912 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800913 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700914 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700915 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800916 // Removing outside removeUserStateUL since that can also be called when
917 // user resets app preferences.
918 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700919 if (action == ACTION_USER_ADDED) {
920 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700921 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700922 }
923 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700924 synchronized (mNetworkPoliciesSecondLock) {
925 updateRulesForGlobalChangeAL(true);
926 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700927 }
928 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700929 }
930 }
931 };
932
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700933 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934 * Receiver that watches for {@link INetworkStatsService} updates, which we
935 * use to check against {@link NetworkPolicy#warningBytes}.
936 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700937 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 @Override
939 public void onReceive(Context context, Intent intent) {
940 // on background handler thread, and verified
941 // READ_NETWORK_USAGE_HISTORY permission above.
942
Felipe Lemef0823852016-06-08 13:43:08 -0700943 synchronized (mNetworkPoliciesSecondLock) {
944 updateNetworkEnabledNL();
945 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700946 }
947 }
948 };
949
950 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700951 * Receiver that watches for {@link Notification} control of
952 * {@link #mRestrictBackground}.
953 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700954 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700955 @Override
956 public void onReceive(Context context, Intent intent) {
957 // on background handler thread, and verified MANAGE_NETWORK_POLICY
958 // permission above.
959
960 setRestrictBackground(false);
961 }
962 };
963
964 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800965 * Receiver that watches for {@link Notification} control of
966 * {@link NetworkPolicy#lastWarningSnooze}.
967 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700968 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800969 @Override
970 public void onReceive(Context context, Intent intent) {
971 // on background handler thread, and verified MANAGE_NETWORK_POLICY
972 // permission above.
973
974 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700975 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
976 performSnooze(template, TYPE_WARNING);
977 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
978 performSnooze(template, TYPE_RAPID);
979 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800980 }
981 };
982
983 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600984 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600985 * we can perform upgrade logic. After initial upgrade logic, it updates
986 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700987 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600988 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700989 @Override
990 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900991 synchronized (mUidRulesFirstLock) {
992 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600993 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600994 }
995 }
996 // Only need to perform upgrade logic once
997 mContext.unregisterReceiver(this);
998 }
999 };
1000
1001 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1002 @Override
1003 public void onCapabilitiesChanged(Network network,
1004 NetworkCapabilities networkCapabilities) {
1005 if (network == null || networkCapabilities == null) return;
1006
1007 synchronized (mNetworkPoliciesSecondLock) {
1008 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1009 final boolean newMetered = !networkCapabilities
1010 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1011
1012 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001013 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001014 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001015 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001016 }
1017 }
1018 }
1019 };
1020
1021 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 * Observer that watches for {@link INetworkManagementService} alerts.
1023 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001024 final private INetworkManagementEventObserver mAlertObserver
1025 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 @Override
1027 public void limitReached(String limitName, String iface) {
1028 // only someone like NMS should be calling us
1029 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1030
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001031 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1032 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001033 }
1034 }
1035 };
1036
1037 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1039 * to show visible notifications as needed.
1040 */
Felipe Lemef0823852016-06-08 13:43:08 -07001041 void updateNotificationsNL() {
1042 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001044 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001045 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001047
1048 // TODO: when switching to kernel notifications, compute next future
1049 // cycle boundary to recompute notifications.
1050
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001051 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001052 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001053 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1054 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 // ignore policies that aren't relevant to user
1056 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001057 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001058
Jeff Sharkey53313d72017-07-13 16:47:32 -06001059 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1060 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001061 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1062 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1063 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001065 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001066 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001067 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1068 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001069 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001071 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001072 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 }
1074
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001076 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001078 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1079 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001080 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001081 }
1082 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001083
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001084 // Warn if average usage over last 4 days is on track to blow pretty
1085 // far past the plan limits.
1086 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001087 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001088 final long recentStart = now - recentDuration;
1089 final long recentEnd = now;
1090 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001091
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001092 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001093 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001094 final long alertBytes = (policy.limitBytes * 3) / 2;
1095
1096 if (LOGD) {
1097 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1098 + projectedBytes + " alert " + alertBytes);
1099 }
1100
1101 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1102 - DateUtils.DAY_IN_MILLIS;
1103 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001104 enqueueNotification(policy, TYPE_RAPID, 0,
1105 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001106 }
1107 }
1108 }
1109
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001110 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001111 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001112 final NotificationId notificationId = beforeNotifs.valueAt(i);
1113 if (!mActiveNotifs.contains(notificationId)) {
1114 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 }
1116 }
1117 }
1118
1119 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001120 * Attempt to find a specific app to blame for rapid data usage during the
1121 * given time period.
1122 */
1123 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1124 long start, long end) {
1125 long totalBytes = 0;
1126 long maxBytes = 0;
1127 int maxUid = 0;
1128
1129 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1130 NetworkStats.Entry entry = null;
1131 for (int i = 0; i < stats.size(); i++) {
1132 entry = stats.getValues(i, entry);
1133 final long bytes = entry.rxBytes + entry.txBytes;
1134 totalBytes += bytes;
1135 if (bytes > maxBytes) {
1136 maxBytes = bytes;
1137 maxUid = entry.uid;
1138 }
1139 }
1140
1141 // Only point blame if the majority of usage was done by a single app.
1142 // TODO: support shared UIDs
1143 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1144 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001145 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001146 try {
1147 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1148 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1149 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1150 } catch (NameNotFoundException ignored) {
1151 }
1152 }
1153 }
1154
1155 return null;
1156 }
1157
1158 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001160 * current device state, such as when
1161 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1162 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163 */
1164 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001165 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001166 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1167 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001168
Jeff Sharkey32566012014-12-02 18:30:14 -08001169 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001170 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001171 for (int subId : subIds) {
1172 final String subscriberId = tele.getSubscriberId(subId);
1173 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001174 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1175 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001176 if (template.matches(probeIdent)) {
1177 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001178 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001179 }
1180 return false;
1181 } else {
1182 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 }
1185
1186 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001187 * Notify that given {@link NetworkTemplate} is over
1188 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1189 */
Felipe Lemef0823852016-06-08 13:43:08 -07001190 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001192 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193 mOverLimitNotified.add(template);
1194 }
1195 }
1196
Felipe Lemef0823852016-06-08 13:43:08 -07001197 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001198 mOverLimitNotified.remove(template);
1199 }
1200
1201 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001202 * Show notification for combined {@link NetworkPolicy} and specific type,
1203 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1204 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001205 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1206 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001207 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001208 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001209 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001210 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001211 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001212 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001213 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001214
1215 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001216 final CharSequence title;
1217 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001218 switch (type) {
1219 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001220 title = res.getText(R.string.data_usage_warning_title);
1221 body = res.getString(R.string.data_usage_warning_body,
1222 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001223
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001224 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001225
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001226 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1227 builder.setDeleteIntent(PendingIntent.getBroadcast(
1228 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1229
Wei Liu546cb772016-07-21 16:19:01 -07001230 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001231 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001232 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1233
Jeff Sharkey497e4432011-06-14 17:27:29 -07001234 break;
1235 }
1236 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001237 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001238 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001239 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001240 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001241 case MATCH_WIFI:
1242 title = res.getText(R.string.data_usage_wifi_limit_title);
1243 break;
1244 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001245 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001246 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001247 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001248
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001249 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001250 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001251
Wei Liu546cb772016-07-21 16:19:01 -07001252 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001253 builder.setContentIntent(PendingIntent.getActivity(
1254 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1255 break;
1256 }
1257 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001258 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001259 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001260 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1261 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001262 case MATCH_WIFI:
1263 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1264 break;
1265 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001266 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001267 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001268 final long overBytes = totalBytes - policy.limitBytes;
1269 body = res.getString(R.string.data_usage_limit_snoozed_body,
1270 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001271
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001272 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001273 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001274 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001275
Wei Liu546cb772016-07-21 16:19:01 -07001276 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001277 builder.setContentIntent(PendingIntent.getActivity(
1278 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001279 break;
1280 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001281 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001282 title = res.getText(R.string.data_usage_rapid_title);
1283 if (rapidBlame != null) {
1284 body = res.getString(R.string.data_usage_rapid_app_body,
1285 rapidBlame.loadLabel(mContext.getPackageManager()));
1286 } else {
1287 body = res.getString(R.string.data_usage_rapid_body);
1288 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001289
Jeff Sharkey2e471452018-01-19 18:02:47 +09001290 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001291
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001292 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1293 builder.setDeleteIntent(PendingIntent.getBroadcast(
1294 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1295
1296 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001297 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001298 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001299 break;
1300 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001301 default: {
1302 return;
1303 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001304 }
1305
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001306 builder.setTicker(title);
1307 builder.setContentTitle(title);
1308 builder.setContentText(body);
1309 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001310
1311 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1312 notificationId.getId(), builder.build(), UserHandle.ALL);
1313 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001314 }
1315
Chris Wren193ae6b2017-03-31 15:17:11 -04001316 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001317 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1318 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001319 }
1320
1321 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001323 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001325 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 @Override
1327 public void onReceive(Context context, Intent intent) {
1328 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1329 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001330
Hugo Benichi446c9c92017-04-10 09:41:10 +09001331 synchronized (mUidRulesFirstLock) {
1332 synchronized (mNetworkPoliciesSecondLock) {
1333 ensureActiveMobilePolicyAL();
1334 normalizePoliciesNL();
1335 updateNetworkEnabledNL();
1336 updateNetworkRulesNL();
1337 updateNotificationsNL();
1338 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001339 }
1340 }
1341 };
1342
Jeff Sharkey2e471452018-01-19 18:02:47 +09001343 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001344 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001345 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001346 final CountDownLatch latch = new CountDownLatch(1);
1347 mHandler.post(() -> {
1348 latch.countDown();
1349 });
1350 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001351 }
1352
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001354 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1355 * if necessary.
1356 *
1357 * @param subId that has its associated NetworkPolicy updated if necessary
1358 * @return if any policies were updated
1359 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001360 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1361 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001362
1363 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001364 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1365 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001366
1367 // find and update the mobile NetworkPolicy for this subscriber id
1368 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001369 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001370 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1371 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1372 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001373 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1374 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001375 }
1376 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001377 return policyUpdated;
1378 }
1379
1380 /**
1381 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1382 *
1383 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1384 * to do so, it returns the fallback value.
1385 *
1386 * @param config The CarrierConfig to read the value from.
1387 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1388 * @return cycleDay to use in the mobile NetworkPolicy.
1389 */
1390 @VisibleForTesting
1391 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1392 int fallbackCycleDay) {
1393 if (config == null) {
1394 return fallbackCycleDay;
1395 }
1396 int cycleDay =
1397 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1398 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1399 return fallbackCycleDay;
1400 }
1401 // validate cycleDay value
1402 final Calendar cal = Calendar.getInstance();
1403 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1404 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1405 Slog.e(TAG, "Invalid date in "
1406 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1407 return fallbackCycleDay;
1408 }
1409 return cycleDay;
1410 }
1411
1412 /**
1413 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1414 *
1415 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1416 * to do so, it returns the fallback value.
1417 *
1418 * @param config The CarrierConfig to read the value from.
1419 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1420 * @return warningBytes to use in the mobile NetworkPolicy.
1421 */
1422 @VisibleForTesting
1423 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1424 long fallbackWarningBytes) {
1425 if (config == null) {
1426 return fallbackWarningBytes;
1427 }
1428 long warningBytes =
1429 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1430
1431 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1432 return WARNING_DISABLED;
1433 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1434 return getPlatformDefaultWarningBytes();
1435 } else if (warningBytes < 0) {
1436 Slog.e(TAG, "Invalid value in "
1437 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1438 + "non-negative value but got: " + warningBytes);
1439 return fallbackWarningBytes;
1440 }
1441
1442 return warningBytes;
1443 }
1444
1445 /**
1446 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1447 *
1448 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1449 * to do so, it returns the fallback value.
1450 *
1451 * @param config The CarrierConfig to read the value from.
1452 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1453 * @return limitBytes to use in the mobile NetworkPolicy.
1454 */
1455 @VisibleForTesting
1456 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1457 long fallbackLimitBytes) {
1458 if (config == null) {
1459 return fallbackLimitBytes;
1460 }
1461 long limitBytes =
1462 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1463
1464 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1465 return LIMIT_DISABLED;
1466 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1467 return getPlatformDefaultLimitBytes();
1468 } else if (limitBytes < 0) {
1469 Slog.e(TAG, "Invalid value in "
1470 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1471 + "non-negative value but got: " + limitBytes);
1472 return fallbackLimitBytes;
1473 }
1474 return limitBytes;
1475 }
1476
1477 /**
1478 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1479 */
1480 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1481 @Override
1482 public void onReceive(Context context, Intent intent) {
1483 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1484 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1485
1486 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1487 return;
1488 }
1489 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001490 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001491 final String subscriberId = tele.getSubscriberId(subId);
1492
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001493 synchronized (mUidRulesFirstLock) {
1494 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001495 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001496 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001497 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001498 if (!updated) return;
1499 // update network and notification rules, as the data cycle changed and it's
1500 // possible that we should be triggering warnings/limits now
1501 handleNetworkPoliciesUpdateAL(true);
1502 }
1503 }
1504 }
1505 };
1506
1507 /**
1508 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1509 * one has been updated.
1510 *
1511 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1512 * update.
1513 */
1514 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1515 if (shouldNormalizePolicies) {
1516 normalizePoliciesNL();
1517 }
1518 updateNetworkEnabledNL();
1519 updateNetworkRulesNL();
1520 updateNotificationsNL();
1521 writePolicyAL();
1522 }
1523
1524 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001525 * Proactively control network data connections when they exceed
1526 * {@link NetworkPolicy#limitBytes}.
1527 */
Felipe Lemef0823852016-06-08 13:43:08 -07001528 void updateNetworkEnabledNL() {
1529 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001530
1531 // TODO: reset any policy-disabled networks when any policy is removed
1532 // completely, which is currently rare case.
1533
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001534 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1535 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001536 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001537 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001538 setNetworkTemplateEnabled(policy.template, true);
1539 continue;
1540 }
1541
Jeff Sharkey53313d72017-07-13 16:47:32 -06001542 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1543 .cycleIterator(policy).next();
1544 final long start = cycle.first.toInstant().toEpochMilli();
1545 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001546 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001547
1548 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001549 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1550 && policy.lastLimitSnooze < start;
1551 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001552
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001553 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001554 }
1555 }
1556
1557 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001558 * Proactively disable networks that match the given
1559 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001560 */
1561 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001562 // TODO: reach into ConnectivityManager to proactively disable bringing
1563 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001564
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001565 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001566 // If mobile data usage hits the limit or if the user resumes the data, we need to
1567 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001568 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1569 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001570
Jeff Sharkey2e471452018-01-19 18:02:47 +09001571 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001572 for (int subId : subIds) {
1573 final String subscriberId = tm.getSubscriberId(subId);
1574 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001575 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1576 true);
Jack Yu8781b682016-07-08 14:28:51 -07001577 // Template is matched when subscriber id matches.
1578 if (template.matches(probeIdent)) {
1579 tm.setPolicyDataEnabled(enabled, subId);
1580 }
1581 }
1582 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001583 }
1584
1585 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001586 * Collect all ifaces from a {@link NetworkState} into the given set.
1587 */
1588 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1589 final String baseIface = state.linkProperties.getInterfaceName();
1590 if (baseIface != null) {
1591 ifaces.add(baseIface);
1592 }
1593 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1594 final String stackedIface = stackedLink.getInterfaceName();
1595 if (stackedIface != null) {
1596 ifaces.add(stackedIface);
1597 }
1598 }
1599 }
1600
1601 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001602 * Examine all connected {@link NetworkState}, looking for
1603 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1604 * remaining quota based on usage cycle and historical stats.
1605 */
Felipe Lemef0823852016-06-08 13:43:08 -07001606 void updateNetworkRulesNL() {
1607 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608
1609 final NetworkState[] states;
1610 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001611 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001613 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001614 return;
1615 }
1616
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001617 // First, generate identities of all connected networks so we can
1618 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001619 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001620 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001622 if (state.network != null) {
1623 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1624 }
Wei Liub8eaf452016-01-25 10:32:27 -08001625 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001626 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1627 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001628 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001629 }
1630 }
1631
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001632 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001633 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001634
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001635 // For every well-defined policy, compute remaining data based on
1636 // current cycle and historical stats, and push to kernel.
1637 final ArraySet<String> matchingIfaces = new ArraySet<>();
1638 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1639 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1640
1641 // Collect all ifaces that match this policy
1642 matchingIfaces.clear();
1643 for (int j = identified.size() - 1; j >= 0; j--) {
1644 if (policy.template.matches(identified.valueAt(j))) {
1645 collectIfaces(matchingIfaces, identified.keyAt(j));
1646 }
1647 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001650 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 }
1652
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001653 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001654 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001655 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001656 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001657 if (hasLimit && policy.hasCycle()) {
1658 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1659 .cycleIterator(policy).next();
1660 final long start = cycle.first.toInstant().toEpochMilli();
1661 final long end = cycle.second.toInstant().toEpochMilli();
1662 final long totalBytes = getTotalBytes(policy.template, start, end);
1663
1664 if (policy.lastLimitSnooze >= start) {
1665 // snoozing past quota, but we still need to restrict apps,
1666 // so push really high quota.
1667 quotaBytes = Long.MAX_VALUE;
1668 } else {
1669 // remaining "quota" bytes are based on total usage in
1670 // current cycle. kernel doesn't like 0-byte rules, so we
1671 // set 1-byte quota and disable the radio later.
1672 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1673 }
1674 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001675 // metered network, but no policy limit; we still need to
1676 // restrict apps, so push really high quota.
1677 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001678 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001679
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001680 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001681 // TODO: switch to shared quota once NMS supports
1682 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001683 }
1684
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001685 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1686 final String iface = matchingIfaces.valueAt(j);
1687 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001688 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001689 }
1690 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001691
1692 // keep track of lowest warning or limit of active policies
1693 if (hasWarning && policy.warningBytes < lowestRule) {
1694 lowestRule = policy.warningBytes;
1695 }
1696 if (hasLimit && policy.limitBytes < lowestRule) {
1697 lowestRule = policy.limitBytes;
1698 }
1699 }
1700
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001701 // One final pass to catch any metered ifaces that don't have explicitly
1702 // defined policies; typically Wi-Fi networks.
1703 for (NetworkState state : states) {
1704 if (state.networkInfo != null && state.networkInfo.isConnected()
1705 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1706 matchingIfaces.clear();
1707 collectIfaces(matchingIfaces, state);
1708 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1709 final String iface = matchingIfaces.valueAt(j);
1710 if (!newMeteredIfaces.contains(iface)) {
1711 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1712 newMeteredIfaces.add(iface);
1713 }
1714 }
1715 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001716 }
1717
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001718 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001719 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1720 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001721 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001722 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001723 }
1724 }
1725 mMeteredIfaces = newMeteredIfaces;
1726
Jeff Sharkey9252b342018-01-19 07:58:35 +09001727 // Finally, calculate our opportunistic quotas
1728 // TODO: add experiments support to disable or tweak ratios
1729 mSubscriptionOpportunisticQuota.clear();
1730 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001731 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001732 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001733 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001734 if (plan == null) continue;
1735
1736 // By default assume we have no quota
Jeff Sharkey9252b342018-01-19 07:58:35 +09001737 long quotaBytes = 0;
1738
Jeff Sharkey2e471452018-01-19 18:02:47 +09001739 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001740 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1741 // Ignore missing limits
Jeff Sharkey2e471452018-01-19 18:02:47 +09001742 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001743 // Unlimited data; let's use 20MiB/day (600MiB/month)
1744 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1745 } else {
1746 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001747 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001748 final long start = cycle.first.toInstant().toEpochMilli();
1749 final long end = cycle.second.toInstant().toEpochMilli();
1750 final long totalBytes = getTotalBytes(
1751 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1752 final long remainingBytes = limitBytes - totalBytes;
Jeff Sharkey9911a282018-02-14 22:29:11 -07001753 final long remainingDays = Math.max(1, (end - mClock.millis())
Jeff Sharkey9252b342018-01-19 07:58:35 +09001754 / TimeUnit.DAYS.toMillis(1));
1755 if (remainingBytes > 0) {
1756 quotaBytes = (remainingBytes / remainingDays) / 10;
1757 }
1758 }
1759
1760 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1761 }
1762
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001763 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001764 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001765
1766 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001767 }
1768
1769 /**
1770 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1771 * have at least a default mobile policy defined.
1772 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001773 private void ensureActiveMobilePolicyAL() {
1774 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001775 if (mSuppressDefaultPolicy) return;
1776
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001777 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1778 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001779
Jeff Sharkey2e471452018-01-19 18:02:47 +09001780 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001781 for (int subId : subIds) {
1782 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001783 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001784 }
1785 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001786
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001787 /**
1788 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1789 * have at least a default mobile policy defined.
1790 *
1791 * @param subId to build a default policy for
1792 * @param subscriberId that we check for an existing policy
1793 * @return true if a mobile network policy was added, or false one already existed.
1794 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001795 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001796 // Poke around to see if we already have a policy
1797 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001798 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001799 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1800 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1801 if (template.matches(probeIdent)) {
1802 if (LOGD) {
1803 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1804 + NetworkIdentity.scrubSubscriberId(subscriberId));
1805 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001806 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001807 }
1808 }
1809
Jeff Sharkey32566012014-12-02 18:30:14 -08001810 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1811 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001812 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001813 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001814 return true;
1815 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001816
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001817 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001818 final int dataWarningConfig = mContext.getResources().getInteger(
1819 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001820 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001821 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001822 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001823 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001824 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001825 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001826
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001827 private long getPlatformDefaultLimitBytes() {
1828 return LIMIT_DISABLED;
1829 }
1830
1831 @VisibleForTesting
1832 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001833 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001834 final RecurrenceRule cycleRule = NetworkPolicy
1835 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001836 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001837 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1838 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1839 synchronized (mUidRulesFirstLock) {
1840 synchronized (mNetworkPoliciesSecondLock) {
1841 updateDefaultMobilePolicyAL(subId, policy);
1842 }
1843 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001844 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001845 }
1846
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001847 /**
1848 * Update the given {@link NetworkPolicy} based on any carrier-provided
1849 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1850 * Leaves policy untouched if the user has modified it.
1851 *
1852 * @return if the policy was modified
1853 */
1854 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1855 if (!policy.inferred) {
1856 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1857 return false;
1858 }
1859
1860 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1861 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1862 policy.lastLimitSnooze, policy.metered, policy.inferred);
1863
1864 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1865 if (!ArrayUtils.isEmpty(plans)) {
1866 final SubscriptionPlan plan = plans[0];
1867 policy.cycleRule = plan.getCycleRule();
1868 final long planLimitBytes = plan.getDataLimitBytes();
1869 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1870 policy.warningBytes = getPlatformDefaultWarningBytes();
1871 policy.limitBytes = getPlatformDefaultLimitBytes();
1872 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1873 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1874 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1875 } else {
1876 policy.warningBytes = (planLimitBytes * 9) / 10;
1877 switch (plan.getDataLimitBehavior()) {
1878 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1879 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1880 policy.limitBytes = planLimitBytes;
1881 break;
1882 default:
1883 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1884 break;
1885 }
1886 }
1887 } else {
1888 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1889 final int currentCycleDay;
1890 if (policy.cycleRule.isMonthly()) {
1891 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1892 } else {
1893 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1894 }
1895 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1896 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1897 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1898 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1899 }
1900
1901 if (policy.equals(original)) {
1902 return false;
1903 } else {
1904 Slog.d(TAG, "Updated " + original + " to " + policy);
1905 return true;
1906 }
1907 }
1908
Felipe Lemef0823852016-06-08 13:43:08 -07001909 private void readPolicyAL() {
1910 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001911
1912 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001913 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001914 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001915 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001916 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001917
1918 FileInputStream fis = null;
1919 try {
1920 fis = mPolicyFile.openRead();
1921 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001922 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001923
Felipe Leme46b451f2016-08-19 08:46:17 -07001924 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1925 // to skip UIDs that were explicitly blacklisted.
1926 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1927
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001928 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001929 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001930 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001931 while ((type = in.next()) != END_DOCUMENT) {
1932 final String tag = in.getName();
1933 if (type == START_TAG) {
1934 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001935 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001936 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001937 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1938 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1940 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1941 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001942 final String networkId;
1943 if (version >= VERSION_ADDED_NETWORK_ID) {
1944 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1945 } else {
1946 networkId = null;
1947 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001948 final RecurrenceRule cycleRule;
1949 if (version >= VERSION_ADDED_CYCLE) {
1950 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1951 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1952 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1953 cycleRule = new RecurrenceRule(
1954 RecurrenceRule.convertZonedDateTime(start),
1955 RecurrenceRule.convertZonedDateTime(end),
1956 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001957 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001958 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1959 final String cycleTimezone;
1960 if (version >= VERSION_ADDED_TIMEZONE) {
1961 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1962 } else {
1963 cycleTimezone = "UTC";
1964 }
1965 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001966 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001967 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1968 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001969 final long lastLimitSnooze;
1970 if (version >= VERSION_SPLIT_SNOOZE) {
1971 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1972 } else if (version >= VERSION_ADDED_SNOOZE) {
1973 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001974 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001975 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001976 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001977 final boolean metered;
1978 if (version >= VERSION_ADDED_METERED) {
1979 metered = readBooleanAttribute(in, ATTR_METERED);
1980 } else {
1981 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001982 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001983 metered = true;
1984 break;
1985 default:
1986 metered = false;
1987 }
1988 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001989 final long lastWarningSnooze;
1990 if (version >= VERSION_SPLIT_SNOOZE) {
1991 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1992 } else {
1993 lastWarningSnooze = SNOOZE_NEVER;
1994 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001995 final boolean inferred;
1996 if (version >= VERSION_ADDED_INFERRED) {
1997 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1998 } else {
1999 inferred = false;
2000 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002001
Jeff Sharkey32566012014-12-02 18:30:14 -08002002 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2003 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002004 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002005 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2006 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002007 lastLimitSnooze, metered, inferred));
2008 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002009
2010 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2011 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2012 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2013 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2014 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2015 RecurrenceRule.convertZonedDateTime(start),
2016 RecurrenceRule.convertZonedDateTime(end),
2017 RecurrenceRule.convertPeriod(period));
2018 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2019 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2020
2021 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2022 SubscriptionPlan.BYTES_UNKNOWN);
2023 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2024 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2025 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2026 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2027 builder.setDataLimit(limitBytes, limitBehavior);
2028 }
2029
2030 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2031 SubscriptionPlan.BYTES_UNKNOWN);
2032 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2033 SubscriptionPlan.TIME_UNKNOWN);
2034 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2035 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2036 builder.setDataUsage(usageBytes, usageTime);
2037 }
2038
2039 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2040 final SubscriptionPlan plan = builder.build();
2041 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2042 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2043
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002044 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2045 mSubscriptionPlansOwner.put(subId, ownerPackage);
2046
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002047 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048 final int uid = readIntAttribute(in, ATTR_UID);
2049 final int policy = readIntAttribute(in, ATTR_POLICY);
2050
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002051 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002052 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002053 } else {
2054 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2055 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002056 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002057 final int appId = readIntAttribute(in, ATTR_APP_ID);
2058 final int policy = readIntAttribute(in, ATTR_POLICY);
2059
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002060 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002061 // app policy is deprecated so this is only used in pre system user split.
2062 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002063 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002064 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002065 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002066 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002067 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002068 } else if (TAG_WHITELIST.equals(tag)) {
2069 insideWhitelist = true;
2070 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2071 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002072 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002073 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2074 final int uid = readIntAttribute(in, ATTR_UID);
2075 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002076 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002077 } else if (type == END_TAG) {
2078 if (TAG_WHITELIST.equals(tag)) {
2079 insideWhitelist = false;
2080 }
2081
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002082 }
2083 }
2084
Felipe Leme46b451f2016-08-19 08:46:17 -07002085 final int size = whitelistedRestrictBackground.size();
2086 for (int i = 0; i < size; i++) {
2087 final int uid = whitelistedRestrictBackground.keyAt(i);
2088 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2089 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2090 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2091 + " because its policy is " + uidPoliciesToString(policy));
2092 continue;
2093 }
2094 if (UserHandle.isApp(uid)) {
2095 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2096 if (LOGV)
2097 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2098 setUidPolicyUncheckedUL(uid, newPolicy, false);
2099 } else {
2100 Slog.w(TAG, "unable to update policy on UID " + uid);
2101 }
2102 }
2103
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002104 } catch (FileNotFoundException e) {
2105 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002106 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002107 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002108 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002109 } finally {
2110 IoUtils.closeQuietly(fis);
2111 }
2112 }
2113
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002114 /**
2115 * Upgrade legacy background data flags, notifying listeners of one last
2116 * change to always-true.
2117 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002118 private void upgradeDefaultBackgroundDataUL() {
2119 // This method is only called when we're unable to find the network policy flag, which
2120 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002121
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002122 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002123 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002124 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2125
2126 // NOTE: We used to read the legacy setting here :
2127 //
2128 // final int legacyFlagValue = Settings.Secure.getInt(
2129 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2130 //
2131 // This is no longer necessary because we will never upgrade directly from Gingerbread
2132 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2133 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002134 }
2135
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002136 /**
2137 * Perform upgrade step of moving any user-defined meterness overrides over
2138 * into {@link WifiConfiguration}.
2139 */
2140 private void upgradeWifiMeteredOverrideAL() {
2141 boolean modified = false;
2142 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2143 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2144 for (int i = 0; i < mNetworkPolicy.size(); ) {
2145 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2146 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2147 && !policy.inferred) {
2148 mNetworkPolicy.removeAt(i);
2149 modified = true;
2150
2151 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2152 for (WifiConfiguration config : configs) {
2153 if (Objects.equals(resolveNetworkId(config), networkId)) {
2154 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2155 config.meteredOverride = policy.metered
2156 ? WifiConfiguration.METERED_OVERRIDE_METERED
2157 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2158 wm.updateNetwork(config);
2159 }
2160 }
2161 } else {
2162 i++;
2163 }
2164 }
2165 if (modified) {
2166 writePolicyAL();
2167 }
2168 }
2169
Felipe Lemef0823852016-06-08 13:43:08 -07002170 void writePolicyAL() {
2171 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002172
2173 FileOutputStream fos = null;
2174 try {
2175 fos = mPolicyFile.startWrite();
2176
2177 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002178 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179 out.startDocument(null, true);
2180
2181 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002182 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002183 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184
2185 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002186 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2187 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002188 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002189 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002190
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002191 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002192 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2193 final String subscriberId = template.getSubscriberId();
2194 if (subscriberId != null) {
2195 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002196 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002197 final String networkId = template.getNetworkId();
2198 if (networkId != null) {
2199 out.attribute(null, ATTR_NETWORK_ID, networkId);
2200 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002201 writeStringAttribute(out, ATTR_CYCLE_START,
2202 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2203 writeStringAttribute(out, ATTR_CYCLE_END,
2204 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2205 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2206 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002207 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2208 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002209 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2210 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002211 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002212 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002213 out.endTag(null, TAG_NETWORK_POLICY);
2214 }
2215
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002216 // write all known subscription plans
2217 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2218 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002219 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002220 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2221 if (ArrayUtils.isEmpty(plans)) continue;
2222
2223 for (SubscriptionPlan plan : plans) {
2224 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2225 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002226 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002227 final RecurrenceRule cycleRule = plan.getCycleRule();
2228 writeStringAttribute(out, ATTR_CYCLE_START,
2229 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2230 writeStringAttribute(out, ATTR_CYCLE_END,
2231 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2232 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2233 RecurrenceRule.convertPeriod(cycleRule.period));
2234 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2235 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2236 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2237 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2238 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2239 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2240 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2241 }
2242 }
2243
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002244 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002245 for (int i = 0; i < mUidPolicy.size(); i++) {
2246 final int uid = mUidPolicy.keyAt(i);
2247 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002248
Jeff Sharkey497e4432011-06-14 17:27:29 -07002249 // skip writing empty policies
2250 if (policy == POLICY_NONE) continue;
2251
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002252 out.startTag(null, TAG_UID_POLICY);
2253 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002254 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002255 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002256 }
2257
2258 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002259
2260 // write all whitelists
2261 out.startTag(null, TAG_WHITELIST);
2262
Felipe Lemea9505cc2016-02-26 10:28:41 -08002263 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002264 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002265 for (int i = 0; i < size; i++) {
2266 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2267 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2268 writeIntAttribute(out, ATTR_UID, uid);
2269 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2270 }
2271
Felipe Lemeb85a6372016-01-14 16:16:16 -08002272 out.endTag(null, TAG_WHITELIST);
2273
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002274 out.endDocument();
2275
2276 mPolicyFile.finishWrite(fos);
2277 } catch (IOException e) {
2278 if (fos != null) {
2279 mPolicyFile.failWrite(fos);
2280 }
2281 }
2282 }
2283
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002284 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002285 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002286 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002287
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002288 if (!UserHandle.isApp(uid)) {
2289 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002290 }
Felipe Lemef0823852016-06-08 13:43:08 -07002291 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002292 final long token = Binder.clearCallingIdentity();
2293 try {
2294 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2295 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002296 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002297 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002298 }
2299 } finally {
2300 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002301 }
2302 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002303 }
2304
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002305 @Override
2306 public void addUidPolicy(int uid, int policy) {
2307 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002308
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002309 if (!UserHandle.isApp(uid)) {
2310 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2311 }
2312
Felipe Lemef0823852016-06-08 13:43:08 -07002313 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002314 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2315 policy |= oldPolicy;
2316 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002317 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002318 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002319 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002320 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002321 }
2322
2323 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002324 public void removeUidPolicy(int uid, int policy) {
2325 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2326
2327 if (!UserHandle.isApp(uid)) {
2328 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2329 }
2330
Felipe Lemef0823852016-06-08 13:43:08 -07002331 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002332 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2333 policy = oldPolicy & ~policy;
2334 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002335 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002336 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002337 }
2338 }
2339 }
2340
Felipe Lemef0823852016-06-08 13:43:08 -07002341 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002342 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002343
Felipe Leme57e3d312016-08-23 14:42:52 -07002344 final boolean notifyApp;
2345 if (!isUidValidForWhitelistRules(uid)) {
2346 notifyApp = false;
2347 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002348 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2349 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2350 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2351 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002352 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2353 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002354 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2355 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2356 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2357 if (LOGD)
2358 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2359 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2360 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002361 notifyApp = wasBlocked != isBlocked;
2362 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002363 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2364 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002365 if (persist) {
2366 synchronized (mNetworkPoliciesSecondLock) {
2367 writePolicyAL();
2368 }
2369 }
Felipe Leme923845f2016-03-02 13:42:48 -08002370 }
2371
Felipe Lemef0823852016-06-08 13:43:08 -07002372 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002373 if (policy == POLICY_NONE) {
2374 mUidPolicy.delete(uid);
2375 } else {
2376 mUidPolicy.put(uid, policy);
2377 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002378
2379 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002380 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002381 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002382 synchronized (mNetworkPoliciesSecondLock) {
2383 writePolicyAL();
2384 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002385 }
2386 }
2387
2388 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002389 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002390 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2391
Felipe Lemef0823852016-06-08 13:43:08 -07002392 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002393 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002394 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002395 }
2396
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002397 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002398 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002399 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2400
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002401 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002402 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002403 for (int i = 0; i < mUidPolicy.size(); i++) {
2404 final int uid = mUidPolicy.keyAt(i);
2405 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002406 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2407 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002408 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002409 }
2410 }
2411 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002412 return uids;
2413 }
2414
2415 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002416 * Removes any persistable state associated with given {@link UserHandle}, persisting
2417 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002418 */
Felipe Lemef0823852016-06-08 13:43:08 -07002419 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002420
Sudheer Shanka352dc572017-09-22 17:09:38 -07002421 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002422 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002423
Felipe Lemea110eec2016-04-29 09:58:06 -07002424 // Remove entries from revoked default restricted background UID whitelist
2425 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2426 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2427 if (UserHandle.getUserId(uid) == userId) {
2428 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002429 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002430 }
2431 }
2432
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002433 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002434 int[] uids = new int[0];
2435 for (int i = 0; i < mUidPolicy.size(); i++) {
2436 final int uid = mUidPolicy.keyAt(i);
2437 if (UserHandle.getUserId(uid) == userId) {
2438 uids = appendInt(uids, uid);
2439 }
2440 }
2441
2442 if (uids.length > 0) {
2443 for (int uid : uids) {
2444 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002445 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002446 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002447 }
Felipe Lemef0823852016-06-08 13:43:08 -07002448 synchronized (mNetworkPoliciesSecondLock) {
2449 updateRulesForGlobalChangeAL(true);
2450 if (writePolicy && changed) {
2451 writePolicyAL();
2452 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002453 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002454 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002455 }
2456
2457 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002458 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002459 // TODO: create permission for observing network policy
2460 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002461 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002462 }
2463
2464 @Override
2465 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002466 // TODO: create permission for observing network policy
2467 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002468 mListeners.unregister(listener);
2469 }
2470
Jeff Sharkey1b861272011-05-22 00:34:52 -07002471 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002472 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002473 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2474
Felipe Leme6a05eee2016-02-19 14:43:51 -08002475 final long token = Binder.clearCallingIdentity();
2476 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002477 synchronized (mUidRulesFirstLock) {
2478 synchronized (mNetworkPoliciesSecondLock) {
2479 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002480 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002481 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002482 }
2483 } finally {
2484 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002485 }
2486 }
2487
Hugo Benichi446c9c92017-04-10 09:41:10 +09002488 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002489 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002490 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2491 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002492 }
2493
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002494 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002495 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002496 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002497 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002498 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2499 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2500 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002501 } catch (SecurityException e) {
2502 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002503
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002504 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2505 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2506 return new NetworkPolicy[0];
2507 }
Svet Ganov16a16892015-04-16 10:32:04 -07002508 }
2509
Felipe Lemef0823852016-06-08 13:43:08 -07002510 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002511 final int size = mNetworkPolicy.size();
2512 final NetworkPolicy[] policies = new NetworkPolicy[size];
2513 for (int i = 0; i < size; i++) {
2514 policies[i] = mNetworkPolicy.valueAt(i);
2515 }
2516 return policies;
2517 }
2518 }
2519
Felipe Lemef0823852016-06-08 13:43:08 -07002520 private void normalizePoliciesNL() {
2521 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002522 }
2523
Felipe Lemef0823852016-06-08 13:43:08 -07002524 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002525 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002526 final String[] merged = tele.getMergedSubscriberIds();
2527
2528 mNetworkPolicy.clear();
2529 for (NetworkPolicy policy : policies) {
2530 // When two normalized templates conflict, prefer the most
2531 // restrictive policy
2532 policy.template = NetworkTemplate.normalize(policy.template, merged);
2533 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2534 if (existing == null || existing.compareTo(policy) > 0) {
2535 if (existing != null) {
2536 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2537 }
2538 mNetworkPolicy.put(policy.template, policy);
2539 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002540 }
2541 }
2542
2543 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002544 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002545 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002546
2547 final long token = Binder.clearCallingIdentity();
2548 try {
2549 performSnooze(template, TYPE_LIMIT);
2550 } finally {
2551 Binder.restoreCallingIdentity(token);
2552 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002553 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002554
Dianne Hackborn497175b2014-07-01 12:56:08 -07002555 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002556 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002557 synchronized (mUidRulesFirstLock) {
2558 synchronized (mNetworkPoliciesSecondLock) {
2559 // find and snooze local policy that matches
2560 final NetworkPolicy policy = mNetworkPolicy.get(template);
2561 if (policy == null) {
2562 throw new IllegalArgumentException("unable to find policy for " + template);
2563 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002564
Felipe Lemef0823852016-06-08 13:43:08 -07002565 switch (type) {
2566 case TYPE_WARNING:
2567 policy.lastWarningSnooze = currentTime;
2568 break;
2569 case TYPE_LIMIT:
2570 policy.lastLimitSnooze = currentTime;
2571 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002572 case TYPE_RAPID:
2573 policy.lastRapidSnooze = currentTime;
2574 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002575 default:
2576 throw new IllegalArgumentException("unexpected type");
2577 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002578
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002579 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002580 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002581 }
2582 }
2583
2584 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002585 public void onTetheringChanged(String iface, boolean tethering) {
2586 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002587 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002588 if (mRestrictBackground && tethering) {
2589 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2590 setRestrictBackground(false);
2591 }
2592 }
2593 }
2594
2595 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002596 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002597 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002598 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002599 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2600 final long token = Binder.clearCallingIdentity();
2601 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002602 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002603 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002604 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002605 } finally {
2606 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002607 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002608 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002609 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002610 }
2611 }
2612
Felipe Lemef0823852016-06-08 13:43:08 -07002613 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002614 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002615 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002616 if (restrictBackground == mRestrictBackground) {
2617 // Ideally, UI should never allow this scenario...
2618 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002619 return;
2620 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002621 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2622 final boolean oldRestrictBackground = mRestrictBackground;
2623 mRestrictBackground = restrictBackground;
2624 // Must whitelist foreground apps before turning data saver mode on.
2625 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2626 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2627 updateRulesForRestrictBackgroundUL();
2628 try {
2629 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2630 Slog.e(TAG,
2631 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2632 mRestrictBackground = oldRestrictBackground;
2633 // TODO: if it knew the foreground apps (see TODO above), it could call
2634 // updateRulesForRestrictBackgroundUL() again to restore state.
2635 return;
2636 }
2637 } catch (RemoteException e) {
2638 // ignored; service lives in system_server
2639 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002640
Sudheer Shanka543339f2017-07-28 15:18:07 -07002641 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002642 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002643
2644 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2645 mRestrictBackgroundChangedInBsm = true;
2646 }
2647 synchronized (mNetworkPoliciesSecondLock) {
2648 updateNotificationsNL();
2649 writePolicyAL();
2650 }
2651 } finally {
2652 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002653 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002654 }
2655
2656 private void sendRestrictBackgroundChangedMsg() {
2657 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2658 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2659 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002660 }
2661
Felipe Lemeb85a6372016-01-14 16:16:16 -08002662 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002663 public int getRestrictBackgroundByCaller() {
2664 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2665 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002666
Felipe Lemef0823852016-06-08 13:43:08 -07002667 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002668 // Must clear identity because getUidPolicy() is restricted to system.
2669 final long token = Binder.clearCallingIdentity();
2670 final int policy;
2671 try {
2672 policy = getUidPolicy(uid);
2673 } finally {
2674 Binder.restoreCallingIdentity(token);
2675 }
2676 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2677 // App is blacklisted.
2678 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2679 }
Felipe Leme1b103232016-01-22 09:44:57 -08002680 if (!mRestrictBackground) {
2681 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2682 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002683 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002684 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2685 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2686 }
2687 }
2688
2689 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002690 public boolean getRestrictBackground() {
2691 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2692
Felipe Lemef0823852016-06-08 13:43:08 -07002693 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002694 return mRestrictBackground;
2695 }
2696 }
2697
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002698 @Override
2699 public void setDeviceIdleMode(boolean enabled) {
2700 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002701 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2702 try {
2703 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002704 if (mDeviceIdleMode == enabled) {
2705 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002706 }
Felipe Lemeea014392016-09-06 13:59:54 -07002707 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002708 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002709 if (mSystemReady) {
2710 // Device idle change means we need to rebuild rules for all
2711 // known apps, so do a global refresh.
2712 updateRulesForRestrictPowerUL();
2713 }
2714 }
2715 if (enabled) {
2716 EventLogTags.writeDeviceIdleOnPhase("net");
2717 } else {
2718 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002719 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002720 } finally {
2721 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002722 }
2723 }
2724
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002725 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002726 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2727 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002728 final long token = Binder.clearCallingIdentity();
2729 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002730 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2731 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2732 for (WifiConfiguration config : configs) {
2733 if (Objects.equals(resolveNetworkId(config), networkId)) {
2734 config.meteredOverride = meteredOverride;
2735 wm.updateNetwork(config);
2736 }
2737 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002738 } finally {
2739 Binder.restoreCallingIdentity(token);
2740 }
2741 }
2742
Jeff Sharkey46645002011-07-27 21:11:21 -07002743 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002744 @Deprecated
2745 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2746 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2747 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2748 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002749 }
2750
Jeff Sharkey53313d72017-07-13 16:47:32 -06002751 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2752 // Verify they're not lying about package name
2753 mAppOps.checkPackage(callingUid, callingPackage);
2754
Jeff Sharkey53313d72017-07-13 16:47:32 -06002755 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002756 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002757 final long token = Binder.clearCallingIdentity();
2758 try {
2759 si = mContext.getSystemService(SubscriptionManager.class)
2760 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002761 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002762 } finally {
2763 Binder.restoreCallingIdentity(token);
2764 }
2765
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002766 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002767 if (si != null) {
2768 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2769 return;
2770 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002771 }
2772
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002773 // Second check: has the CarrierService delegated access?
2774 if (config != null) {
2775 final String overridePackage = config
2776 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2777 if (!TextUtils.isEmpty(overridePackage)
2778 && Objects.equals(overridePackage, callingPackage)) {
2779 return;
2780 }
2781 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002782
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002783 // Third check: is caller the fallback/default CarrierService?
2784 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2785 if (!TextUtils.isEmpty(defaultPackage)
2786 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002787 return;
2788 }
2789
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002790 // Fourth check: is caller a testing app?
2791 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2792 if (!TextUtils.isEmpty(testPackage)
2793 && Objects.equals(testPackage, callingPackage)) {
2794 return;
2795 }
2796
2797 // Fifth check: is caller a legacy testing app?
2798 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2799 if (!TextUtils.isEmpty(legacyTestPackage)
2800 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002801 return;
2802 }
2803
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002804 // Final check: does the caller hold a permission?
2805 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002806 }
2807
2808 @Override
2809 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2810 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2811
Jeff Sharkey53313d72017-07-13 16:47:32 -06002812 final String fake = SystemProperties.get("fw.fake_plan");
2813 if (!TextUtils.isEmpty(fake)) {
2814 final List<SubscriptionPlan> plans = new ArrayList<>();
2815 if ("month_hard".equals(fake)) {
2816 plans.add(SubscriptionPlan.Builder
2817 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2818 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002819 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2820 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2821 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2822 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2823 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002824 plans.add(SubscriptionPlan.Builder
2825 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2826 .setTitle("G-Mobile Happy")
2827 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2828 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2829 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2830 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2831 .build());
2832 plans.add(SubscriptionPlan.Builder
2833 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2834 .setTitle("G-Mobile, Charged after limit")
2835 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2836 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2837 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2838 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2839 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002840 } else if ("month_soft".equals(fake)) {
2841 plans.add(SubscriptionPlan.Builder
2842 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2843 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2844 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2845 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002846 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2847 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2848 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2849 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2850 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002851 plans.add(SubscriptionPlan.Builder
2852 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2853 .setTitle("G-Mobile, Throttled after limit")
2854 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2855 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2856 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2857 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2858 .build());
2859 plans.add(SubscriptionPlan.Builder
2860 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2861 .setTitle("G-Mobile, No data connection after limit")
2862 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2863 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2864 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2865 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2866 .build());
2867
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002868 } else if ("month_over".equals(fake)) {
2869 plans.add(SubscriptionPlan.Builder
2870 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2871 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2872 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2873 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2874 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2875 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2876 .build());
2877 plans.add(SubscriptionPlan.Builder
2878 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2879 .setTitle("G-Mobile, Throttled after limit")
2880 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2881 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2882 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2883 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2884 .build());
2885 plans.add(SubscriptionPlan.Builder
2886 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2887 .setTitle("G-Mobile, No data connection after limit")
2888 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2889 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2890 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2891 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2892 .build());
2893
Jeff Sharkey53313d72017-07-13 16:47:32 -06002894 } else if ("month_none".equals(fake)) {
2895 plans.add(SubscriptionPlan.Builder
2896 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2897 .setTitle("G-Mobile")
2898 .build());
2899 } else if ("prepaid".equals(fake)) {
2900 plans.add(SubscriptionPlan.Builder
2901 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2902 ZonedDateTime.now().plusDays(10))
2903 .setTitle("G-Mobile")
2904 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2905 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2906 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2907 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2908 .build());
2909 } else if ("prepaid_crazy".equals(fake)) {
2910 plans.add(SubscriptionPlan.Builder
2911 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2912 ZonedDateTime.now().plusDays(10))
2913 .setTitle("G-Mobile Anytime")
2914 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2915 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2916 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2917 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2918 .build());
2919 plans.add(SubscriptionPlan.Builder
2920 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2921 ZonedDateTime.now().plusDays(20))
2922 .setTitle("G-Mobile Nickel Nights")
2923 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002924 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2925 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002926 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2927 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2928 .build());
2929 plans.add(SubscriptionPlan.Builder
2930 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2931 ZonedDateTime.now().plusDays(20))
2932 .setTitle("G-Mobile Bonus 3G")
2933 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002934 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002935 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2936 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2937 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2938 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002939 } else if ("unlimited".equals(fake)) {
2940 plans.add(SubscriptionPlan.Builder
2941 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2942 ZonedDateTime.now().plusDays(10))
2943 .setTitle("G-Mobile Awesome")
2944 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2945 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2946 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2947 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2948 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002949 }
2950 return plans.toArray(new SubscriptionPlan[plans.size()]);
2951 }
2952
Jeff Sharkey4635f102017-09-01 11:27:13 -06002953 synchronized (mNetworkPoliciesSecondLock) {
2954 // Only give out plan details to the package that defined them,
2955 // so that we don't risk leaking plans between apps. We always
2956 // let in core system components (like the Settings app).
2957 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2958 if (Objects.equals(ownerPackage, callingPackage)
2959 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2960 return mSubscriptionPlans.get(subId);
2961 } else {
2962 Log.w(TAG, "Not returning plans because caller " + callingPackage
2963 + " doesn't match owner " + ownerPackage);
2964 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002965 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002966 }
2967 }
2968
2969 @Override
2970 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2971 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2972
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002973 for (SubscriptionPlan plan : plans) {
2974 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002975 }
2976
2977 final long token = Binder.clearCallingIdentity();
2978 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002979 synchronized (mUidRulesFirstLock) {
2980 synchronized (mNetworkPoliciesSecondLock) {
2981 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002982 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002983
2984 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2985 .getSubscriberId(subId);
2986 ensureActiveMobilePolicyAL(subId, subscriberId);
2987 maybeUpdateMobilePolicyCycleAL(subId);
2988 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002989 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002990 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002991
2992 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2993 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2994 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2995 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002996 } finally {
2997 Binder.restoreCallingIdentity(token);
2998 }
2999 }
3000
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003001 /**
3002 * Only visible for testing purposes. This doesn't give any access to
3003 * existing plans; it simply lets the debug package define new plans.
3004 */
3005 void setSubscriptionPlansOwner(int subId, String packageName) {
3006 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3007 }
3008
Jeff Sharkey53313d72017-07-13 16:47:32 -06003009 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003010 public String getSubscriptionPlansOwner(int subId) {
3011 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3012 throw new SecurityException();
3013 }
3014
3015 synchronized (mNetworkPoliciesSecondLock) {
3016 return mSubscriptionPlansOwner.get(subId);
3017 }
3018 }
3019
3020 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003021 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3022 long timeoutMillis, String callingPackage) {
3023 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3024
3025 // We can only override when carrier told us about plans
3026 synchronized (mNetworkPoliciesSecondLock) {
3027 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3028 throw new IllegalStateException(
3029 "Must provide SubscriptionPlan information before overriding");
3030 }
3031 }
3032
3033 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3034 overrideMask, overrideValue, subId));
3035 if (timeoutMillis > 0) {
3036 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3037 overrideMask, 0, subId), timeoutMillis);
3038 }
3039 }
3040
3041 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003042 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003043 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003044
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003045 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3046
Dianne Hackborn497175b2014-07-01 12:56:08 -07003047 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003048 for (String arg : args) {
3049 argSet.add(arg);
3050 }
3051
Felipe Lemef0823852016-06-08 13:43:08 -07003052 synchronized (mUidRulesFirstLock) {
3053 synchronized (mNetworkPoliciesSecondLock) {
3054 if (argSet.contains("--unsnooze")) {
3055 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3056 mNetworkPolicy.valueAt(i).clearSnooze();
3057 }
3058
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003059 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003060
3061 fout.println("Cleared snooze timestamps");
3062 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003063 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003064
Felipe Lemef0823852016-06-08 13:43:08 -07003065 fout.print("System ready: "); fout.println(mSystemReady);
3066 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3067 fout.print("Restrict power: "); fout.println(mRestrictPower);
3068 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003069 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3070
3071 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003072 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003073 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003074 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3075 fout.println(mNetworkPolicy.valueAt(i).toString());
3076 }
3077 fout.decreaseIndent();
3078
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003079 fout.println();
3080 fout.println("Subscription plans:");
3081 fout.increaseIndent();
3082 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3083 final int subId = mSubscriptionPlans.keyAt(i);
3084 fout.println("Subscriber ID " + subId + ":");
3085 fout.increaseIndent();
3086 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3087 if (!ArrayUtils.isEmpty(plans)) {
3088 for (SubscriptionPlan plan : plans) {
3089 fout.println(plan);
3090 }
3091 }
3092 fout.decreaseIndent();
3093 }
3094 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003095
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003096 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003097 fout.println("Policy for UIDs:");
3098 fout.increaseIndent();
3099 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003100 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003101 final int uid = mUidPolicy.keyAt(i);
3102 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003103 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003104 fout.print(uid);
3105 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003106 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003107 fout.println();
3108 }
3109 fout.decreaseIndent();
3110
3111 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3112 if (size > 0) {
3113 fout.println("Power save whitelist (except idle) app ids:");
3114 fout.increaseIndent();
3115 for (int i = 0; i < size; i++) {
3116 fout.print("UID=");
3117 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3118 fout.print(": ");
3119 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3120 fout.println();
3121 }
3122 fout.decreaseIndent();
3123 }
3124
3125 size = mPowerSaveWhitelistAppIds.size();
3126 if (size > 0) {
3127 fout.println("Power save whitelist app ids:");
3128 fout.increaseIndent();
3129 for (int i = 0; i < size; i++) {
3130 fout.print("UID=");
3131 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3132 fout.print(": ");
3133 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3134 fout.println();
3135 }
3136 fout.decreaseIndent();
3137 }
3138
Felipe Lemef0823852016-06-08 13:43:08 -07003139 size = mDefaultRestrictBackgroundWhitelistUids.size();
3140 if (size > 0) {
3141 fout.println("Default restrict background whitelist uids:");
3142 fout.increaseIndent();
3143 for (int i = 0; i < size; i++) {
3144 fout.print("UID=");
3145 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3146 fout.println();
3147 }
3148 fout.decreaseIndent();
3149 }
3150
3151 size = mRestrictBackgroundWhitelistRevokedUids.size();
3152 if (size > 0) {
3153 fout.println("Default restrict background whitelist uids revoked by users:");
3154 fout.increaseIndent();
3155 for (int i = 0; i < size; i++) {
3156 fout.print("UID=");
3157 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3158 fout.println();
3159 }
3160 fout.decreaseIndent();
3161 }
3162
3163 final SparseBooleanArray knownUids = new SparseBooleanArray();
3164 collectKeys(mUidState, knownUids);
3165 collectKeys(mUidRules, knownUids);
3166
3167 fout.println("Status for all known UIDs:");
3168 fout.increaseIndent();
3169 size = knownUids.size();
3170 for (int i = 0; i < size; i++) {
3171 final int uid = knownUids.keyAt(i);
3172 fout.print("UID=");
3173 fout.print(uid);
3174
3175 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3176 fout.print(" state=");
3177 fout.print(state);
3178 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3179 fout.print(" (fg)");
3180 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003181 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003182 ? " (fg svc)" : " (bg)");
3183 }
3184
3185 final int uidRules = mUidRules.get(uid, RULE_NONE);
3186 fout.print(" rules=");
3187 fout.print(uidRulesToString(uidRules));
3188 fout.println();
3189 }
3190 fout.decreaseIndent();
3191
3192 fout.println("Status for just UIDs with rules:");
3193 fout.increaseIndent();
3194 size = mUidRules.size();
3195 for (int i = 0; i < size; i++) {
3196 final int uid = mUidRules.keyAt(i);
3197 fout.print("UID=");
3198 fout.print(uid);
3199 final int uidRules = mUidRules.get(uid, RULE_NONE);
3200 fout.print(" rules=");
3201 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003202 fout.println();
3203 }
3204 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003205
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003206 fout.println("Admin restricted uids for metered data:");
3207 fout.increaseIndent();
3208 size = mMeteredRestrictedUids.size();
3209 for (int i = 0; i < size; ++i) {
3210 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3211 fout.println(mMeteredRestrictedUids.valueAt(i));
3212 }
3213 fout.decreaseIndent();
3214
Sudheer Shanka352dc572017-09-22 17:09:38 -07003215 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003216 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003217 }
3218 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003219
3220 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003221 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003222 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003223 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003224 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003225 }
3226
3227 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003228 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003229 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3230
Felipe Lemef0823852016-06-08 13:43:08 -07003231 synchronized (mUidRulesFirstLock) {
3232 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003233 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003234 }
3235
Felipe Lemef0823852016-06-08 13:43:08 -07003236 private boolean isUidForegroundUL(int uid) {
3237 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003238 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3239 }
3240
Felipe Lemef0823852016-06-08 13:43:08 -07003241 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003242 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003243 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003244 }
3245
Felipe Lemef0823852016-06-08 13:43:08 -07003246 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003247 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3248 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3249 }
3250
Felipe Lemef0823852016-06-08 13:43:08 -07003251 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003252 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003253 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003254 }
3255
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003256 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003257 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003258 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3259 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003260 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003261 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003262 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3263 try {
3264 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3265 if (oldUidState != uidState) {
3266 // state changed, push updated rules
3267 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003268 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3269 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3270 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003271 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003272 if (mDeviceIdleMode) {
3273 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003274 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003275 if (mRestrictPower) {
3276 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003277 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003278 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003279 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003280 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003281 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003282 } finally {
3283 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003284 }
3285 }
3286
Felipe Lemef0823852016-06-08 13:43:08 -07003287 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003288 final int index = mUidState.indexOfKey(uid);
3289 if (index >= 0) {
3290 final int oldUidState = mUidState.valueAt(index);
3291 mUidState.removeAt(index);
3292 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003293 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003294 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003295 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003296 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003297 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003298 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003299 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003300 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003301 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003302 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003303 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003304 }
3305 }
3306
Felipe Lemef28983d2016-03-25 12:18:23 -07003307 // adjust stats accounting based on foreground status
3308 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003309 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3310 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3311 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3312 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003313 try {
3314 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003315 } finally {
3316 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003317 }
3318 }
3319
Sudheer Shankac9d94072017-02-22 22:13:55 +00003320 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3321 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003322 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003323 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003324 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003325 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003326 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003327 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003328 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003329 }
3330
Felipe Lemef0823852016-06-08 13:43:08 -07003331 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003332 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3333 try {
3334 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3335 mUidFirewallPowerSaveRules);
3336 } finally {
3337 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3338 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003339 }
3340
Felipe Lemef0823852016-06-08 13:43:08 -07003341 void updateRuleForRestrictPowerUL(int uid) {
3342 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003343 }
3344
Felipe Lemef0823852016-06-08 13:43:08 -07003345 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003346 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3347 try {
3348 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3349 mUidFirewallDozableRules);
3350 } finally {
3351 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3352 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003353 }
3354
Felipe Lemef0823852016-06-08 13:43:08 -07003355 void updateRuleForDeviceIdleUL(int uid) {
3356 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003357 }
3358
Felipe Lemef28983d2016-03-25 12:18:23 -07003359 // NOTE: since both fw_dozable and fw_powersave uses the same map
3360 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003361 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003362 SparseIntArray rules) {
3363 if (enabled) {
3364 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003365 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003366 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003367 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003368 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003369 for (int ui = users.size() - 1; ui >= 0; ui--) {
3370 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003371 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3372 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3373 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3374 updateRulesForWhitelistedAppIds(uidRules,
3375 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003376 }
3377 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003378 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003379 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003380 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3381 }
3382 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003383 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003384 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003385 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003386 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003387 }
3388
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003389 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3390 final SparseBooleanArray whitelistedAppIds, int userId) {
3391 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3392 if (whitelistedAppIds.valueAt(i)) {
3393 final int appId = whitelistedAppIds.keyAt(i);
3394 final int uid = UserHandle.getUid(userId, appId);
3395 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3396 }
3397 }
3398 }
3399
3400 /**
3401 * @param deviceIdleMode if true then we don't consider
3402 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3403 * whitelisted.
3404 */
3405 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003406 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003407 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3408 || mPowerSaveWhitelistAppIds.get(appId);
3409 if (!deviceIdleMode) {
3410 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3411 }
3412 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003413 }
3414
Felipe Lemef28983d2016-03-25 12:18:23 -07003415 // NOTE: since both fw_dozable and fw_powersave uses the same map
3416 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003417 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003418 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003419 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3420 chain == FIREWALL_CHAIN_DOZABLE);
3421 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003422 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003423 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003424 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003425 }
3426 }
3427 }
3428
Felipe Lemef0823852016-06-08 13:43:08 -07003429 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003430 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3431 try {
3432 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3433 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003434
Felipe Leme873a83a2016-09-07 11:34:10 -07003435 // Fully update the app idle firewall chain.
3436 final List<UserInfo> users = mUserManager.getUsers();
3437 for (int ui = users.size() - 1; ui >= 0; ui--) {
3438 UserInfo user = users.get(ui);
3439 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3440 for (int uid : idleUids) {
3441 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3442 // quick check: if this uid doesn't have INTERNET permission, it
3443 // doesn't have network access anyway, so it is a waste to mess
3444 // with it here.
3445 if (hasInternetPermissions(uid)) {
3446 uidRules.put(uid, FIREWALL_RULE_DENY);
3447 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003448 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003449 }
3450 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003451
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003452 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003453 } finally {
3454 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3455 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003456 }
3457
Felipe Lemef0823852016-06-08 13:43:08 -07003458 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003459 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003460
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003461 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3462 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3463 }
3464 try {
3465 int appId = UserHandle.getAppId(uid);
3466 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3467 && !isUidForegroundOnRestrictPowerUL(uid)) {
3468 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3469 } else {
3470 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3471 }
3472 } finally {
3473 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003474 }
3475 }
3476
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003477 /**
3478 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3479 * changed.
3480 */
Felipe Lemef0823852016-06-08 13:43:08 -07003481 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003482 boolean paroled = mUsageStats.isAppIdleParoleOn();
3483 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003484 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003485
3486 int ruleCount = mUidFirewallStandbyRules.size();
3487 for (int i = 0; i < ruleCount; i++) {
3488 int uid = mUidFirewallStandbyRules.keyAt(i);
3489 int oldRules = mUidRules.get(uid);
3490 if (enableChain) {
3491 // Chain wasn't enabled before and the other power-related
3492 // chains are whitelists, so we can clear the
3493 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3494 // the effective rules result in blocking network access.
3495 oldRules &= MASK_METERED_NETWORKS;
3496 } else {
3497 // Skip if it had no restrictions to begin with
3498 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3499 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003500 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3501 if (newUidRules == RULE_NONE) {
3502 mUidRules.delete(uid);
3503 } else {
3504 mUidRules.put(uid, newUidRules);
3505 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003506 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003507 }
3508
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003509 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003510 * Update rules that might be changed by {@link #mRestrictBackground},
3511 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003512 */
Felipe Lemef0823852016-06-08 13:43:08 -07003513 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003514 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3515 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3516 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3517 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003518 try {
Felipe Leme09700462016-09-08 09:33:48 -07003519 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003520 updateRulesForRestrictPowerUL();
3521 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003522
Felipe Leme873a83a2016-09-07 11:34:10 -07003523 // If the set of restricted networks may have changed, re-evaluate those.
3524 if (restrictedNetworksChanged) {
3525 normalizePoliciesNL();
3526 updateNetworkRulesNL();
3527 }
3528 } finally {
3529 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003530 }
3531 }
3532
Felipe Leme09700462016-09-08 09:33:48 -07003533 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003534 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003535 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3536 try {
3537 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003538 updateRulesForPowerSaveUL();
3539 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3540 } finally {
3541 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3542 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003543 }
3544
Felipe Lemef0823852016-06-08 13:43:08 -07003545 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003546 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3547 try {
3548 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3549 } finally {
3550 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3551 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003552 }
3553
3554 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3555 private static final int TYPE_RESTRICT_POWER = 2;
3556 @Retention(RetentionPolicy.SOURCE)
3557 @IntDef(flag = false, value = {
3558 TYPE_RESTRICT_BACKGROUND,
3559 TYPE_RESTRICT_POWER,
3560 })
3561 public @interface RestrictType {
3562 }
3563
3564 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003565 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003566 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3567 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3568 }
3569 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003570 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003571
3572 final PackageManager pm = mContext.getPackageManager();
3573 final List<UserInfo> users;
3574 final List<ApplicationInfo> apps;
3575
3576 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3577 try {
3578 users = mUserManager.getUsers();
3579 } finally {
3580 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3581 }
3582 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3583 try {
3584 apps = pm.getInstalledApplications(
3585 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3586 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3587 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3588 } finally {
3589 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3590 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003591
Felipe Leme873a83a2016-09-07 11:34:10 -07003592 final int usersSize = users.size();
3593 final int appsSize = apps.size();
3594 for (int i = 0; i < usersSize; i++) {
3595 final UserInfo user = users.get(i);
3596 for (int j = 0; j < appsSize; j++) {
3597 final ApplicationInfo app = apps.get(j);
3598 final int uid = UserHandle.getUid(user.id, app.uid);
3599 switch (type) {
3600 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003601 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003602 break;
3603 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003604 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003605 break;
3606 default:
3607 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3608 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003609 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003610 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003611 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003612 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003613 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003614 }
3615
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003616 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003617 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003618 final int numUsers = users.size();
3619 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003620 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003621 int uid = UserHandle.getUid(user.id, appId);
3622 // Update external firewall rules.
3623 updateRuleForAppIdleUL(uid);
3624 updateRuleForDeviceIdleUL(uid);
3625 updateRuleForRestrictPowerUL(uid);
3626 // Update internal rules.
3627 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003628 }
3629 }
3630
Felipe Leme70c57c22016-03-29 10:45:13 -07003631 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3632 // methods below could be merged into a isUidValidForRules() method.
3633 private boolean isUidValidForBlacklistRules(int uid) {
3634 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003635 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003636 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003637 return true;
3638 }
3639
3640 return false;
3641 }
3642
Felipe Leme70c57c22016-03-29 10:45:13 -07003643 private boolean isUidValidForWhitelistRules(int uid) {
3644 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3645 }
3646
Amith Yamasani15e472352015-04-24 19:06:07 -07003647 private boolean isUidIdle(int uid) {
3648 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3649 final int userId = UserHandle.getUserId(uid);
3650
songjinshi0655edd2016-05-18 19:55:32 +08003651 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003652 for (String packageName : packages) {
3653 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3654 return false;
3655 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003656 }
3657 }
3658 return true;
3659 }
3660
3661 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003662 * Checks if an uid has INTERNET permissions.
3663 * <p>
3664 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003665 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003666 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003667 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003668 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003669 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003670 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003671 }
3672 } catch (RemoteException e) {
3673 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003674 return true;
3675 }
3676
3677 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003678 * Clears all state - internal and external - associated with an UID.
3679 */
3680 private void onUidDeletedUL(int uid) {
3681 // First cleanup in-memory state synchronously...
3682 mUidRules.delete(uid);
3683 mUidPolicy.delete(uid);
3684 mUidFirewallStandbyRules.delete(uid);
3685 mUidFirewallDozableRules.delete(uid);
3686 mUidFirewallPowerSaveRules.delete(uid);
3687 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3688 mPowerSaveWhitelistAppIds.delete(uid);
3689 mPowerSaveTempWhitelistAppIds.delete(uid);
3690
3691 // ...then update iptables asynchronously.
3692 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3693 }
3694
3695 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003696 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003697 *
Felipe Leme781ba142016-05-09 16:24:48 -07003698 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003699 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003700 * <li>Doze mode
3701 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003702 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003703 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003704 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003705 *
3706 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003707 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003708 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003709 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003710 updateRuleForDeviceIdleUL(uid);
3711 updateRuleForAppIdleUL(uid);
3712 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003713
3714 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003715 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003716
3717 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003718 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003719 }
3720
Felipe Leme70c57c22016-03-29 10:45:13 -07003721 /**
3722 * Applies network rules to bandwidth controllers based on process state and user-defined
3723 * restrictions (blacklist / whitelist).
3724 *
3725 * <p>
3726 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3727 * networks:
3728 * <ul>
3729 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3730 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3731 * also blacklisted.
3732 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3733 * no UIDs other those whitelisted will have access.
3734 * <ul>
3735 *
3736 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3737 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3738 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3739 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003740 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003741 * {@link INetworkManagementService}, but this method should also be called in events (like
3742 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3743 * following rules should also be applied:
3744 *
3745 * <ul>
3746 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3747 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3748 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3749 * {@code bw_penalty_box}.
3750 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3751 * </ul>
3752 *
3753 * <p>For optimization, the rules are only applied on user apps that have internet access
3754 * permission, since there is no need to change the {@code iptables} rule if the app does not
3755 * have permission to use the internet.
3756 *
3757 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003758 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003759 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003760 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003761 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3762 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3763 "updateRulesForDataUsageRestrictionsUL: " + uid);
3764 }
3765 try {
3766 updateRulesForDataUsageRestrictionsULInner(uid);
3767 } finally {
3768 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3769 }
3770 }
3771
3772 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003773 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003774 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003775 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003776 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003777
Dianne Hackborn497175b2014-07-01 12:56:08 -07003778 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003779 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003780 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003781 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003782
Felipe Leme781ba142016-05-09 16:24:48 -07003783 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003784 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003785 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3786 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003787
Felipe Leme70c57c22016-03-29 10:45:13 -07003788 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003789 if (isRestrictedByAdmin) {
3790 newRule = RULE_REJECT_METERED;
3791 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003792 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3793 newRule = RULE_TEMPORARY_ALLOW_METERED;
3794 } else if (isWhitelisted) {
3795 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003796 }
3797 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003798 if (isBlacklisted) {
3799 newRule = RULE_REJECT_METERED;
3800 } else if (mRestrictBackground && isWhitelisted) {
3801 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003802 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003803 }
Felipe Leme781ba142016-05-09 16:24:48 -07003804 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003805
Felipe Lemef28983d2016-03-25 12:18:23 -07003806 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003807 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003808 + ": isForeground=" +isForeground
3809 + ", isBlacklisted=" + isBlacklisted
3810 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003811 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003812 + ", oldRule=" + uidRulesToString(oldRule)
3813 + ", newRule=" + uidRulesToString(newRule)
3814 + ", newUidRules=" + uidRulesToString(newUidRules)
3815 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003816 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003817
Felipe Leme46c4fc32016-05-04 09:21:43 -07003818 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003819 mUidRules.delete(uid);
3820 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003821 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003822 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003823
Felipe Leme70c57c22016-03-29 10:45:13 -07003824 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003825 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003826 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003827 // Temporarily whitelist foreground app, removing from blacklist if necessary
3828 // (since bw_penalty_box prevails over bw_happy_box).
3829
3830 setMeteredNetworkWhitelist(uid, true);
3831 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3832 // but ideally it should be just:
3833 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003834 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003835 setMeteredNetworkBlacklist(uid, false);
3836 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003837 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003838 // Remove temporary whitelist from app that is not on foreground anymore.
3839
3840 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3841 // but ideally they should be just:
3842 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3843 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003844 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003845 setMeteredNetworkWhitelist(uid, false);
3846 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003847 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003848 setMeteredNetworkBlacklist(uid, true);
3849 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003850 } else if (hasRule(newRule, RULE_REJECT_METERED)
3851 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003852 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003853 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003854 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003855 // Since blacklist prevails over whitelist, we need to handle the special case
3856 // where app is whitelisted and blacklisted at the same time (although such
3857 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003858 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003859 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003860 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3861 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003862 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003863 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003864 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003865 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003866 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3867 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003868 + ", whitelisted=" + isWhitelisted
3869 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003870 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003871 + ", newRule=" + uidRulesToString(newUidRules)
3872 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003873 }
Felipe Leme781ba142016-05-09 16:24:48 -07003874
Sudheer Shankac9d94072017-02-22 22:13:55 +00003875 // Dispatch changed rule to existing listeners.
3876 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003877 }
3878 }
3879
3880 /**
3881 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3882 * listeners in case of change.
3883 * <p>
3884 * There are 3 power-related rules that affects whether an app has background access on
3885 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3886 * restriction, it's added to the equivalent firewall chain:
3887 * <ul>
3888 * <li>App is idle: {@code fw_standby} firewall chain.
3889 * <li>Device is idle: {@code fw_dozable} firewall chain.
3890 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3891 * </ul>
3892 * <p>
3893 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3894 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3895 * <p>
3896 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3897 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003898 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003899 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3900
Sudheer Shankac9d94072017-02-22 22:13:55 +00003901 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003902
Sudheer Shankac9d94072017-02-22 22:13:55 +00003903 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003904 mUidRules.delete(uid);
3905 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003906 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003907 }
3908 }
3909
3910 /**
3911 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3912 *
3913 * @param uid the uid of the app to update rules for
3914 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3915 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3916 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003917 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003918 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003919 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003920 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3921 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3922 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3923 + (paroled ? "P" : "-"));
3924 }
3925 try {
3926 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3927 } finally {
3928 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3929 }
3930 }
3931
3932 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003933 if (!isUidValidForBlacklistRules(uid)) {
3934 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003935 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003936 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003937
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003938 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003939 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003940 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003941
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003942 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003943 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3944 int newRule = RULE_NONE;
3945
3946 // First step: define the new rule based on user restrictions and foreground state.
3947
3948 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3949 // by considering the foreground and non-foreground states.
3950 if (isForeground) {
3951 if (restrictMode) {
3952 newRule = RULE_ALLOW_ALL;
3953 }
3954 } else if (restrictMode) {
3955 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3956 }
3957
3958 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3959
3960 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003961 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003962 + ", isIdle: " + isIdle
3963 + ", mRestrictPower: " + mRestrictPower
3964 + ", mDeviceIdleMode: " + mDeviceIdleMode
3965 + ", isForeground=" + isForeground
3966 + ", isWhitelisted=" + isWhitelisted
3967 + ", oldRule=" + uidRulesToString(oldRule)
3968 + ", newRule=" + uidRulesToString(newRule)
3969 + ", newUidRules=" + uidRulesToString(newUidRules)
3970 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3971 }
3972
Felipe Leme781ba142016-05-09 16:24:48 -07003973 // Second step: notify listeners if state changed.
3974 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003975 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003976 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003977 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003978 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3979 } else {
3980 // All scenarios should have been covered above
3981 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3982 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003983 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003984 + ", newRule=" + uidRulesToString(newUidRules)
3985 + ", oldRule=" + uidRulesToString(oldUidRules));
3986 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003987 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003988 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003989
Sudheer Shankac9d94072017-02-22 22:13:55 +00003990 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003991 }
3992
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003993 private class AppIdleStateChangeListener
3994 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3995
3996 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08003997 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
3998 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003999 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004000 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4001 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004002 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004003 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004004 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004005 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004006 }
4007 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004008 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004009 }
4010
4011 @Override
4012 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004013 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004014 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004015 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004016 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004017 }
4018 }
4019
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004020 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4021 if (listener != null) {
4022 try {
4023 listener.onUidRulesChanged(uid, uidRules);
4024 } catch (RemoteException ignored) {
4025 }
4026 }
4027 }
4028
4029 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4030 String[] meteredIfaces) {
4031 if (listener != null) {
4032 try {
4033 listener.onMeteredIfacesChanged(meteredIfaces);
4034 } catch (RemoteException ignored) {
4035 }
4036 }
4037 }
4038
4039 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4040 boolean restrictBackground) {
4041 if (listener != null) {
4042 try {
4043 listener.onRestrictBackgroundChanged(restrictBackground);
4044 } catch (RemoteException ignored) {
4045 }
4046 }
4047 }
4048
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004049 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4050 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004051 if (listener != null) {
4052 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004053 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004054 } catch (RemoteException ignored) {
4055 }
4056 }
4057 }
4058
Jeff Sharkey9252b342018-01-19 07:58:35 +09004059 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4060 int overrideMask, int overrideValue) {
4061 if (listener != null) {
4062 try {
4063 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4064 } catch (RemoteException ignored) {
4065 }
4066 }
4067 }
4068
Makoto Onuki8e777332017-03-28 11:25:47 -07004069 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004070 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004071 public boolean handleMessage(Message msg) {
4072 switch (msg.what) {
4073 case MSG_RULES_CHANGED: {
4074 final int uid = msg.arg1;
4075 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004076 final int length = mListeners.beginBroadcast();
4077 for (int i = 0; i < length; i++) {
4078 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4079 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004080 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004081 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004082 return true;
4083 }
4084 case MSG_METERED_IFACES_CHANGED: {
4085 final String[] meteredIfaces = (String[]) msg.obj;
4086 final int length = mListeners.beginBroadcast();
4087 for (int i = 0; i < length; i++) {
4088 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004089 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004090 }
4091 mListeners.finishBroadcast();
4092 return true;
4093 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004094 case MSG_LIMIT_REACHED: {
4095 final String iface = (String) msg.obj;
4096
Felipe Lemef0823852016-06-08 13:43:08 -07004097 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004098 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004099 // force stats update to make sure we have
4100 // numbers that caused alert to trigger.
4101 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004102
Felipe Lemef0823852016-06-08 13:43:08 -07004103 updateNetworkEnabledNL();
4104 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004105 }
4106 }
4107 return true;
4108 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004109 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4110 final boolean restrictBackground = msg.arg1 != 0;
4111 final int length = mListeners.beginBroadcast();
4112 for (int i = 0; i < length; i++) {
4113 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004114 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004115 }
4116 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004117 final Intent intent =
4118 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4119 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4120 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4121 return true;
4122 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004123 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004124 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004125 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004126 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004127 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004128 final int length = mListeners.beginBroadcast();
4129 for (int i = 0; i < length; i++) {
4130 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004131 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004132 }
4133 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004134 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4135 if (notifyApp.booleanValue()) {
4136 broadcastRestrictBackgroundChanged(uid, notifyApp);
4137 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004138 return true;
4139 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004140 case MSG_ADVISE_PERSIST_THRESHOLD: {
4141 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004142 // make sure stats are recorded frequently enough; we aim
4143 // for 2MB threshold for 2GB/month rules.
4144 final long persistThreshold = lowestRule / 1000;
4145 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004146 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004147 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004148 case MSG_UPDATE_INTERFACE_QUOTA: {
4149 removeInterfaceQuota((String) msg.obj);
4150 // int params need to be stitched back into a long
4151 setInterfaceQuota((String) msg.obj,
4152 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4153 return true;
4154 }
4155 case MSG_REMOVE_INTERFACE_QUOTA: {
4156 removeInterfaceQuota((String) msg.obj);
4157 return true;
4158 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004159 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4160 resetUidFirewallRules(msg.arg1);
4161 return true;
4162 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004163 case MSG_SUBSCRIPTION_OVERRIDE: {
4164 final int overrideMask = msg.arg1;
4165 final int overrideValue = msg.arg2;
4166 final int subId = (int) msg.obj;
4167 final int length = mListeners.beginBroadcast();
4168 for (int i = 0; i < length; i++) {
4169 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4170 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4171 }
4172 mListeners.finishBroadcast();
4173 return true;
4174 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004175 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4176 final int userId = msg.arg1;
4177 final Set<String> packageNames = (Set<String>) msg.obj;
4178 setMeteredRestrictedPackagesInternal(packageNames, userId);
4179 return true;
4180 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004181 default: {
4182 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004183 }
4184 }
4185 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004186 };
4187
4188 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4189 @Override
4190 public boolean handleMessage(Message msg) {
4191 switch (msg.what) {
4192 case UID_MSG_STATE_CHANGED: {
4193 final int uid = msg.arg1;
4194 final int procState = msg.arg2;
4195 final long procStateSeq = (Long) msg.obj;
4196
4197 handleUidChanged(uid, procState, procStateSeq);
4198 return true;
4199 }
4200 case UID_MSG_GONE: {
4201 final int uid = msg.arg1;
4202 handleUidGone(uid);
4203 return true;
4204 }
4205 default: {
4206 return false;
4207 }
4208 }
4209 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004210
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004211 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004212
Makoto Onuki8e777332017-03-28 11:25:47 -07004213 void handleUidChanged(int uid, int procState, long procStateSeq) {
4214 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4215 try {
4216 synchronized (mUidRulesFirstLock) {
4217 // We received a uid state change callback, add it to the history so that it
4218 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004219 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004220 // Now update the network policy rules as per the updated uid state.
4221 updateUidStateUL(uid, procState);
4222 // Updating the network rules is done, so notify AMS about this.
4223 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4224 }
4225 } finally {
4226 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4227 }
4228 }
4229
4230 void handleUidGone(int uid) {
4231 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4232 try {
4233 synchronized (mUidRulesFirstLock) {
4234 removeUidStateUL(uid);
4235 }
4236 } finally {
4237 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4238 }
4239 }
4240
Felipe Leme57e3d312016-08-23 14:42:52 -07004241 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4242 final PackageManager pm = mContext.getPackageManager();
4243 final String[] packages = pm.getPackagesForUid(uid);
4244 if (packages != null) {
4245 final int userId = UserHandle.getUserId(uid);
4246 for (String packageName : packages) {
4247 final Intent intent =
4248 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4249 intent.setPackage(packageName);
4250 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4251 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4252 }
4253 }
4254 }
4255
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004256 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4257 // long quotaBytes split up into two ints to fit in message
4258 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4259 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4260 }
4261
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004262 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004263 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004264 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004265 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004266 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004267 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004268 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004269 }
4270 }
4271
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004272 private void removeInterfaceQuotaAsync(String iface) {
4273 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4274 }
4275
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004276 private void removeInterfaceQuota(String iface) {
4277 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004278 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004279 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004280 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004281 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004282 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004283 }
4284 }
4285
Felipe Leme70c57c22016-03-29 10:45:13 -07004286 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4287 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004288 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004289 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004290 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004291 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4292 } catch (RemoteException e) {
4293 // ignored; service lives in system_server
4294 }
4295 }
4296
4297 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4298 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4299 try {
4300 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4301 } catch (IllegalStateException e) {
4302 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004303 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004304 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004305 }
4306 }
4307
Felipe Lemebc853dd2016-09-08 13:26:55 -07004308 private static final int CHAIN_TOGGLE_NONE = 0;
4309 private static final int CHAIN_TOGGLE_ENABLE = 1;
4310 private static final int CHAIN_TOGGLE_DISABLE = 2;
4311 @Retention(RetentionPolicy.SOURCE)
4312 @IntDef(flag = false, value = {
4313 CHAIN_TOGGLE_NONE,
4314 CHAIN_TOGGLE_ENABLE,
4315 CHAIN_TOGGLE_DISABLE
4316 })
4317 public @interface ChainToggleType {
4318 }
4319
4320 /**
4321 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004322 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004323 *
4324 * @param chain firewall chain.
4325 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4326 * @param toggle whether the chain should be enabled, disabled, or not changed.
4327 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004328 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004329 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004330 if (uidRules != null) {
4331 setUidFirewallRulesUL(chain, uidRules);
4332 }
4333 if (toggle != CHAIN_TOGGLE_NONE) {
4334 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4335 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004336 }
4337
Amith Yamasani15e472352015-04-24 19:06:07 -07004338 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004339 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4340 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4341 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004342 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004343 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004344 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004345 int size = uidRules.size();
4346 int[] uids = new int[size];
4347 int[] rules = new int[size];
4348 for(int index = size - 1; index >= 0; --index) {
4349 uids[index] = uidRules.keyAt(index);
4350 rules[index] = uidRules.valueAt(index);
4351 }
4352 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004353 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004354 } catch (IllegalStateException e) {
4355 Log.wtf(TAG, "problem setting firewall uid rules", e);
4356 } catch (RemoteException e) {
4357 // ignored; service lives in system_server
4358 }
4359 }
4360
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004361 /**
4362 * Add or remove a uid to the firewall blacklist for all network ifaces.
4363 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004364 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004365 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4366 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4367 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004368 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004369 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004370 if (chain == FIREWALL_CHAIN_DOZABLE) {
4371 mUidFirewallDozableRules.put(uid, rule);
4372 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4373 mUidFirewallStandbyRules.put(uid, rule);
4374 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4375 mUidFirewallPowerSaveRules.put(uid, rule);
4376 }
4377
4378 try {
4379 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004380 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004381 } catch (IllegalStateException e) {
4382 Log.wtf(TAG, "problem setting firewall uid rules", e);
4383 } catch (RemoteException e) {
4384 // ignored; service lives in system_server
4385 }
4386 } finally {
4387 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004388 }
4389 }
4390
4391 /**
4392 * Add or remove a uid to the firewall blacklist for all network ifaces.
4393 */
Felipe Lemef0823852016-06-08 13:43:08 -07004394 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004395 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4396 mFirewallChainStates.get(chain) == enable) {
4397 // All is the same, nothing to do.
4398 return;
4399 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004400 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004401 try {
4402 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004403 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004404 } catch (IllegalStateException e) {
4405 Log.wtf(TAG, "problem enable firewall chain", e);
4406 } catch (RemoteException e) {
4407 // ignored; service lives in system_server
4408 }
4409 }
4410
Felipe Leme03e95e22016-09-09 09:25:31 -07004411 /**
4412 * Resets all firewall rules associated with an UID.
4413 */
4414 private void resetUidFirewallRules(int uid) {
4415 try {
4416 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4417 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4418 mNetworkManager
4419 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4420 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4421 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4422 } catch (IllegalStateException e) {
4423 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4424 } catch (RemoteException e) {
4425 // ignored; service lives in system_server
4426 }
4427 }
4428
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004429 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004430 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004431 return getNetworkTotalBytes(template, start, end);
4432 }
4433
4434 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004435 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004436 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004437 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004438 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004439 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004440 }
4441 }
4442
4443 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4444 try {
4445 return mNetworkStats.getNetworkUidBytes(template, start, end);
4446 } catch (RuntimeException e) {
4447 Slog.w(TAG, "Failed to read network stats: " + e);
4448 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004449 }
4450 }
4451
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004452 private boolean isBandwidthControlEnabled() {
4453 final long token = Binder.clearCallingIdentity();
4454 try {
4455 return mNetworkManager.isBandwidthControlEnabled();
4456 } catch (RemoteException e) {
4457 // ignored; service lives in system_server
4458 return false;
4459 } finally {
4460 Binder.restoreCallingIdentity(token);
4461 }
4462 }
4463
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004464 private static Intent buildAllowBackgroundDataIntent() {
4465 return new Intent(ACTION_ALLOW_BACKGROUND);
4466 }
4467
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004468 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4469 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004470 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4471 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4472 return intent;
4473 }
4474
4475 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4476 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4477 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004478 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4479 return intent;
4480 }
4481
Wei Liu546cb772016-07-21 16:19:01 -07004482 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004483 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004484 intent.setComponent(ComponentName.unflattenFromString(
4485 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004486 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4487 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4488 return intent;
4489 }
4490
Wei Liu546cb772016-07-21 16:19:01 -07004491 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004492 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004493 intent.setComponent(ComponentName.unflattenFromString(
4494 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004495 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4496 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4497 return intent;
4498 }
4499
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004500 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004501 public void addIdleHandler(IdleHandler handler) {
4502 mHandler.getLooper().getQueue().addIdleHandler(handler);
4503 }
4504
jackqdyulei29c82ab2017-03-10 14:09:16 -08004505 @VisibleForTesting
4506 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4507 mRestrictBackgroundPowerState = result;
4508
4509 boolean restrictBackground = result.batterySaverEnabled;
4510 boolean shouldInvokeRestrictBackground;
4511 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4512 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4513
4514 if (result.globalBatterySaverEnabled) {
4515 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4516 // turn it on.
4517 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4518 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4519 localRestrictBgChangedInBsm = false;
4520 } else {
4521 // Try to restore the restrictBackground if it doesn't change in bsm
4522 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4523 restrictBackground = mRestrictBackgroundBeforeBsm;
4524 }
4525
4526 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004527 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004528 }
4529
4530 // Change it at last so setRestrictBackground() won't affect this variable
4531 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4532 }
4533
Jeff Sharkey1b861272011-05-22 00:34:52 -07004534 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4535 final int size = source.size();
4536 for (int i = 0; i < size; i++) {
4537 target.put(source.keyAt(i), true);
4538 }
4539 }
4540
Stuart Scottf1fb3972015-04-02 18:00:02 -07004541 @Override
4542 public void factoryReset(String subscriber) {
4543 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4544
Stuart Scotte3e314d2015-04-20 14:07:45 -07004545 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4546 return;
4547 }
4548
Stuart Scottf1fb3972015-04-02 18:00:02 -07004549 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004550 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004551 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4552 for (NetworkPolicy policy : policies) {
4553 if (policy.template.equals(template)) {
4554 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4555 policy.inferred = false;
4556 policy.clearSnooze();
4557 }
4558 }
4559 setNetworkPolicies(policies);
4560
4561 // Turn restrict background data off
4562 setRestrictBackground(false);
4563
Stuart Scotte3e314d2015-04-20 14:07:45 -07004564 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4565 // Remove app's "restrict background data" flag
4566 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4567 setUidPolicy(uid, POLICY_NONE);
4568 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004569 }
4570 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004571
Sudheer Shankab8f23162017-08-04 13:30:10 -07004572 @Override
4573 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4574 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4575 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4576 }
4577
4578 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4579 final int uidRules;
4580 final boolean isBackgroundRestricted;
4581 synchronized (mUidRulesFirstLock) {
4582 uidRules = mUidRules.get(uid, RULE_NONE);
4583 isBackgroundRestricted = mRestrictBackground;
4584 }
4585 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004586 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004587 return true;
4588 }
4589 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004590 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004591 return false;
4592 }
4593 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004594 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004595 return true;
4596 }
4597 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004598 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004599 return false;
4600 }
4601 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004602 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004603 return false;
4604 }
4605 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004606 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004607 return true;
4608 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004609 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004610 return false;
4611 }
4612
Felipe Lemed17fda42016-04-29 11:12:45 -07004613 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4614
4615 @Override
4616 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004617 synchronized (mUidRulesFirstLock) {
4618 boolean changed = removeUserStateUL(userId, false);
4619 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004620 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004621 synchronized (mNetworkPoliciesSecondLock) {
4622 writePolicyAL();
4623 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004624 }
4625 }
4626 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004627
4628 /**
4629 * @return true if the given uid is restricted from doing networking on metered networks.
4630 */
4631 @Override
4632 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4633 final int uidRules;
4634 final boolean isBackgroundRestricted;
4635 synchronized (mUidRulesFirstLock) {
4636 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4637 isBackgroundRestricted = mRestrictBackground;
4638 }
4639 return isBackgroundRestricted
4640 && !hasRule(uidRules, RULE_ALLOW_METERED)
4641 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4642 }
4643
4644 /**
4645 * @return true if networking is blocked on the given interface for the given uid according
4646 * to current networking policies.
4647 */
4648 @Override
4649 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004650 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004651 synchronized (mNetworkPoliciesSecondLock) {
4652 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004653 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004654 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004655 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004656
4657 @Override
4658 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4659 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004660 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004661 if (added) {
4662 mPowerSaveTempWhitelistAppIds.put(appId, true);
4663 } else {
4664 mPowerSaveTempWhitelistAppIds.delete(appId);
4665 }
4666 updateRulesForTempWhitelistChangeUL(appId);
4667 }
4668 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004669
4670 @Override
4671 public SubscriptionPlan getSubscriptionPlan(Network network) {
4672 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004673 final int subId = getSubIdLocked(network);
4674 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004675 }
4676 }
4677
4678 @Override
4679 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4680 synchronized (mNetworkPoliciesSecondLock) {
4681 // TODO: handle splitting quota between use-cases
4682 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network));
4683 }
4684 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004685
4686 @Override
4687 public void onAdminDataAvailable() {
4688 mAdminDataAvailableLatch.countDown();
4689 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004690
4691 @Override
4692 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4693 setMeteredRestrictedPackagesInternal(packageNames, userId);
4694 }
4695
4696 @Override
4697 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4698 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4699 userId, 0, packageNames).sendToTarget();
4700 }
4701 }
4702
4703 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4704 synchronized (mUidRulesFirstLock) {
4705 final Set<Integer> newRestrictedUids = new ArraySet<>();
4706 for (String packageName : packageNames) {
4707 final int uid = getUidForPackage(packageName, userId);
4708 if (uid >= 0) {
4709 newRestrictedUids.add(uid);
4710 }
4711 }
4712 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4713 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4714 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4715 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4716 }
4717 }
4718
4719 private int getUidForPackage(String packageName, int userId) {
4720 try {
4721 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4722 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4723 } catch (NameNotFoundException e) {
4724 return -1;
4725 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004726 }
4727
4728 private int parseSubId(NetworkState state) {
4729 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4730 int subId = INVALID_SUBSCRIPTION_ID;
4731 if (state != null && state.networkCapabilities != null
4732 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4733 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4734 if (spec instanceof StringNetworkSpecifier) {
4735 try {
4736 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4737 } catch (NumberFormatException e) {
4738 }
4739 }
4740 }
4741 return subId;
4742 }
4743
Andreas Gampea36dc622018-02-05 17:19:22 -08004744 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004745 private int getSubIdLocked(Network network) {
4746 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004747 }
4748
Andreas Gampea36dc622018-02-05 17:19:22 -08004749 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004750 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4751 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4752 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4753 }
4754
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004755 /**
4756 * This will only ever be called once - during device boot.
4757 */
4758 private void waitForAdminData() {
4759 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4760 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4761 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4762 }
4763 }
4764
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004765 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4766 Set<Integer> newRestrictedUids) {
4767 if (oldRestrictedUids == null) {
4768 for (int uid : newRestrictedUids) {
4769 updateRulesForDataUsageRestrictionsUL(uid);
4770 }
4771 return;
4772 }
4773 for (int uid : oldRestrictedUids) {
4774 if (!newRestrictedUids.contains(uid)) {
4775 updateRulesForDataUsageRestrictionsUL(uid);
4776 }
4777 }
4778 for (int uid : newRestrictedUids) {
4779 if (!oldRestrictedUids.contains(uid)) {
4780 updateRulesForDataUsageRestrictionsUL(uid);
4781 }
4782 }
4783 }
4784
4785 private boolean isRestrictedByAdminUL(int uid) {
4786 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4787 UserHandle.getUserId(uid));
4788 return restrictedUids != null && restrictedUids.contains(uid);
4789 }
4790
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004791 private static boolean hasRule(int uidRules, int rule) {
4792 return (uidRules & rule) != 0;
4793 }
4794
Jeff Sharkey2e471452018-01-19 18:02:47 +09004795 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4796 return (val != null) ? val : new NetworkState[0];
4797 }
4798
Chris Wren193ae6b2017-03-31 15:17:11 -04004799 private class NotificationId {
4800 private final String mTag;
4801 private final int mId;
4802
4803 NotificationId(NetworkPolicy policy, int type) {
4804 mTag = buildNotificationTag(policy, type);
4805 mId = type;
4806 }
4807
4808 @Override
4809 public boolean equals(Object o) {
4810 if (this == o) return true;
4811 if (!(o instanceof NotificationId)) return false;
4812 NotificationId that = (NotificationId) o;
4813 return Objects.equals(mTag, that.mTag);
4814 }
4815
4816 @Override
4817 public int hashCode() {
4818 return Objects.hash(mTag);
4819 }
4820
4821 /**
4822 * Build unique tag that identifies an active {@link NetworkPolicy}
4823 * notification of a specific type, like {@link #TYPE_LIMIT}.
4824 */
4825 private String buildNotificationTag(NetworkPolicy policy, int type) {
4826 return TAG + ":" + policy.template.hashCode() + ":" + type;
4827 }
4828
4829 public String getTag() {
4830 return mTag;
4831 }
4832
4833 public int getId() {
4834 return mId;
4835 }
4836 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004837}