blob: 8e7737312676248d2e5bf3ac0403becd89918a92 [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;
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +090042import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Jeff Sharkey9252b342018-01-19 07:58:35 +090043import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070044import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070045import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070046import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070047import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070048import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080049import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070050import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
51import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070052import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070053import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060054import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070056import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070057import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070059import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070060import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070061import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070062import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070063import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070064import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080065import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
66import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060067import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070068import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070069import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkeye0c29952018-02-20 17:24:55 -070070import static android.net.NetworkTemplate.MATCH_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070071import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070072import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080073import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060074import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
75import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
79import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070080import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070081import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060082import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090083import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080084
Jeff Sharkey854b2b12012-04-13 16:03:40 -070085import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070087import static com.android.internal.util.XmlUtils.readBooleanAttribute;
88import static com.android.internal.util.XmlUtils.readIntAttribute;
89import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060090import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070091import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
92import static com.android.internal.util.XmlUtils.writeIntAttribute;
93import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060094import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070095import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070096import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
97import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
98import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
99import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
100import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
102import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700103import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600104
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700105import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800106import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700107import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700108
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700109import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700110import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900111import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700112import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700113import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800114import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700115import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700116import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700117import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700118import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700119import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700120import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700121import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700122import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700123import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700124import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600125import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700126import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700127import android.content.Intent;
128import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700129import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700130import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700131import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700132import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700133import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700134import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600136import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700138import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700139import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700140import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700141import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700142import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600143import android.net.Network;
144import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700145import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700146import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700148import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600149import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900150import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700152import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700153import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900154import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600155import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700156import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700157import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700158import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700159import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700160import android.os.Environment;
161import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700162import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700163import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700164import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700165import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700166import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700167import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700169import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700170import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600171import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800172import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700173import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700174import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600175import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700176import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700177import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700178import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600179import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700180import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700181import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700182import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700183import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100184import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700185import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600186import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800187import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600188import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700189import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400190import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700191import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700192import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700193import android.util.ArrayMap;
194import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700195import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900196import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700197import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700198import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600199import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600200import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700201import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600202import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700203import android.util.SparseBooleanArray;
204import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900205import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700207
Jeff Sharkey497e4432011-06-14 17:27:29 -0700208import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700209import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800210import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400211import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500212import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700213import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800214import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800215import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600216import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700218import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600219import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700220import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700221import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700222import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800223import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600224
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600225import libcore.io.IoUtils;
226
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700227import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700228import org.xmlpull.v1.XmlSerializer;
229
230import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700231import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232import java.io.FileInputStream;
233import java.io.FileNotFoundException;
234import java.io.FileOutputStream;
235import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700236import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700237import java.lang.annotation.Retention;
238import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100239import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700240import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900241import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600242import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700243import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600244import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900245import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700247import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600248import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400249import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800250import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800251import java.util.concurrent.CountDownLatch;
252import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700254/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700255 * Service that maintains low-level network policy rules, using
256 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700257 * <p>
258 * Derives active rules by combining a given policy with other system status,
259 * and delivers to listeners, such as {@link ConnectivityManager}, for
260 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700261 *
262 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000263 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700264 * <ul>
265 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
266 * rules).
267 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
268 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000269 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
270 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700271 * </ul>
272 *
273 * <p>
274 * As such, methods that require synchronization have the following prefixes:
275 * <ul>
276 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
277 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000278 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
279 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700280 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700281 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700282public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700283 static final String TAG = NetworkPolicyLogger.TAG;
284 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
285 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700286
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900287 /**
288 * No opportunistic quota could be calculated from user data plan or data settings.
289 */
290 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
291
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700292 private static final int VERSION_INIT = 1;
293 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700294 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800295 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800296 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800297 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700298 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700299 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700300 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700301 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600302 private static final int VERSION_ADDED_CYCLE = 11;
303 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800305 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400306 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800307 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400308 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800309 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400310 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900311 @VisibleForTesting
312 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700313
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314 private static final String TAG_POLICY_LIST = "policy-list";
315 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600316 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700317 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700318 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800319 private static final String TAG_WHITELIST = "whitelist";
320 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800321 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322
323 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700324 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
326 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700327 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600328 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
329 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
330 private static final String ATTR_CYCLE_START = "cycleStart";
331 private static final String ATTR_CYCLE_END = "cycleEnd";
332 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700333 private static final String ATTR_WARNING_BYTES = "warningBytes";
334 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700335 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800336 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
337 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800338 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700339 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700340 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700341 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700342 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600343 private static final String ATTR_SUB_ID = "subId";
344 private static final String ATTR_TITLE = "title";
345 private static final String ATTR_SUMMARY = "summary";
346 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
347 private static final String ATTR_USAGE_BYTES = "usageBytes";
348 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600349 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800351 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800352 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800353 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800354 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700355 private static final String ACTION_SNOOZE_RAPID =
356 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700357
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800358 /**
359 * Indicates the maximum wait time for admin data to be available;
360 */
361 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
362
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600363 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
364 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
365 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
366 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
367
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700368 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700369 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800370 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800371 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700372 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700373 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
374 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700375 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700376 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900377 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800378 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700379 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700380
Makoto Onuki8e777332017-03-28 11:25:47 -0700381 private static final int UID_MSG_STATE_CHANGED = 100;
382 private static final int UID_MSG_GONE = 101;
383
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600384 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
385
Jeff Sharkey75279902011-05-24 18:39:45 -0700386 private final Context mContext;
387 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700388 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700389 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700390 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700391 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700392 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700393 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700394
395 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700396 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700397 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800398 @GuardedBy("mUidRulesFirstLock")
399 private PowerSaveState mRestrictBackgroundPowerState;
400
401 // Store the status of restrict background before turning on battery saver.
402 // Used to restore mRestrictBackground when battery saver is turned off.
403 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700404
Sudheer Shanka543339f2017-07-28 15:18:07 -0700405 // Denotes the status of restrict background read from disk.
406 private boolean mLoadedRestrictBackground;
407
Felipe Lemef0823852016-06-08 13:43:08 -0700408 // See main javadoc for instructions on how to use these locks.
409 final Object mUidRulesFirstLock = new Object();
410 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700411
Felipe Lemef0823852016-06-08 13:43:08 -0700412 @GuardedBy("allLocks") volatile boolean mSystemReady;
413
Felipe Lemef0823852016-06-08 13:43:08 -0700414 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
415 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
416 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800417 // Store whether user flipped restrict background in battery saver mode
418 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700419
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700420 private final boolean mSuppressDefaultPolicy;
421
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800422 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
423
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700424 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600425 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800426 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700427
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600428 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600429 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600430 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600431 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600432 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600433 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600434
Jeff Sharkey9252b342018-01-19 07:58:35 +0900435 /** Map from subId to daily opportunistic quota. */
436 @GuardedBy("mNetworkPoliciesSecondLock")
437 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
438
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700439 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700441 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700442 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700443
Felipe Lemef0823852016-06-08 13:43:08 -0700444 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700445 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700446 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700447 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700448 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800449 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700450
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700451 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700453 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
454
Jeff Sharkey32566012014-12-02 18:30:14 -0800455 /**
456 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700457 * in power save mode, except device idle (doze) still applies.
458 * TODO: An int array might be sufficient
459 */
Felipe Lemef0823852016-06-08 13:43:08 -0700460 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700461 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
462
463 /**
464 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800465 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700466 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800467 */
Felipe Lemef0823852016-06-08 13:43:08 -0700468 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700469 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700470
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700472 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
473
Felipe Lemeb85a6372016-01-14 16:16:16 -0800474 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800475 * UIDs that have been initially white-listed by system to avoid restricted background.
476 */
Felipe Lemef0823852016-06-08 13:43:08 -0700477 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800478 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
479 new SparseBooleanArray();
480
481 /**
482 * UIDs that have been initially white-listed by system to avoid restricted background,
483 * but later revoked by user.
484 */
Felipe Lemef0823852016-06-08 13:43:08 -0700485 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800486 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
487 new SparseBooleanArray();
488
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700489 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700490 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800491 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700492 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700493 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800494 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700495
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700496 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700497 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400498 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700499
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700500 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700501 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800502 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700503
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600504 /** Map from network ID to last observed meteredness state */
505 @GuardedBy("mNetworkPoliciesSecondLock")
506 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
507
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900508 /** Map from network ID to last observed roaming state */
509 @GuardedBy("mNetworkPoliciesSecondLock")
510 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
511
Jeff Sharkey9252b342018-01-19 07:58:35 +0900512 /** Map from netId to subId as of last update */
513 @GuardedBy("mNetworkPoliciesSecondLock")
514 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
515
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800516 /**
517 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
518 * userId to restricted uids which belong to that user.
519 */
520 @GuardedBy("mUidRulesFirstLock")
521 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
522
Jeff Sharkey32566012014-12-02 18:30:14 -0800523 private final RemoteCallbackList<INetworkPolicyListener>
524 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700525
Dianne Hackborn497175b2014-07-01 12:56:08 -0700526 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700527 @VisibleForTesting
528 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700529
530 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700531
Felipe Lemef0823852016-06-08 13:43:08 -0700532 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700533 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700534
Svet Ganov16a16892015-04-16 10:32:04 -0700535 private final AppOpsManager mAppOps;
536
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800537 private final IPackageManager mIPm;
538
Sudheer Shankae7361852017-03-07 11:51:46 -0800539 private ActivityManagerInternal mActivityManagerInternal;
540
Sudheer Shanka352dc572017-09-22 17:09:38 -0700541 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800542
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700543 // TODO: keep whitelist of system-critical services that should never have
544 // rules enforced, such as system, phone, and radio UIDs.
545
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700546 // TODO: migrate notifications to SystemUI
547
Jeff Sharkey75279902011-05-24 18:39:45 -0700548 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700549 INetworkManagementService networkManagement) {
550 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
551 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700552 }
553
Jeff Sharkey9911a282018-02-14 22:29:11 -0700554 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700555 return new File(Environment.getDataDirectory(), "system");
556 }
557
Jeff Sharkey9911a282018-02-14 22:29:11 -0700558 private static @NonNull Clock getDefaultClock() {
559 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
560 Clock.systemUTC());
561 }
562
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700563 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700564 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
565 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700566 mContext = checkNotNull(context, "missing context");
567 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700568 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700569 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700570 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700571 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700572 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700573 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700574 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700575
Amith Yamasani450a16b2013-09-18 16:28:50 -0700576 HandlerThread thread = new HandlerThread(TAG);
577 thread.start();
578 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700579
Makoto Onuki8e777332017-03-28 11:25:47 -0700580 // We create another thread for the UID events, which are more time-critical.
581 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
582 /*allowIo=*/ false);
583 mUidEventThread.start();
584 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
585
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700586 mSuppressDefaultPolicy = suppressDefaultPolicy;
587
Dianne Hackborne17b4452018-01-10 13:15:40 -0800588 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700589
590 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800591
Felipe Lemed17fda42016-04-29 11:12:45 -0700592 // Expose private service for system components to use.
593 LocalServices.addService(NetworkPolicyManagerInternal.class,
594 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700595 }
596
597 public void bindConnectivityManager(IConnectivityManager connManager) {
598 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700599 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700600
Felipe Lemef0823852016-06-08 13:43:08 -0700601 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700602 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700603 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
604 mPowerSaveWhitelistExceptIdleAppIds.clear();
605 if (whitelist != null) {
606 for (int uid : whitelist) {
607 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
608 }
609 }
610 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700611 mPowerSaveWhitelistAppIds.clear();
612 if (whitelist != null) {
613 for (int uid : whitelist) {
614 mPowerSaveWhitelistAppIds.put(uid, true);
615 }
616 }
617 } catch (RemoteException e) {
618 }
619 }
620
Felipe Lemea9505cc2016-02-26 10:28:41 -0800621 /**
622 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
623 * revoke the whitelist.
624 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700625 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800626 */
Felipe Lemef0823852016-06-08 13:43:08 -0700627 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800628 final List<UserInfo> users = mUserManager.getUsers();
629 final int numberUsers = users.size();
630
Felipe Lemea110eec2016-04-29 09:58:06 -0700631 boolean changed = false;
632 for (int i = 0; i < numberUsers; i++) {
633 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700634 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700635 }
636 return changed;
637 }
638
Felipe Lemef0823852016-06-08 13:43:08 -0700639 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700640 final SystemConfig sysConfig = SystemConfig.getInstance();
641 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800642 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
643 boolean changed = false;
644 for (int i = 0; i < allowDataUsage.size(); i++) {
645 final String pkg = allowDataUsage.valueAt(i);
646 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700647 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
648 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800649 final ApplicationInfo app;
650 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700651 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800652 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700653 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
654 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800655 continue;
656 }
657 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700658 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
659 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800660 continue;
661 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700662 final int uid = UserHandle.getUid(userId, app.uid);
663 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
664 if (LOGD)
665 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
666 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800667 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700668 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700669 if (LOGD)
670 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
671 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700672 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700673 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800674 }
675 }
676 return changed;
677 }
678
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800679 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700680 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800681 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700682 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800683 // Boost thread's priority during system server init
684 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700685 if (!isBandwidthControlEnabled()) {
686 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
687 return;
688 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700689
Felipe Leme873a83a2016-09-07 11:34:10 -0700690 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700691 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700692
Felipe Leme873a83a2016-09-07 11:34:10 -0700693 synchronized (mUidRulesFirstLock) {
694 synchronized (mNetworkPoliciesSecondLock) {
695 updatePowerSaveWhitelistUL();
696 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
697 mPowerManagerInternal.registerLowPowerModeObserver(
698 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800699 @Override
700 public int getServiceType() {
701 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700702 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800703
704 @Override
705 public void onLowPowerModeChanged(PowerSaveState result) {
706 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800707 if (LOGD) {
708 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
709 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800710 synchronized (mUidRulesFirstLock) {
711 if (mRestrictPower != enabled) {
712 mRestrictPower = enabled;
713 updateRulesForRestrictPowerUL();
714 }
715 }
716 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800717 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800718 mRestrictPower = mPowerManagerInternal.getLowPowerState(
719 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700720
721 mSystemReady = true;
722
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800723 waitForAdminData();
724
Felipe Leme873a83a2016-09-07 11:34:10 -0700725 // read policy from disk
726 readPolicyAL();
727
jackqdyulei29c82ab2017-03-10 14:09:16 -0800728 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700729 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800730 mRestrictBackgroundPowerState = mPowerManagerInternal
731 .getLowPowerState(ServiceType.DATA_SAVER);
732 final boolean localRestrictBackground =
733 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700734 if (localRestrictBackground && !mLoadedRestrictBackground) {
735 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800736 }
737 mPowerManagerInternal.registerLowPowerModeObserver(
738 new PowerManagerInternal.LowPowerModeListener() {
739 @Override
740 public int getServiceType() {
741 return ServiceType.DATA_SAVER;
742 }
743
744 @Override
745 public void onLowPowerModeChanged(PowerSaveState result) {
746 synchronized (mUidRulesFirstLock) {
747 updateRestrictBackgroundByLowPowerModeUL(result);
748 }
749 }
750 });
751
Felipe Leme873a83a2016-09-07 11:34:10 -0700752 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
753 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700754 }
Felipe Lemef0823852016-06-08 13:43:08 -0700755
Sudheer Shanka543339f2017-07-28 15:18:07 -0700756 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700757 updateRulesForGlobalChangeAL(false);
758 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700759 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800760 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700761
Sudheer Shankae7361852017-03-07 11:51:46 -0800762 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700763 try {
764 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000765 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800766 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700767 mNetworkManager.registerObserver(mAlertObserver);
768 } catch (RemoteException e) {
769 // ignored; both services live in system_server
770 }
771
772 // listen for changes to power save whitelist
773 final IntentFilter whitelistFilter = new IntentFilter(
774 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
775 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
776
Felipe Leme873a83a2016-09-07 11:34:10 -0700777 // watch for network interfaces to be claimed
778 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
779 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
780
781 // listen for package changes to update policy
782 final IntentFilter packageFilter = new IntentFilter();
783 packageFilter.addAction(ACTION_PACKAGE_ADDED);
784 packageFilter.addDataScheme("package");
785 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
786
787 // listen for UID changes to update policy
788 mContext.registerReceiver(
789 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
790
791 // listen for user changes to update policy
792 final IntentFilter userFilter = new IntentFilter();
793 userFilter.addAction(ACTION_USER_ADDED);
794 userFilter.addAction(ACTION_USER_REMOVED);
795 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
796
797 // listen for stats update events
798 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
799 mContext.registerReceiver(
800 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
801
802 // listen for restrict background changes from notifications
803 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
804 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
805
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700806 // Listen for snooze from notifications
807 mContext.registerReceiver(mSnoozeReceiver,
808 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
809 mContext.registerReceiver(mSnoozeReceiver,
810 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700811
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600812 // listen for configured wifi networks to be loaded
813 final IntentFilter wifiFilter =
814 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
815 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700816
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700817 // listen for carrier config changes to update data cycle information
818 final IntentFilter carrierConfigFilter = new IntentFilter(
819 ACTION_CARRIER_CONFIG_CHANGED);
820 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
821
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600822 // listen for meteredness changes
823 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
824 new NetworkRequest.Builder().build(), mNetworkCallback);
825
Felipe Leme873a83a2016-09-07 11:34:10 -0700826 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800827 // tell systemReady() that the service has been initialized
828 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700829 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800830 // Restore the default priority after init is done
831 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700832 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700833 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700834 }
835
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800836 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
837 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
838 mHandler.post(() -> initService(initCompleteSignal));
839 return initCompleteSignal;
840 }
841
842 public void systemReady(CountDownLatch initCompleteSignal) {
843 // wait for initService to complete
844 try {
845 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
846 throw new IllegalStateException("Service " + TAG +" init timeout");
847 }
848 } catch (InterruptedException e) {
849 Thread.currentThread().interrupt();
850 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
851 }
852 }
853
Sudheer Shankac9d94072017-02-22 22:13:55 +0000854 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700855 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700856 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
857 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700858 }
859
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700860 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700861 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700862 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700863
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700864 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700865 }
866
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700867 @Override public void onUidIdle(int uid, boolean disabled) {
868 }
869
870 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700871 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700872 };
873
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700874 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700875 @Override
876 public void onReceive(Context context, Intent intent) {
877 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700878 synchronized (mUidRulesFirstLock) {
879 updatePowerSaveWhitelistUL();
880 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700881 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700882 }
883 }
884 };
885
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700886 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700887 @Override
888 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700889 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700890
891 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700892 final int uid = intent.getIntExtra(EXTRA_UID, -1);
893 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700894
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700895 if (ACTION_PACKAGE_ADDED.equals(action)) {
896 // update rules for UID, since it might be subject to
897 // global background data policy
898 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700899 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700900 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700901 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700902 }
903 }
904 };
905
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700906 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700907 @Override
908 public void onReceive(Context context, Intent intent) {
909 // on background handler thread, and UID_REMOVED is protected
910
911 final int uid = intent.getIntExtra(EXTRA_UID, -1);
912 if (uid == -1) return;
913
914 // remove any policy and update rules to clean up
915 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700916 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700917 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700918 synchronized (mNetworkPoliciesSecondLock) {
919 writePolicyAL();
920 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700921 }
922 }
923 };
924
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700925 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700926 @Override
927 public void onReceive(Context context, Intent intent) {
928 // on background handler thread, and USER_ADDED and USER_REMOVED
929 // broadcasts are protected
930
931 final String action = intent.getAction();
932 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
933 if (userId == -1) return;
934
Amith Yamasani15e472352015-04-24 19:06:07 -0700935 switch (action) {
936 case ACTION_USER_REMOVED:
937 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700938 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800939 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700940 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700941 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800942 // Removing outside removeUserStateUL since that can also be called when
943 // user resets app preferences.
944 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700945 if (action == ACTION_USER_ADDED) {
946 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700947 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700948 }
949 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700950 synchronized (mNetworkPoliciesSecondLock) {
951 updateRulesForGlobalChangeAL(true);
952 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700953 }
954 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700955 }
956 }
957 };
958
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700959 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700960 * Receiver that watches for {@link INetworkStatsService} updates, which we
961 * use to check against {@link NetworkPolicy#warningBytes}.
962 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700963 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700964 @Override
965 public void onReceive(Context context, Intent intent) {
966 // on background handler thread, and verified
967 // READ_NETWORK_USAGE_HISTORY permission above.
968
Felipe Lemef0823852016-06-08 13:43:08 -0700969 synchronized (mNetworkPoliciesSecondLock) {
970 updateNetworkEnabledNL();
971 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700972 }
973 }
974 };
975
976 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700977 * Receiver that watches for {@link Notification} control of
978 * {@link #mRestrictBackground}.
979 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700980 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700981 @Override
982 public void onReceive(Context context, Intent intent) {
983 // on background handler thread, and verified MANAGE_NETWORK_POLICY
984 // permission above.
985
986 setRestrictBackground(false);
987 }
988 };
989
990 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800991 * Receiver that watches for {@link Notification} control of
992 * {@link NetworkPolicy#lastWarningSnooze}.
993 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700994 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800995 @Override
996 public void onReceive(Context context, Intent intent) {
997 // on background handler thread, and verified MANAGE_NETWORK_POLICY
998 // permission above.
999
1000 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001001 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1002 performSnooze(template, TYPE_WARNING);
1003 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1004 performSnooze(template, TYPE_RAPID);
1005 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001006 }
1007 };
1008
1009 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001010 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001011 * we can perform upgrade logic. After initial upgrade logic, it updates
1012 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001013 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001014 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001015 @Override
1016 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001017 synchronized (mUidRulesFirstLock) {
1018 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001019 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001020 }
1021 }
1022 // Only need to perform upgrade logic once
1023 mContext.unregisterReceiver(this);
1024 }
1025 };
1026
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001027 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1028 Network network) {
1029 final boolean lastValue = lastValues.get(network.netId, false);
1030 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1031 if (changed) {
1032 lastValues.put(network.netId, newValue);
1033 }
1034 return changed;
1035 }
1036
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001037 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1038 @Override
1039 public void onCapabilitiesChanged(Network network,
1040 NetworkCapabilities networkCapabilities) {
1041 if (network == null || networkCapabilities == null) return;
1042
1043 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001044 final boolean newMetered = !networkCapabilities
1045 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001046 final boolean meteredChanged = updateCapabilityChange(
1047 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001048
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001049 final boolean newRoaming = !networkCapabilities
1050 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1051 final boolean roamingChanged = updateCapabilityChange(
1052 mNetworkRoaming, newRoaming, network);
1053
1054 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001055 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001056 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001057 }
1058 }
1059 }
1060 };
1061
1062 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001063 * Observer that watches for {@link INetworkManagementService} alerts.
1064 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001065 final private INetworkManagementEventObserver mAlertObserver
1066 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 @Override
1068 public void limitReached(String limitName, String iface) {
1069 // only someone like NMS should be calling us
1070 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1071
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001072 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1073 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 }
1075 }
1076 };
1077
1078 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001079 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1080 * to show visible notifications as needed.
1081 */
Felipe Lemef0823852016-06-08 13:43:08 -07001082 void updateNotificationsNL() {
1083 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001084
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001085 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001086 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001087 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088
1089 // TODO: when switching to kernel notifications, compute next future
1090 // cycle boundary to recompute notifications.
1091
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001092 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001093 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001094 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1095 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001096 // ignore policies that aren't relevant to user
1097 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001098 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099
Jeff Sharkey53313d72017-07-13 16:47:32 -06001100 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1101 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001102 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1103 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1104 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001105
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001106 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001107 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001108 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1109 if (snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001110 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001111 } else {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001112 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
Felipe Lemef0823852016-06-08 13:43:08 -07001113 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001114 }
1115
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001117 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001118
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001119 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1120 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001121 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 }
1123 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001124
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001125 // Warn if average usage over last 4 days is on track to blow pretty
1126 // far past the plan limits.
1127 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001128 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001129 final long recentStart = now - recentDuration;
1130 final long recentEnd = now;
1131 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001132
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001133 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001134 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001135 final long alertBytes = (policy.limitBytes * 3) / 2;
1136
1137 if (LOGD) {
1138 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1139 + projectedBytes + " alert " + alertBytes);
1140 }
1141
1142 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1143 - DateUtils.DAY_IN_MILLIS;
1144 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001145 enqueueNotification(policy, TYPE_RAPID, 0,
1146 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001147 }
1148 }
1149 }
1150
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001152 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001153 final NotificationId notificationId = beforeNotifs.valueAt(i);
1154 if (!mActiveNotifs.contains(notificationId)) {
1155 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 }
1157 }
1158 }
1159
1160 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001161 * Attempt to find a specific app to blame for rapid data usage during the
1162 * given time period.
1163 */
1164 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1165 long start, long end) {
1166 long totalBytes = 0;
1167 long maxBytes = 0;
1168 int maxUid = 0;
1169
1170 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1171 NetworkStats.Entry entry = null;
1172 for (int i = 0; i < stats.size(); i++) {
1173 entry = stats.getValues(i, entry);
1174 final long bytes = entry.rxBytes + entry.txBytes;
1175 totalBytes += bytes;
1176 if (bytes > maxBytes) {
1177 maxBytes = bytes;
1178 maxUid = entry.uid;
1179 }
1180 }
1181
1182 // Only point blame if the majority of usage was done by a single app.
1183 // TODO: support shared UIDs
1184 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1185 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001186 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001187 try {
1188 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1189 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1190 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1191 } catch (NameNotFoundException ignored) {
1192 }
1193 }
1194 }
1195
1196 return null;
1197 }
1198
1199 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001200 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001201 * current device state, such as when
1202 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1203 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001204 */
1205 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001206 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001207 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1208 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001209
Jeff Sharkey32566012014-12-02 18:30:14 -08001210 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001211 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001212 for (int subId : subIds) {
1213 final String subscriberId = tele.getSubscriberId(subId);
1214 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001215 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1216 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001217 if (template.matches(probeIdent)) {
1218 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001219 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001220 }
1221 return false;
1222 } else {
1223 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001224 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001225 }
1226
1227 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001228 * Notify that given {@link NetworkTemplate} is over
1229 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1230 */
Felipe Lemef0823852016-06-08 13:43:08 -07001231 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001232 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001233 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001234 mOverLimitNotified.add(template);
1235 }
1236 }
1237
Felipe Lemef0823852016-06-08 13:43:08 -07001238 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001239 mOverLimitNotified.remove(template);
1240 }
1241
1242 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001243 * Show notification for combined {@link NetworkPolicy} and specific type,
1244 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1245 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001246 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1247 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001248 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001249 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001250 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001251 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001252 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001253 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001254 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001255
1256 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001257 final CharSequence title;
1258 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001259 switch (type) {
1260 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001261 title = res.getText(R.string.data_usage_warning_title);
1262 body = res.getString(R.string.data_usage_warning_body,
1263 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001264
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001265 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001266
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001267 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1268 builder.setDeleteIntent(PendingIntent.getBroadcast(
1269 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1270
Wei Liu546cb772016-07-21 16:19:01 -07001271 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001272 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001273 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1274
Jeff Sharkey497e4432011-06-14 17:27:29 -07001275 break;
1276 }
1277 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001278 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001279 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001280 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001281 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001282 case MATCH_WIFI:
1283 title = res.getText(R.string.data_usage_wifi_limit_title);
1284 break;
1285 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001286 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001287 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001288 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001289
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001290 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001291 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001292
Wei Liu546cb772016-07-21 16:19:01 -07001293 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001294 builder.setContentIntent(PendingIntent.getActivity(
1295 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1296 break;
1297 }
1298 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001299 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001300 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001301 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1302 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001303 case MATCH_WIFI:
1304 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1305 break;
1306 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001307 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001308 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001309 final long overBytes = totalBytes - policy.limitBytes;
1310 body = res.getString(R.string.data_usage_limit_snoozed_body,
1311 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001312
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001313 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001314 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001315 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001316
Wei Liu546cb772016-07-21 16:19:01 -07001317 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001318 builder.setContentIntent(PendingIntent.getActivity(
1319 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001320 break;
1321 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001322 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001323 title = res.getText(R.string.data_usage_rapid_title);
1324 if (rapidBlame != null) {
1325 body = res.getString(R.string.data_usage_rapid_app_body,
1326 rapidBlame.loadLabel(mContext.getPackageManager()));
1327 } else {
1328 body = res.getString(R.string.data_usage_rapid_body);
1329 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001330
Jeff Sharkey2e471452018-01-19 18:02:47 +09001331 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001332
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001333 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1334 builder.setDeleteIntent(PendingIntent.getBroadcast(
1335 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1336
1337 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001338 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001339 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001340 break;
1341 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001342 default: {
1343 return;
1344 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001345 }
1346
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001347 builder.setTicker(title);
1348 builder.setContentTitle(title);
1349 builder.setContentText(body);
1350 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001351
1352 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1353 notificationId.getId(), builder.build(), UserHandle.ALL);
1354 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001355 }
1356
Chris Wren193ae6b2017-03-31 15:17:11 -04001357 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001358 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1359 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001360 }
1361
1362 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001364 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001366 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001367 @Override
1368 public void onReceive(Context context, Intent intent) {
1369 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1370 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001371
Hugo Benichi446c9c92017-04-10 09:41:10 +09001372 synchronized (mUidRulesFirstLock) {
1373 synchronized (mNetworkPoliciesSecondLock) {
1374 ensureActiveMobilePolicyAL();
1375 normalizePoliciesNL();
1376 updateNetworkEnabledNL();
1377 updateNetworkRulesNL();
1378 updateNotificationsNL();
1379 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001380 }
1381 }
1382 };
1383
Jeff Sharkey2e471452018-01-19 18:02:47 +09001384 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001385 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001386 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001387 final CountDownLatch latch = new CountDownLatch(1);
1388 mHandler.post(() -> {
1389 latch.countDown();
1390 });
1391 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001392 }
1393
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001394 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001395 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1396 * if necessary.
1397 *
1398 * @param subId that has its associated NetworkPolicy updated if necessary
1399 * @return if any policies were updated
1400 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001401 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1402 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001403
1404 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001405 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1406 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001407
1408 // find and update the mobile NetworkPolicy for this subscriber id
1409 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001410 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001411 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1412 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1413 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001414 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1415 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001416 }
1417 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001418 return policyUpdated;
1419 }
1420
1421 /**
1422 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1423 *
1424 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1425 * to do so, it returns the fallback value.
1426 *
1427 * @param config The CarrierConfig to read the value from.
1428 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1429 * @return cycleDay to use in the mobile NetworkPolicy.
1430 */
1431 @VisibleForTesting
1432 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1433 int fallbackCycleDay) {
1434 if (config == null) {
1435 return fallbackCycleDay;
1436 }
1437 int cycleDay =
1438 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1439 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1440 return fallbackCycleDay;
1441 }
1442 // validate cycleDay value
1443 final Calendar cal = Calendar.getInstance();
1444 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1445 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1446 Slog.e(TAG, "Invalid date in "
1447 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1448 return fallbackCycleDay;
1449 }
1450 return cycleDay;
1451 }
1452
1453 /**
1454 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1455 *
1456 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1457 * to do so, it returns the fallback value.
1458 *
1459 * @param config The CarrierConfig to read the value from.
1460 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1461 * @return warningBytes to use in the mobile NetworkPolicy.
1462 */
1463 @VisibleForTesting
1464 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1465 long fallbackWarningBytes) {
1466 if (config == null) {
1467 return fallbackWarningBytes;
1468 }
1469 long warningBytes =
1470 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1471
1472 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1473 return WARNING_DISABLED;
1474 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1475 return getPlatformDefaultWarningBytes();
1476 } else if (warningBytes < 0) {
1477 Slog.e(TAG, "Invalid value in "
1478 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1479 + "non-negative value but got: " + warningBytes);
1480 return fallbackWarningBytes;
1481 }
1482
1483 return warningBytes;
1484 }
1485
1486 /**
1487 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1488 *
1489 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1490 * to do so, it returns the fallback value.
1491 *
1492 * @param config The CarrierConfig to read the value from.
1493 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1494 * @return limitBytes to use in the mobile NetworkPolicy.
1495 */
1496 @VisibleForTesting
1497 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1498 long fallbackLimitBytes) {
1499 if (config == null) {
1500 return fallbackLimitBytes;
1501 }
1502 long limitBytes =
1503 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1504
1505 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1506 return LIMIT_DISABLED;
1507 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1508 return getPlatformDefaultLimitBytes();
1509 } else if (limitBytes < 0) {
1510 Slog.e(TAG, "Invalid value in "
1511 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1512 + "non-negative value but got: " + limitBytes);
1513 return fallbackLimitBytes;
1514 }
1515 return limitBytes;
1516 }
1517
1518 /**
1519 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1520 */
1521 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1522 @Override
1523 public void onReceive(Context context, Intent intent) {
1524 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1525 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1526
1527 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1528 return;
1529 }
1530 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001531 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001532 final String subscriberId = tele.getSubscriberId(subId);
1533
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001534 synchronized (mUidRulesFirstLock) {
1535 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001536 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001537 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001538 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001539 if (!updated) return;
1540 // update network and notification rules, as the data cycle changed and it's
1541 // possible that we should be triggering warnings/limits now
1542 handleNetworkPoliciesUpdateAL(true);
1543 }
1544 }
1545 }
1546 };
1547
1548 /**
1549 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1550 * one has been updated.
1551 *
1552 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1553 * update.
1554 */
1555 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1556 if (shouldNormalizePolicies) {
1557 normalizePoliciesNL();
1558 }
1559 updateNetworkEnabledNL();
1560 updateNetworkRulesNL();
1561 updateNotificationsNL();
1562 writePolicyAL();
1563 }
1564
1565 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566 * Proactively control network data connections when they exceed
1567 * {@link NetworkPolicy#limitBytes}.
1568 */
Felipe Lemef0823852016-06-08 13:43:08 -07001569 void updateNetworkEnabledNL() {
1570 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001571
1572 // TODO: reset any policy-disabled networks when any policy is removed
1573 // completely, which is currently rare case.
1574
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001575 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1576 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001577 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001578 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001579 setNetworkTemplateEnabled(policy.template, true);
1580 continue;
1581 }
1582
Jeff Sharkey53313d72017-07-13 16:47:32 -06001583 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1584 .cycleIterator(policy).next();
1585 final long start = cycle.first.toInstant().toEpochMilli();
1586 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001587 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001588
1589 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001590 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1591 && policy.lastLimitSnooze < start;
1592 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001593
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001594 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001595 }
1596 }
1597
1598 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001599 * Proactively disable networks that match the given
1600 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001601 */
1602 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001603 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1604 // held. Call it via the handler.
1605 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1606 .sendToTarget();
1607 }
1608
1609 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001610 // TODO: reach into ConnectivityManager to proactively disable bringing
1611 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001612
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001613 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001614 // If mobile data usage hits the limit or if the user resumes the data, we need to
1615 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001616 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1617 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001618
Jeff Sharkey2e471452018-01-19 18:02:47 +09001619 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001620 for (int subId : subIds) {
1621 final String subscriberId = tm.getSubscriberId(subId);
1622 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001623 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1624 true);
Jack Yu8781b682016-07-08 14:28:51 -07001625 // Template is matched when subscriber id matches.
1626 if (template.matches(probeIdent)) {
1627 tm.setPolicyDataEnabled(enabled, subId);
1628 }
1629 }
1630 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001631 }
1632
1633 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001634 * Collect all ifaces from a {@link NetworkState} into the given set.
1635 */
1636 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1637 final String baseIface = state.linkProperties.getInterfaceName();
1638 if (baseIface != null) {
1639 ifaces.add(baseIface);
1640 }
1641 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1642 final String stackedIface = stackedLink.getInterfaceName();
1643 if (stackedIface != null) {
1644 ifaces.add(stackedIface);
1645 }
1646 }
1647 }
1648
1649 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001650 * Examine all connected {@link NetworkState}, looking for
1651 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1652 * remaining quota based on usage cycle and historical stats.
1653 */
Felipe Lemef0823852016-06-08 13:43:08 -07001654 void updateNetworkRulesNL() {
1655 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656
1657 final NetworkState[] states;
1658 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001659 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001660 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001661 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 return;
1663 }
1664
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001665 // First, generate identities of all connected networks so we can
1666 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001667 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001668 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001670 if (state.network != null) {
1671 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1672 }
Wei Liub8eaf452016-01-25 10:32:27 -08001673 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001674 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1675 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001676 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 }
1678 }
1679
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001680 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001681 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001682
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001683 // For every well-defined policy, compute remaining data based on
1684 // current cycle and historical stats, and push to kernel.
1685 final ArraySet<String> matchingIfaces = new ArraySet<>();
1686 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1687 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1688
1689 // Collect all ifaces that match this policy
1690 matchingIfaces.clear();
1691 for (int j = identified.size() - 1; j >= 0; j--) {
1692 if (policy.template.matches(identified.valueAt(j))) {
1693 collectIfaces(matchingIfaces, identified.keyAt(j));
1694 }
1695 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001696
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001697 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001698 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001699 }
1700
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001701 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001702 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001703 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001704 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001705 if (hasLimit && policy.hasCycle()) {
1706 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1707 .cycleIterator(policy).next();
1708 final long start = cycle.first.toInstant().toEpochMilli();
1709 final long end = cycle.second.toInstant().toEpochMilli();
1710 final long totalBytes = getTotalBytes(policy.template, start, end);
1711
1712 if (policy.lastLimitSnooze >= start) {
1713 // snoozing past quota, but we still need to restrict apps,
1714 // so push really high quota.
1715 quotaBytes = Long.MAX_VALUE;
1716 } else {
1717 // remaining "quota" bytes are based on total usage in
1718 // current cycle. kernel doesn't like 0-byte rules, so we
1719 // set 1-byte quota and disable the radio later.
1720 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1721 }
1722 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001723 // metered network, but no policy limit; we still need to
1724 // restrict apps, so push really high quota.
1725 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001726 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001727
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001728 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001729 // TODO: switch to shared quota once NMS supports
1730 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001731 }
1732
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001733 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1734 final String iface = matchingIfaces.valueAt(j);
1735 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001736 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001737 }
1738 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001739
1740 // keep track of lowest warning or limit of active policies
1741 if (hasWarning && policy.warningBytes < lowestRule) {
1742 lowestRule = policy.warningBytes;
1743 }
1744 if (hasLimit && policy.limitBytes < lowestRule) {
1745 lowestRule = policy.limitBytes;
1746 }
1747 }
1748
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001749 // One final pass to catch any metered ifaces that don't have explicitly
1750 // defined policies; typically Wi-Fi networks.
1751 for (NetworkState state : states) {
1752 if (state.networkInfo != null && state.networkInfo.isConnected()
1753 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1754 matchingIfaces.clear();
1755 collectIfaces(matchingIfaces, state);
1756 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1757 final String iface = matchingIfaces.valueAt(j);
1758 if (!newMeteredIfaces.contains(iface)) {
1759 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1760 newMeteredIfaces.add(iface);
1761 }
1762 }
1763 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001764 }
1765
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001766 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001767 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1768 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001769 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001770 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001771 }
1772 }
1773 mMeteredIfaces = newMeteredIfaces;
1774
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001775 final ContentResolver cr = mContext.getContentResolver();
1776 final boolean quotaEnabled = Settings.Global.getInt(cr,
1777 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1778 final long quotaUnlimited = Settings.Global.getLong(cr,
1779 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1780 final float quotaLimited = Settings.Global.getFloat(cr,
1781 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1782
Jeff Sharkey9252b342018-01-19 07:58:35 +09001783 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001784 mSubscriptionOpportunisticQuota.clear();
1785 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001786 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001787 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001788 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001789 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001790 if (plan == null) continue;
1791
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001792 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001793 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001794 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1795 // Clamp to 0 when roaming
1796 quotaBytes = 0;
1797 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001798 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001799 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001800 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001801 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001802 } else {
1803 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001804 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1805 final long start = cycle.getLower().toInstant().toEpochMilli();
1806 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001807 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001808 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001809 .truncatedTo(ChronoUnit.DAYS)
1810 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001811 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001812 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1813 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001814 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001815 // Number of remaining days including current day
1816 final long remainingDays =
1817 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001818
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001819 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001820 }
1821
1822 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1823 }
1824
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001825 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001826 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001827
1828 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001829 }
1830
1831 /**
1832 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1833 * have at least a default mobile policy defined.
1834 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001835 private void ensureActiveMobilePolicyAL() {
1836 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001837 if (mSuppressDefaultPolicy) return;
1838
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001839 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1840 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001841
Jeff Sharkey2e471452018-01-19 18:02:47 +09001842 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001843 for (int subId : subIds) {
1844 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001845 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001846 }
1847 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001848
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001849 /**
1850 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1851 * have at least a default mobile policy defined.
1852 *
1853 * @param subId to build a default policy for
1854 * @param subscriberId that we check for an existing policy
1855 * @return true if a mobile network policy was added, or false one already existed.
1856 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001857 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001858 // Poke around to see if we already have a policy
1859 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001860 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001861 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1862 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1863 if (template.matches(probeIdent)) {
1864 if (LOGD) {
1865 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1866 + NetworkIdentity.scrubSubscriberId(subscriberId));
1867 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001868 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001869 }
1870 }
1871
Jeff Sharkey32566012014-12-02 18:30:14 -08001872 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1873 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001874 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001875 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001876 return true;
1877 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001878
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001879 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001880 final int dataWarningConfig = mContext.getResources().getInteger(
1881 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001882 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001883 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001884 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001885 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001886 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001887 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001888
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001889 private long getPlatformDefaultLimitBytes() {
1890 return LIMIT_DISABLED;
1891 }
1892
1893 @VisibleForTesting
1894 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001895 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001896 final RecurrenceRule cycleRule = NetworkPolicy
1897 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001898 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001899 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1900 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1901 synchronized (mUidRulesFirstLock) {
1902 synchronized (mNetworkPoliciesSecondLock) {
1903 updateDefaultMobilePolicyAL(subId, policy);
1904 }
1905 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001906 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001907 }
1908
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001909 /**
1910 * Update the given {@link NetworkPolicy} based on any carrier-provided
1911 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1912 * Leaves policy untouched if the user has modified it.
1913 *
1914 * @return if the policy was modified
1915 */
1916 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1917 if (!policy.inferred) {
1918 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1919 return false;
1920 }
1921
1922 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1923 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1924 policy.lastLimitSnooze, policy.metered, policy.inferred);
1925
1926 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1927 if (!ArrayUtils.isEmpty(plans)) {
1928 final SubscriptionPlan plan = plans[0];
1929 policy.cycleRule = plan.getCycleRule();
1930 final long planLimitBytes = plan.getDataLimitBytes();
1931 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1932 policy.warningBytes = getPlatformDefaultWarningBytes();
1933 policy.limitBytes = getPlatformDefaultLimitBytes();
1934 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1935 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1936 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1937 } else {
1938 policy.warningBytes = (planLimitBytes * 9) / 10;
1939 switch (plan.getDataLimitBehavior()) {
1940 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1941 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1942 policy.limitBytes = planLimitBytes;
1943 break;
1944 default:
1945 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1946 break;
1947 }
1948 }
1949 } else {
1950 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1951 final int currentCycleDay;
1952 if (policy.cycleRule.isMonthly()) {
1953 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1954 } else {
1955 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1956 }
1957 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1958 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1959 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1960 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1961 }
1962
1963 if (policy.equals(original)) {
1964 return false;
1965 } else {
1966 Slog.d(TAG, "Updated " + original + " to " + policy);
1967 return true;
1968 }
1969 }
1970
Felipe Lemef0823852016-06-08 13:43:08 -07001971 private void readPolicyAL() {
1972 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001973
1974 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001975 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001976 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001977 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001978 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001979
1980 FileInputStream fis = null;
1981 try {
1982 fis = mPolicyFile.openRead();
1983 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001984 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001985
Felipe Leme46b451f2016-08-19 08:46:17 -07001986 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1987 // to skip UIDs that were explicitly blacklisted.
1988 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1989
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001990 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001991 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001992 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001993 while ((type = in.next()) != END_DOCUMENT) {
1994 final String tag = in.getName();
1995 if (type == START_TAG) {
1996 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001997 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001999 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2000 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002001 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2002 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2003 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002004 final String networkId;
2005 if (version >= VERSION_ADDED_NETWORK_ID) {
2006 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2007 } else {
2008 networkId = null;
2009 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002010 final RecurrenceRule cycleRule;
2011 if (version >= VERSION_ADDED_CYCLE) {
2012 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2013 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2014 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2015 cycleRule = new RecurrenceRule(
2016 RecurrenceRule.convertZonedDateTime(start),
2017 RecurrenceRule.convertZonedDateTime(end),
2018 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002019 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002020 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2021 final String cycleTimezone;
2022 if (version >= VERSION_ADDED_TIMEZONE) {
2023 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2024 } else {
2025 cycleTimezone = "UTC";
2026 }
2027 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002028 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002029 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2030 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002031 final long lastLimitSnooze;
2032 if (version >= VERSION_SPLIT_SNOOZE) {
2033 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2034 } else if (version >= VERSION_ADDED_SNOOZE) {
2035 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002036 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002037 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002038 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002039 final boolean metered;
2040 if (version >= VERSION_ADDED_METERED) {
2041 metered = readBooleanAttribute(in, ATTR_METERED);
2042 } else {
2043 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002044 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002045 metered = true;
2046 break;
2047 default:
2048 metered = false;
2049 }
2050 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002051 final long lastWarningSnooze;
2052 if (version >= VERSION_SPLIT_SNOOZE) {
2053 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2054 } else {
2055 lastWarningSnooze = SNOOZE_NEVER;
2056 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002057 final boolean inferred;
2058 if (version >= VERSION_ADDED_INFERRED) {
2059 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2060 } else {
2061 inferred = false;
2062 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002063
Jeff Sharkey32566012014-12-02 18:30:14 -08002064 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2065 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002066 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002067 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2068 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002069 lastLimitSnooze, metered, inferred));
2070 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002071
2072 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2073 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2074 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2075 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2076 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2077 RecurrenceRule.convertZonedDateTime(start),
2078 RecurrenceRule.convertZonedDateTime(end),
2079 RecurrenceRule.convertPeriod(period));
2080 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2081 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2082
2083 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2084 SubscriptionPlan.BYTES_UNKNOWN);
2085 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2086 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2087 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2088 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2089 builder.setDataLimit(limitBytes, limitBehavior);
2090 }
2091
2092 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2093 SubscriptionPlan.BYTES_UNKNOWN);
2094 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2095 SubscriptionPlan.TIME_UNKNOWN);
2096 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2097 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2098 builder.setDataUsage(usageBytes, usageTime);
2099 }
2100
2101 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2102 final SubscriptionPlan plan = builder.build();
2103 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2104 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2105
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002106 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2107 mSubscriptionPlansOwner.put(subId, ownerPackage);
2108
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002109 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 final int uid = readIntAttribute(in, ATTR_UID);
2111 final int policy = readIntAttribute(in, ATTR_POLICY);
2112
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002113 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002114 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002115 } else {
2116 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2117 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002118 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002119 final int appId = readIntAttribute(in, ATTR_APP_ID);
2120 final int policy = readIntAttribute(in, ATTR_POLICY);
2121
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002122 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002123 // app policy is deprecated so this is only used in pre system user split.
2124 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002125 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002126 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002127 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002128 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002129 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002130 } else if (TAG_WHITELIST.equals(tag)) {
2131 insideWhitelist = true;
2132 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2133 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002134 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002135 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2136 final int uid = readIntAttribute(in, ATTR_UID);
2137 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002138 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002139 } else if (type == END_TAG) {
2140 if (TAG_WHITELIST.equals(tag)) {
2141 insideWhitelist = false;
2142 }
2143
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002144 }
2145 }
2146
Felipe Leme46b451f2016-08-19 08:46:17 -07002147 final int size = whitelistedRestrictBackground.size();
2148 for (int i = 0; i < size; i++) {
2149 final int uid = whitelistedRestrictBackground.keyAt(i);
2150 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2151 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2152 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2153 + " because its policy is " + uidPoliciesToString(policy));
2154 continue;
2155 }
2156 if (UserHandle.isApp(uid)) {
2157 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2158 if (LOGV)
2159 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2160 setUidPolicyUncheckedUL(uid, newPolicy, false);
2161 } else {
2162 Slog.w(TAG, "unable to update policy on UID " + uid);
2163 }
2164 }
2165
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002166 } catch (FileNotFoundException e) {
2167 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002168 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002169 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002170 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171 } finally {
2172 IoUtils.closeQuietly(fis);
2173 }
2174 }
2175
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002176 /**
2177 * Upgrade legacy background data flags, notifying listeners of one last
2178 * change to always-true.
2179 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002180 private void upgradeDefaultBackgroundDataUL() {
2181 // This method is only called when we're unable to find the network policy flag, which
2182 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002183
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002184 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002185 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002186 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2187
2188 // NOTE: We used to read the legacy setting here :
2189 //
2190 // final int legacyFlagValue = Settings.Secure.getInt(
2191 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2192 //
2193 // This is no longer necessary because we will never upgrade directly from Gingerbread
2194 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2195 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002196 }
2197
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002198 /**
2199 * Perform upgrade step of moving any user-defined meterness overrides over
2200 * into {@link WifiConfiguration}.
2201 */
2202 private void upgradeWifiMeteredOverrideAL() {
2203 boolean modified = false;
2204 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2205 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2206 for (int i = 0; i < mNetworkPolicy.size(); ) {
2207 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2208 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2209 && !policy.inferred) {
2210 mNetworkPolicy.removeAt(i);
2211 modified = true;
2212
2213 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2214 for (WifiConfiguration config : configs) {
2215 if (Objects.equals(resolveNetworkId(config), networkId)) {
2216 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2217 config.meteredOverride = policy.metered
2218 ? WifiConfiguration.METERED_OVERRIDE_METERED
2219 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2220 wm.updateNetwork(config);
2221 }
2222 }
2223 } else {
2224 i++;
2225 }
2226 }
2227 if (modified) {
2228 writePolicyAL();
2229 }
2230 }
2231
Felipe Lemef0823852016-06-08 13:43:08 -07002232 void writePolicyAL() {
2233 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002234
2235 FileOutputStream fos = null;
2236 try {
2237 fos = mPolicyFile.startWrite();
2238
2239 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002240 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002241 out.startDocument(null, true);
2242
2243 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002244 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002245 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002246
2247 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002248 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2249 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002250 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002251 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002252
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002253 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002254 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2255 final String subscriberId = template.getSubscriberId();
2256 if (subscriberId != null) {
2257 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002258 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002259 final String networkId = template.getNetworkId();
2260 if (networkId != null) {
2261 out.attribute(null, ATTR_NETWORK_ID, networkId);
2262 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002263 writeStringAttribute(out, ATTR_CYCLE_START,
2264 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2265 writeStringAttribute(out, ATTR_CYCLE_END,
2266 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2267 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2268 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002269 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2270 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002271 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2272 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002273 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002274 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002275 out.endTag(null, TAG_NETWORK_POLICY);
2276 }
2277
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002278 // write all known subscription plans
2279 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2280 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002281 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002282 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2283 if (ArrayUtils.isEmpty(plans)) continue;
2284
2285 for (SubscriptionPlan plan : plans) {
2286 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2287 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002288 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002289 final RecurrenceRule cycleRule = plan.getCycleRule();
2290 writeStringAttribute(out, ATTR_CYCLE_START,
2291 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2292 writeStringAttribute(out, ATTR_CYCLE_END,
2293 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2294 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2295 RecurrenceRule.convertPeriod(cycleRule.period));
2296 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2297 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2298 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2299 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2300 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2301 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2302 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2303 }
2304 }
2305
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002306 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002307 for (int i = 0; i < mUidPolicy.size(); i++) {
2308 final int uid = mUidPolicy.keyAt(i);
2309 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002310
Jeff Sharkey497e4432011-06-14 17:27:29 -07002311 // skip writing empty policies
2312 if (policy == POLICY_NONE) continue;
2313
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002314 out.startTag(null, TAG_UID_POLICY);
2315 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002316 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002318 }
2319
2320 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002321
2322 // write all whitelists
2323 out.startTag(null, TAG_WHITELIST);
2324
Felipe Lemea9505cc2016-02-26 10:28:41 -08002325 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002326 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002327 for (int i = 0; i < size; i++) {
2328 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2329 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2330 writeIntAttribute(out, ATTR_UID, uid);
2331 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2332 }
2333
Felipe Lemeb85a6372016-01-14 16:16:16 -08002334 out.endTag(null, TAG_WHITELIST);
2335
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002336 out.endDocument();
2337
2338 mPolicyFile.finishWrite(fos);
2339 } catch (IOException e) {
2340 if (fos != null) {
2341 mPolicyFile.failWrite(fos);
2342 }
2343 }
2344 }
2345
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002346 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002347 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002348 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002349
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002350 if (!UserHandle.isApp(uid)) {
2351 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002352 }
Felipe Lemef0823852016-06-08 13:43:08 -07002353 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002354 final long token = Binder.clearCallingIdentity();
2355 try {
2356 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2357 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002358 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002359 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002360 }
2361 } finally {
2362 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002363 }
2364 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002365 }
2366
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002367 @Override
2368 public void addUidPolicy(int uid, int policy) {
2369 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002370
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002371 if (!UserHandle.isApp(uid)) {
2372 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2373 }
2374
Felipe Lemef0823852016-06-08 13:43:08 -07002375 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002376 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2377 policy |= oldPolicy;
2378 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002379 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002380 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002381 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002382 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002383 }
2384
2385 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002386 public void removeUidPolicy(int uid, int policy) {
2387 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2388
2389 if (!UserHandle.isApp(uid)) {
2390 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2391 }
2392
Felipe Lemef0823852016-06-08 13:43:08 -07002393 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002394 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2395 policy = oldPolicy & ~policy;
2396 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002397 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002398 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002399 }
2400 }
2401 }
2402
Felipe Lemef0823852016-06-08 13:43:08 -07002403 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002404 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002405
Felipe Leme57e3d312016-08-23 14:42:52 -07002406 final boolean notifyApp;
2407 if (!isUidValidForWhitelistRules(uid)) {
2408 notifyApp = false;
2409 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002410 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2411 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2412 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2413 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002414 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2415 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002416 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2417 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2418 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2419 if (LOGD)
2420 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2421 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2422 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002423 notifyApp = wasBlocked != isBlocked;
2424 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002425 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2426 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002427 if (persist) {
2428 synchronized (mNetworkPoliciesSecondLock) {
2429 writePolicyAL();
2430 }
2431 }
Felipe Leme923845f2016-03-02 13:42:48 -08002432 }
2433
Felipe Lemef0823852016-06-08 13:43:08 -07002434 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002435 if (policy == POLICY_NONE) {
2436 mUidPolicy.delete(uid);
2437 } else {
2438 mUidPolicy.put(uid, policy);
2439 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002440
2441 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002442 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002443 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002444 synchronized (mNetworkPoliciesSecondLock) {
2445 writePolicyAL();
2446 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002447 }
2448 }
2449
2450 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002451 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002452 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2453
Felipe Lemef0823852016-06-08 13:43:08 -07002454 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002455 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002456 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002457 }
2458
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002459 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002460 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002461 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2462
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002463 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002464 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002465 for (int i = 0; i < mUidPolicy.size(); i++) {
2466 final int uid = mUidPolicy.keyAt(i);
2467 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002468 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2469 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002470 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002471 }
2472 }
2473 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002474 return uids;
2475 }
2476
2477 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002478 * Removes any persistable state associated with given {@link UserHandle}, persisting
2479 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002480 */
Felipe Lemef0823852016-06-08 13:43:08 -07002481 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002482
Sudheer Shanka352dc572017-09-22 17:09:38 -07002483 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002484 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002485
Felipe Lemea110eec2016-04-29 09:58:06 -07002486 // Remove entries from revoked default restricted background UID whitelist
2487 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2488 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2489 if (UserHandle.getUserId(uid) == userId) {
2490 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002491 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002492 }
2493 }
2494
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002495 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002496 int[] uids = new int[0];
2497 for (int i = 0; i < mUidPolicy.size(); i++) {
2498 final int uid = mUidPolicy.keyAt(i);
2499 if (UserHandle.getUserId(uid) == userId) {
2500 uids = appendInt(uids, uid);
2501 }
2502 }
2503
2504 if (uids.length > 0) {
2505 for (int uid : uids) {
2506 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002507 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002508 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002509 }
Felipe Lemef0823852016-06-08 13:43:08 -07002510 synchronized (mNetworkPoliciesSecondLock) {
2511 updateRulesForGlobalChangeAL(true);
2512 if (writePolicy && changed) {
2513 writePolicyAL();
2514 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002515 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002516 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002517 }
2518
2519 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002520 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002521 // TODO: create permission for observing network policy
2522 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002523 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002524 }
2525
2526 @Override
2527 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002528 // TODO: create permission for observing network policy
2529 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002530 mListeners.unregister(listener);
2531 }
2532
Jeff Sharkey1b861272011-05-22 00:34:52 -07002533 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002534 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002535 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2536
Felipe Leme6a05eee2016-02-19 14:43:51 -08002537 final long token = Binder.clearCallingIdentity();
2538 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002539 synchronized (mUidRulesFirstLock) {
2540 synchronized (mNetworkPoliciesSecondLock) {
2541 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002542 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002543 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002544 }
2545 } finally {
2546 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002547 }
2548 }
2549
Hugo Benichi446c9c92017-04-10 09:41:10 +09002550 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002551 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002552 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2553 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002554 }
2555
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002556 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002557 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002558 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002559 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002560 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2561 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2562 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002563 } catch (SecurityException e) {
2564 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002565
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002566 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2567 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2568 return new NetworkPolicy[0];
2569 }
Svet Ganov16a16892015-04-16 10:32:04 -07002570 }
2571
Felipe Lemef0823852016-06-08 13:43:08 -07002572 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002573 final int size = mNetworkPolicy.size();
2574 final NetworkPolicy[] policies = new NetworkPolicy[size];
2575 for (int i = 0; i < size; i++) {
2576 policies[i] = mNetworkPolicy.valueAt(i);
2577 }
2578 return policies;
2579 }
2580 }
2581
Felipe Lemef0823852016-06-08 13:43:08 -07002582 private void normalizePoliciesNL() {
2583 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002584 }
2585
Felipe Lemef0823852016-06-08 13:43:08 -07002586 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002587 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002588 final String[] merged = tele.getMergedSubscriberIds();
2589
2590 mNetworkPolicy.clear();
2591 for (NetworkPolicy policy : policies) {
2592 // When two normalized templates conflict, prefer the most
2593 // restrictive policy
2594 policy.template = NetworkTemplate.normalize(policy.template, merged);
2595 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2596 if (existing == null || existing.compareTo(policy) > 0) {
2597 if (existing != null) {
2598 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2599 }
2600 mNetworkPolicy.put(policy.template, policy);
2601 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002602 }
2603 }
2604
2605 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002606 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002607 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002608
2609 final long token = Binder.clearCallingIdentity();
2610 try {
2611 performSnooze(template, TYPE_LIMIT);
2612 } finally {
2613 Binder.restoreCallingIdentity(token);
2614 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002615 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002616
Dianne Hackborn497175b2014-07-01 12:56:08 -07002617 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002618 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002619 synchronized (mUidRulesFirstLock) {
2620 synchronized (mNetworkPoliciesSecondLock) {
2621 // find and snooze local policy that matches
2622 final NetworkPolicy policy = mNetworkPolicy.get(template);
2623 if (policy == null) {
2624 throw new IllegalArgumentException("unable to find policy for " + template);
2625 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002626
Felipe Lemef0823852016-06-08 13:43:08 -07002627 switch (type) {
2628 case TYPE_WARNING:
2629 policy.lastWarningSnooze = currentTime;
2630 break;
2631 case TYPE_LIMIT:
2632 policy.lastLimitSnooze = currentTime;
2633 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002634 case TYPE_RAPID:
2635 policy.lastRapidSnooze = currentTime;
2636 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002637 default:
2638 throw new IllegalArgumentException("unexpected type");
2639 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002640
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002641 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002642 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002643 }
2644 }
2645
2646 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002647 public void onTetheringChanged(String iface, boolean tethering) {
2648 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002649 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002650 if (mRestrictBackground && tethering) {
2651 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2652 setRestrictBackground(false);
2653 }
2654 }
2655 }
2656
2657 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002658 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002659 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002660 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002661 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2662 final long token = Binder.clearCallingIdentity();
2663 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002664 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002665 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002666 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002667 } finally {
2668 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002669 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002670 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002671 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002672 }
2673 }
2674
Felipe Lemef0823852016-06-08 13:43:08 -07002675 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002676 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002677 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002678 if (restrictBackground == mRestrictBackground) {
2679 // Ideally, UI should never allow this scenario...
2680 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002681 return;
2682 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002683 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2684 final boolean oldRestrictBackground = mRestrictBackground;
2685 mRestrictBackground = restrictBackground;
2686 // Must whitelist foreground apps before turning data saver mode on.
2687 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2688 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2689 updateRulesForRestrictBackgroundUL();
2690 try {
2691 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2692 Slog.e(TAG,
2693 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2694 mRestrictBackground = oldRestrictBackground;
2695 // TODO: if it knew the foreground apps (see TODO above), it could call
2696 // updateRulesForRestrictBackgroundUL() again to restore state.
2697 return;
2698 }
2699 } catch (RemoteException e) {
2700 // ignored; service lives in system_server
2701 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002702
Sudheer Shanka543339f2017-07-28 15:18:07 -07002703 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002704 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002705
2706 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2707 mRestrictBackgroundChangedInBsm = true;
2708 }
2709 synchronized (mNetworkPoliciesSecondLock) {
2710 updateNotificationsNL();
2711 writePolicyAL();
2712 }
2713 } finally {
2714 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002715 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002716 }
2717
2718 private void sendRestrictBackgroundChangedMsg() {
2719 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2720 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2721 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002722 }
2723
Felipe Lemeb85a6372016-01-14 16:16:16 -08002724 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002725 public int getRestrictBackgroundByCaller() {
2726 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2727 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002728
Felipe Lemef0823852016-06-08 13:43:08 -07002729 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002730 // Must clear identity because getUidPolicy() is restricted to system.
2731 final long token = Binder.clearCallingIdentity();
2732 final int policy;
2733 try {
2734 policy = getUidPolicy(uid);
2735 } finally {
2736 Binder.restoreCallingIdentity(token);
2737 }
2738 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2739 // App is blacklisted.
2740 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2741 }
Felipe Leme1b103232016-01-22 09:44:57 -08002742 if (!mRestrictBackground) {
2743 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2744 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002745 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002746 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2747 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2748 }
2749 }
2750
2751 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002752 public boolean getRestrictBackground() {
2753 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2754
Felipe Lemef0823852016-06-08 13:43:08 -07002755 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002756 return mRestrictBackground;
2757 }
2758 }
2759
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002760 @Override
2761 public void setDeviceIdleMode(boolean enabled) {
2762 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002763 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2764 try {
2765 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002766 if (mDeviceIdleMode == enabled) {
2767 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002768 }
Felipe Lemeea014392016-09-06 13:59:54 -07002769 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002770 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002771 if (mSystemReady) {
2772 // Device idle change means we need to rebuild rules for all
2773 // known apps, so do a global refresh.
2774 updateRulesForRestrictPowerUL();
2775 }
2776 }
2777 if (enabled) {
2778 EventLogTags.writeDeviceIdleOnPhase("net");
2779 } else {
2780 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002781 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002782 } finally {
2783 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002784 }
2785 }
2786
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002787 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002788 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2789 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002790 final long token = Binder.clearCallingIdentity();
2791 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002792 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2793 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2794 for (WifiConfiguration config : configs) {
2795 if (Objects.equals(resolveNetworkId(config), networkId)) {
2796 config.meteredOverride = meteredOverride;
2797 wm.updateNetwork(config);
2798 }
2799 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002800 } finally {
2801 Binder.restoreCallingIdentity(token);
2802 }
2803 }
2804
Jeff Sharkey46645002011-07-27 21:11:21 -07002805 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002806 @Deprecated
2807 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2808 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2809 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2810 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002811 }
2812
Jeff Sharkey53313d72017-07-13 16:47:32 -06002813 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2814 // Verify they're not lying about package name
2815 mAppOps.checkPackage(callingUid, callingPackage);
2816
Jeff Sharkey53313d72017-07-13 16:47:32 -06002817 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002818 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002819 final long token = Binder.clearCallingIdentity();
2820 try {
2821 si = mContext.getSystemService(SubscriptionManager.class)
2822 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002823 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002824 } finally {
2825 Binder.restoreCallingIdentity(token);
2826 }
2827
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002828 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002829 if (si != null) {
2830 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2831 return;
2832 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002833 }
2834
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002835 // Second check: has the CarrierService delegated access?
2836 if (config != null) {
2837 final String overridePackage = config
2838 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2839 if (!TextUtils.isEmpty(overridePackage)
2840 && Objects.equals(overridePackage, callingPackage)) {
2841 return;
2842 }
2843 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002844
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002845 // Third check: is caller the fallback/default CarrierService?
2846 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2847 if (!TextUtils.isEmpty(defaultPackage)
2848 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002849 return;
2850 }
2851
Jeff Sharkey003d3e62018-03-30 14:35:04 -06002852 // Fourth check: is caller a testing app?
2853 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
2854 if (!TextUtils.isEmpty(testPackage)
2855 && Objects.equals(testPackage, callingPackage)) {
2856 return;
2857 }
2858
2859 // Fifth check: is caller a legacy testing app?
2860 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
2861 if (!TextUtils.isEmpty(legacyTestPackage)
2862 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002863 return;
2864 }
2865
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002866 // Final check: does the caller hold a permission?
2867 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002868 }
2869
2870 @Override
2871 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2872 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2873
Jeff Sharkey53313d72017-07-13 16:47:32 -06002874 final String fake = SystemProperties.get("fw.fake_plan");
2875 if (!TextUtils.isEmpty(fake)) {
2876 final List<SubscriptionPlan> plans = new ArrayList<>();
2877 if ("month_hard".equals(fake)) {
2878 plans.add(SubscriptionPlan.Builder
2879 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2880 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002881 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2882 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2883 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2884 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2885 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002886 plans.add(SubscriptionPlan.Builder
2887 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2888 .setTitle("G-Mobile Happy")
2889 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2890 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2891 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2892 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2893 .build());
2894 plans.add(SubscriptionPlan.Builder
2895 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2896 .setTitle("G-Mobile, Charged after limit")
2897 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2898 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2899 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2900 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2901 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002902 } else if ("month_soft".equals(fake)) {
2903 plans.add(SubscriptionPlan.Builder
2904 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2905 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2906 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2907 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002908 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2909 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2910 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2911 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2912 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002913 plans.add(SubscriptionPlan.Builder
2914 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2915 .setTitle("G-Mobile, Throttled after limit")
2916 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2917 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2918 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2919 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2920 .build());
2921 plans.add(SubscriptionPlan.Builder
2922 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2923 .setTitle("G-Mobile, No data connection after limit")
2924 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2925 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2926 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2927 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2928 .build());
2929
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07002930 } else if ("month_over".equals(fake)) {
2931 plans.add(SubscriptionPlan.Builder
2932 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2933 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2934 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2935 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2936 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
2937 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2938 .build());
2939 plans.add(SubscriptionPlan.Builder
2940 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2941 .setTitle("G-Mobile, Throttled after limit")
2942 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2943 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2944 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2945 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2946 .build());
2947 plans.add(SubscriptionPlan.Builder
2948 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2949 .setTitle("G-Mobile, No data connection after limit")
2950 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2951 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2952 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2953 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2954 .build());
2955
Jeff Sharkey53313d72017-07-13 16:47:32 -06002956 } else if ("month_none".equals(fake)) {
2957 plans.add(SubscriptionPlan.Builder
2958 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2959 .setTitle("G-Mobile")
2960 .build());
2961 } else if ("prepaid".equals(fake)) {
2962 plans.add(SubscriptionPlan.Builder
2963 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2964 ZonedDateTime.now().plusDays(10))
2965 .setTitle("G-Mobile")
2966 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2967 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2968 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2969 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2970 .build());
2971 } else if ("prepaid_crazy".equals(fake)) {
2972 plans.add(SubscriptionPlan.Builder
2973 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2974 ZonedDateTime.now().plusDays(10))
2975 .setTitle("G-Mobile Anytime")
2976 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2977 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2978 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2979 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2980 .build());
2981 plans.add(SubscriptionPlan.Builder
2982 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2983 ZonedDateTime.now().plusDays(20))
2984 .setTitle("G-Mobile Nickel Nights")
2985 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002986 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2987 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002988 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2989 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2990 .build());
2991 plans.add(SubscriptionPlan.Builder
2992 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2993 ZonedDateTime.now().plusDays(20))
2994 .setTitle("G-Mobile Bonus 3G")
2995 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002996 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002997 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2998 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2999 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3000 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003001 } else if ("unlimited".equals(fake)) {
3002 plans.add(SubscriptionPlan.Builder
3003 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3004 ZonedDateTime.now().plusDays(10))
3005 .setTitle("G-Mobile Awesome")
3006 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3007 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3008 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3009 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3010 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003011 }
3012 return plans.toArray(new SubscriptionPlan[plans.size()]);
3013 }
3014
Jeff Sharkey4635f102017-09-01 11:27:13 -06003015 synchronized (mNetworkPoliciesSecondLock) {
3016 // Only give out plan details to the package that defined them,
3017 // so that we don't risk leaking plans between apps. We always
3018 // let in core system components (like the Settings app).
3019 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3020 if (Objects.equals(ownerPackage, callingPackage)
3021 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3022 return mSubscriptionPlans.get(subId);
3023 } else {
3024 Log.w(TAG, "Not returning plans because caller " + callingPackage
3025 + " doesn't match owner " + ownerPackage);
3026 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003027 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003028 }
3029 }
3030
3031 @Override
3032 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3033 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3034
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003035 for (SubscriptionPlan plan : plans) {
3036 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003037 }
3038
3039 final long token = Binder.clearCallingIdentity();
3040 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003041 synchronized (mUidRulesFirstLock) {
3042 synchronized (mNetworkPoliciesSecondLock) {
3043 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003044 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003045
3046 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
3047 .getSubscriberId(subId);
3048 ensureActiveMobilePolicyAL(subId, subscriberId);
3049 maybeUpdateMobilePolicyCycleAL(subId);
3050 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003051 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003052 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003053
3054 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3055 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3056 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3057 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003058 } finally {
3059 Binder.restoreCallingIdentity(token);
3060 }
3061 }
3062
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003063 /**
3064 * Only visible for testing purposes. This doesn't give any access to
3065 * existing plans; it simply lets the debug package define new plans.
3066 */
3067 void setSubscriptionPlansOwner(int subId, String packageName) {
3068 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3069 }
3070
Jeff Sharkey53313d72017-07-13 16:47:32 -06003071 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003072 public String getSubscriptionPlansOwner(int subId) {
3073 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3074 throw new SecurityException();
3075 }
3076
3077 synchronized (mNetworkPoliciesSecondLock) {
3078 return mSubscriptionPlansOwner.get(subId);
3079 }
3080 }
3081
3082 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003083 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3084 long timeoutMillis, String callingPackage) {
3085 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3086
3087 // We can only override when carrier told us about plans
3088 synchronized (mNetworkPoliciesSecondLock) {
3089 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
3090 throw new IllegalStateException(
3091 "Must provide SubscriptionPlan information before overriding");
3092 }
3093 }
3094
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003095 // Only allow overrides when feature is enabled. However, we always
3096 // allow disabling of overrides for safety reasons.
3097 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3098 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3099 if (overrideEnabled || overrideValue == 0) {
3100 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3101 overrideMask, overrideValue, subId));
3102 if (timeoutMillis > 0) {
3103 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3104 overrideMask, 0, subId), timeoutMillis);
3105 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003106 }
3107 }
3108
3109 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003110 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003111 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003112
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003113 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3114
Dianne Hackborn497175b2014-07-01 12:56:08 -07003115 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003116 for (String arg : args) {
3117 argSet.add(arg);
3118 }
3119
Felipe Lemef0823852016-06-08 13:43:08 -07003120 synchronized (mUidRulesFirstLock) {
3121 synchronized (mNetworkPoliciesSecondLock) {
3122 if (argSet.contains("--unsnooze")) {
3123 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3124 mNetworkPolicy.valueAt(i).clearSnooze();
3125 }
3126
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003127 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003128
3129 fout.println("Cleared snooze timestamps");
3130 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003131 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003132
Felipe Lemef0823852016-06-08 13:43:08 -07003133 fout.print("System ready: "); fout.println(mSystemReady);
3134 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3135 fout.print("Restrict power: "); fout.println(mRestrictPower);
3136 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003137 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3138
3139 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003140 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003141 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003142 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3143 fout.println(mNetworkPolicy.valueAt(i).toString());
3144 }
3145 fout.decreaseIndent();
3146
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003147 fout.println();
3148 fout.println("Subscription plans:");
3149 fout.increaseIndent();
3150 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3151 final int subId = mSubscriptionPlans.keyAt(i);
3152 fout.println("Subscriber ID " + subId + ":");
3153 fout.increaseIndent();
3154 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3155 if (!ArrayUtils.isEmpty(plans)) {
3156 for (SubscriptionPlan plan : plans) {
3157 fout.println(plan);
3158 }
3159 }
3160 fout.decreaseIndent();
3161 }
3162 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003163
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003164 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003165 fout.println("Policy for UIDs:");
3166 fout.increaseIndent();
3167 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003168 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003169 final int uid = mUidPolicy.keyAt(i);
3170 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003171 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003172 fout.print(uid);
3173 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003174 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003175 fout.println();
3176 }
3177 fout.decreaseIndent();
3178
3179 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3180 if (size > 0) {
3181 fout.println("Power save whitelist (except idle) app ids:");
3182 fout.increaseIndent();
3183 for (int i = 0; i < size; i++) {
3184 fout.print("UID=");
3185 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3186 fout.print(": ");
3187 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3188 fout.println();
3189 }
3190 fout.decreaseIndent();
3191 }
3192
3193 size = mPowerSaveWhitelistAppIds.size();
3194 if (size > 0) {
3195 fout.println("Power save whitelist app ids:");
3196 fout.increaseIndent();
3197 for (int i = 0; i < size; i++) {
3198 fout.print("UID=");
3199 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3200 fout.print(": ");
3201 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3202 fout.println();
3203 }
3204 fout.decreaseIndent();
3205 }
3206
Felipe Lemef0823852016-06-08 13:43:08 -07003207 size = mDefaultRestrictBackgroundWhitelistUids.size();
3208 if (size > 0) {
3209 fout.println("Default restrict background whitelist uids:");
3210 fout.increaseIndent();
3211 for (int i = 0; i < size; i++) {
3212 fout.print("UID=");
3213 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3214 fout.println();
3215 }
3216 fout.decreaseIndent();
3217 }
3218
3219 size = mRestrictBackgroundWhitelistRevokedUids.size();
3220 if (size > 0) {
3221 fout.println("Default restrict background whitelist uids revoked by users:");
3222 fout.increaseIndent();
3223 for (int i = 0; i < size; i++) {
3224 fout.print("UID=");
3225 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3226 fout.println();
3227 }
3228 fout.decreaseIndent();
3229 }
3230
3231 final SparseBooleanArray knownUids = new SparseBooleanArray();
3232 collectKeys(mUidState, knownUids);
3233 collectKeys(mUidRules, knownUids);
3234
3235 fout.println("Status for all known UIDs:");
3236 fout.increaseIndent();
3237 size = knownUids.size();
3238 for (int i = 0; i < size; i++) {
3239 final int uid = knownUids.keyAt(i);
3240 fout.print("UID=");
3241 fout.print(uid);
3242
3243 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3244 fout.print(" state=");
3245 fout.print(state);
3246 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3247 fout.print(" (fg)");
3248 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003249 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003250 ? " (fg svc)" : " (bg)");
3251 }
3252
3253 final int uidRules = mUidRules.get(uid, RULE_NONE);
3254 fout.print(" rules=");
3255 fout.print(uidRulesToString(uidRules));
3256 fout.println();
3257 }
3258 fout.decreaseIndent();
3259
3260 fout.println("Status for just UIDs with rules:");
3261 fout.increaseIndent();
3262 size = mUidRules.size();
3263 for (int i = 0; i < size; i++) {
3264 final int uid = mUidRules.keyAt(i);
3265 fout.print("UID=");
3266 fout.print(uid);
3267 final int uidRules = mUidRules.get(uid, RULE_NONE);
3268 fout.print(" rules=");
3269 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003270 fout.println();
3271 }
3272 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003273
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003274 fout.println("Admin restricted uids for metered data:");
3275 fout.increaseIndent();
3276 size = mMeteredRestrictedUids.size();
3277 for (int i = 0; i < size; ++i) {
3278 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3279 fout.println(mMeteredRestrictedUids.valueAt(i));
3280 }
3281 fout.decreaseIndent();
3282
Sudheer Shanka352dc572017-09-22 17:09:38 -07003283 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003284 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003285 }
3286 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003287
3288 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003289 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003290 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003291 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003292 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003293 }
3294
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003295 @VisibleForTesting
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003296 public boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003297 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003298 return isUidStateForeground(
3299 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003300 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003301 }
3302
Felipe Lemef0823852016-06-08 13:43:08 -07003303 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003304 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003305 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003306 }
3307
Felipe Lemef0823852016-06-08 13:43:08 -07003308 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003309 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3310 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3311 }
3312
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003313 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003314 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003315 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003316 }
3317
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003318 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003319 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003320 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3321 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003322 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003323 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003324 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3325 try {
3326 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3327 if (oldUidState != uidState) {
3328 // state changed, push updated rules
3329 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003330 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3331 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3332 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003333 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003334 if (mDeviceIdleMode) {
3335 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003336 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003337 if (mRestrictPower) {
3338 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003339 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003340 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003341 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003342 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003343 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003344 } finally {
3345 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003346 }
3347 }
3348
Felipe Lemef0823852016-06-08 13:43:08 -07003349 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003350 final int index = mUidState.indexOfKey(uid);
3351 if (index >= 0) {
3352 final int oldUidState = mUidState.valueAt(index);
3353 mUidState.removeAt(index);
3354 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003355 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003356 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003357 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003358 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003359 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003360 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003361 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003362 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003363 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003364 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003365 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003366 }
3367 }
3368
Felipe Lemef28983d2016-03-25 12:18:23 -07003369 // adjust stats accounting based on foreground status
3370 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003371 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3372 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3373 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3374 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003375 try {
3376 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003377 } finally {
3378 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003379 }
3380 }
3381
Sudheer Shankac9d94072017-02-22 22:13:55 +00003382 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3383 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003384 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003385 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003386 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003387 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003388 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003389 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003390 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003391 }
3392
Felipe Lemef0823852016-06-08 13:43:08 -07003393 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003394 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3395 try {
3396 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3397 mUidFirewallPowerSaveRules);
3398 } finally {
3399 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3400 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003401 }
3402
Felipe Lemef0823852016-06-08 13:43:08 -07003403 void updateRuleForRestrictPowerUL(int uid) {
3404 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003405 }
3406
Felipe Lemef0823852016-06-08 13:43:08 -07003407 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003408 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3409 try {
3410 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3411 mUidFirewallDozableRules);
3412 } finally {
3413 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3414 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003415 }
3416
Felipe Lemef0823852016-06-08 13:43:08 -07003417 void updateRuleForDeviceIdleUL(int uid) {
3418 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003419 }
3420
Felipe Lemef28983d2016-03-25 12:18:23 -07003421 // NOTE: since both fw_dozable and fw_powersave uses the same map
3422 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003423 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003424 SparseIntArray rules) {
3425 if (enabled) {
3426 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003427 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003428 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003429 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003430 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003431 for (int ui = users.size() - 1; ui >= 0; ui--) {
3432 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003433 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3434 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3435 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3436 updateRulesForWhitelistedAppIds(uidRules,
3437 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003438 }
3439 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003440 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003441 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003442 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3443 }
3444 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003445 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003446 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003447 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003448 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003449 }
3450
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003451 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3452 final SparseBooleanArray whitelistedAppIds, int userId) {
3453 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3454 if (whitelistedAppIds.valueAt(i)) {
3455 final int appId = whitelistedAppIds.keyAt(i);
3456 final int uid = UserHandle.getUid(userId, appId);
3457 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3458 }
3459 }
3460 }
3461
3462 /**
3463 * @param deviceIdleMode if true then we don't consider
3464 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3465 * whitelisted.
3466 */
3467 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003468 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003469 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3470 || mPowerSaveWhitelistAppIds.get(appId);
3471 if (!deviceIdleMode) {
3472 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3473 }
3474 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003475 }
3476
Felipe Lemef28983d2016-03-25 12:18:23 -07003477 // NOTE: since both fw_dozable and fw_powersave uses the same map
3478 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003479 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003480 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003481 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3482 chain == FIREWALL_CHAIN_DOZABLE);
3483 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003484 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003485 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003486 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003487 }
3488 }
3489 }
3490
Felipe Lemef0823852016-06-08 13:43:08 -07003491 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003492 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3493 try {
3494 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3495 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003496
Felipe Leme873a83a2016-09-07 11:34:10 -07003497 // Fully update the app idle firewall chain.
3498 final List<UserInfo> users = mUserManager.getUsers();
3499 for (int ui = users.size() - 1; ui >= 0; ui--) {
3500 UserInfo user = users.get(ui);
3501 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3502 for (int uid : idleUids) {
3503 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3504 // quick check: if this uid doesn't have INTERNET permission, it
3505 // doesn't have network access anyway, so it is a waste to mess
3506 // with it here.
3507 if (hasInternetPermissions(uid)) {
3508 uidRules.put(uid, FIREWALL_RULE_DENY);
3509 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003510 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003511 }
3512 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003513
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003514 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003515 } finally {
3516 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3517 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003518 }
3519
Felipe Lemef0823852016-06-08 13:43:08 -07003520 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003521 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003522
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003523 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3524 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3525 }
3526 try {
3527 int appId = UserHandle.getAppId(uid);
3528 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3529 && !isUidForegroundOnRestrictPowerUL(uid)) {
3530 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3531 } else {
3532 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3533 }
3534 } finally {
3535 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003536 }
3537 }
3538
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003539 /**
3540 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3541 * changed.
3542 */
Felipe Lemef0823852016-06-08 13:43:08 -07003543 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003544 boolean paroled = mUsageStats.isAppIdleParoleOn();
3545 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003546 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003547
3548 int ruleCount = mUidFirewallStandbyRules.size();
3549 for (int i = 0; i < ruleCount; i++) {
3550 int uid = mUidFirewallStandbyRules.keyAt(i);
3551 int oldRules = mUidRules.get(uid);
3552 if (enableChain) {
3553 // Chain wasn't enabled before and the other power-related
3554 // chains are whitelists, so we can clear the
3555 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3556 // the effective rules result in blocking network access.
3557 oldRules &= MASK_METERED_NETWORKS;
3558 } else {
3559 // Skip if it had no restrictions to begin with
3560 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3561 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003562 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3563 if (newUidRules == RULE_NONE) {
3564 mUidRules.delete(uid);
3565 } else {
3566 mUidRules.put(uid, newUidRules);
3567 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003568 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003569 }
3570
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003571 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003572 * Update rules that might be changed by {@link #mRestrictBackground},
3573 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003574 */
Felipe Lemef0823852016-06-08 13:43:08 -07003575 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003576 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3577 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3578 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3579 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003580 try {
Felipe Leme09700462016-09-08 09:33:48 -07003581 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003582 updateRulesForRestrictPowerUL();
3583 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003584
Felipe Leme873a83a2016-09-07 11:34:10 -07003585 // If the set of restricted networks may have changed, re-evaluate those.
3586 if (restrictedNetworksChanged) {
3587 normalizePoliciesNL();
3588 updateNetworkRulesNL();
3589 }
3590 } finally {
3591 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003592 }
3593 }
3594
Felipe Leme09700462016-09-08 09:33:48 -07003595 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003596 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003597 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3598 try {
3599 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003600 updateRulesForPowerSaveUL();
3601 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3602 } finally {
3603 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3604 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003605 }
3606
Felipe Lemef0823852016-06-08 13:43:08 -07003607 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003608 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3609 try {
3610 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3611 } finally {
3612 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3613 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003614 }
3615
3616 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3617 private static final int TYPE_RESTRICT_POWER = 2;
3618 @Retention(RetentionPolicy.SOURCE)
3619 @IntDef(flag = false, value = {
3620 TYPE_RESTRICT_BACKGROUND,
3621 TYPE_RESTRICT_POWER,
3622 })
3623 public @interface RestrictType {
3624 }
3625
3626 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003627 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003628 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3629 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3630 }
3631 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003632 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003633
3634 final PackageManager pm = mContext.getPackageManager();
3635 final List<UserInfo> users;
3636 final List<ApplicationInfo> apps;
3637
3638 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3639 try {
3640 users = mUserManager.getUsers();
3641 } finally {
3642 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3643 }
3644 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3645 try {
3646 apps = pm.getInstalledApplications(
3647 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3648 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3649 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3650 } finally {
3651 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3652 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003653
Felipe Leme873a83a2016-09-07 11:34:10 -07003654 final int usersSize = users.size();
3655 final int appsSize = apps.size();
3656 for (int i = 0; i < usersSize; i++) {
3657 final UserInfo user = users.get(i);
3658 for (int j = 0; j < appsSize; j++) {
3659 final ApplicationInfo app = apps.get(j);
3660 final int uid = UserHandle.getUid(user.id, app.uid);
3661 switch (type) {
3662 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003663 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003664 break;
3665 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003666 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003667 break;
3668 default:
3669 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3670 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003671 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003672 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003673 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003674 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003675 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003676 }
3677
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003678 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003679 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003680 final int numUsers = users.size();
3681 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003682 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003683 int uid = UserHandle.getUid(user.id, appId);
3684 // Update external firewall rules.
3685 updateRuleForAppIdleUL(uid);
3686 updateRuleForDeviceIdleUL(uid);
3687 updateRuleForRestrictPowerUL(uid);
3688 // Update internal rules.
3689 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003690 }
3691 }
3692
Felipe Leme70c57c22016-03-29 10:45:13 -07003693 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3694 // methods below could be merged into a isUidValidForRules() method.
3695 private boolean isUidValidForBlacklistRules(int uid) {
3696 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003697 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003698 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003699 return true;
3700 }
3701
3702 return false;
3703 }
3704
Felipe Leme70c57c22016-03-29 10:45:13 -07003705 private boolean isUidValidForWhitelistRules(int uid) {
3706 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3707 }
3708
Amith Yamasani15e472352015-04-24 19:06:07 -07003709 private boolean isUidIdle(int uid) {
3710 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3711 final int userId = UserHandle.getUserId(uid);
3712
songjinshi0655edd2016-05-18 19:55:32 +08003713 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003714 for (String packageName : packages) {
3715 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3716 return false;
3717 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003718 }
3719 }
3720 return true;
3721 }
3722
3723 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003724 * Checks if an uid has INTERNET permissions.
3725 * <p>
3726 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003727 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003728 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003729 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003730 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003731 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003732 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003733 }
3734 } catch (RemoteException e) {
3735 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003736 return true;
3737 }
3738
3739 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003740 * Clears all state - internal and external - associated with an UID.
3741 */
3742 private void onUidDeletedUL(int uid) {
3743 // First cleanup in-memory state synchronously...
3744 mUidRules.delete(uid);
3745 mUidPolicy.delete(uid);
3746 mUidFirewallStandbyRules.delete(uid);
3747 mUidFirewallDozableRules.delete(uid);
3748 mUidFirewallPowerSaveRules.delete(uid);
3749 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3750 mPowerSaveWhitelistAppIds.delete(uid);
3751 mPowerSaveTempWhitelistAppIds.delete(uid);
3752
3753 // ...then update iptables asynchronously.
3754 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3755 }
3756
3757 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003758 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003759 *
Felipe Leme781ba142016-05-09 16:24:48 -07003760 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003761 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003762 * <li>Doze mode
3763 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003764 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003765 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003766 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003767 *
3768 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003769 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003770 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003771 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003772 updateRuleForDeviceIdleUL(uid);
3773 updateRuleForAppIdleUL(uid);
3774 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003775
3776 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003777 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003778
3779 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003780 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003781 }
3782
Felipe Leme70c57c22016-03-29 10:45:13 -07003783 /**
3784 * Applies network rules to bandwidth controllers based on process state and user-defined
3785 * restrictions (blacklist / whitelist).
3786 *
3787 * <p>
3788 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3789 * networks:
3790 * <ul>
3791 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3792 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3793 * also blacklisted.
3794 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3795 * no UIDs other those whitelisted will have access.
3796 * <ul>
3797 *
3798 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3799 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3800 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3801 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003802 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003803 * {@link INetworkManagementService}, but this method should also be called in events (like
3804 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3805 * following rules should also be applied:
3806 *
3807 * <ul>
3808 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3809 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3810 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3811 * {@code bw_penalty_box}.
3812 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3813 * </ul>
3814 *
3815 * <p>For optimization, the rules are only applied on user apps that have internet access
3816 * permission, since there is no need to change the {@code iptables} rule if the app does not
3817 * have permission to use the internet.
3818 *
3819 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003820 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003821 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003822 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003823 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3824 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3825 "updateRulesForDataUsageRestrictionsUL: " + uid);
3826 }
3827 try {
3828 updateRulesForDataUsageRestrictionsULInner(uid);
3829 } finally {
3830 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3831 }
3832 }
3833
3834 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003835 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003836 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003837 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003838 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003839
Dianne Hackborn497175b2014-07-01 12:56:08 -07003840 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003841 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003842 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003843 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003844
Felipe Leme781ba142016-05-09 16:24:48 -07003845 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003846 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003847 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3848 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003849
Felipe Leme70c57c22016-03-29 10:45:13 -07003850 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003851 if (isRestrictedByAdmin) {
3852 newRule = RULE_REJECT_METERED;
3853 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003854 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3855 newRule = RULE_TEMPORARY_ALLOW_METERED;
3856 } else if (isWhitelisted) {
3857 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003858 }
3859 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003860 if (isBlacklisted) {
3861 newRule = RULE_REJECT_METERED;
3862 } else if (mRestrictBackground && isWhitelisted) {
3863 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003864 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003865 }
Felipe Leme781ba142016-05-09 16:24:48 -07003866 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003867
Felipe Lemef28983d2016-03-25 12:18:23 -07003868 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003869 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003870 + ": isForeground=" +isForeground
3871 + ", isBlacklisted=" + isBlacklisted
3872 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003873 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003874 + ", oldRule=" + uidRulesToString(oldRule)
3875 + ", newRule=" + uidRulesToString(newRule)
3876 + ", newUidRules=" + uidRulesToString(newUidRules)
3877 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003878 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003879
Felipe Leme46c4fc32016-05-04 09:21:43 -07003880 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003881 mUidRules.delete(uid);
3882 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003883 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003884 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003885
Felipe Leme70c57c22016-03-29 10:45:13 -07003886 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003887 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003888 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003889 // Temporarily whitelist foreground app, removing from blacklist if necessary
3890 // (since bw_penalty_box prevails over bw_happy_box).
3891
3892 setMeteredNetworkWhitelist(uid, true);
3893 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3894 // but ideally it should be just:
3895 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003896 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003897 setMeteredNetworkBlacklist(uid, false);
3898 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003899 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003900 // Remove temporary whitelist from app that is not on foreground anymore.
3901
3902 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3903 // but ideally they should be just:
3904 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3905 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003906 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003907 setMeteredNetworkWhitelist(uid, false);
3908 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003909 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003910 setMeteredNetworkBlacklist(uid, true);
3911 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003912 } else if (hasRule(newRule, RULE_REJECT_METERED)
3913 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003914 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003915 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003916 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003917 // Since blacklist prevails over whitelist, we need to handle the special case
3918 // where app is whitelisted and blacklisted at the same time (although such
3919 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003920 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003921 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003922 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3923 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003924 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003925 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003926 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003927 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003928 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3929 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003930 + ", whitelisted=" + isWhitelisted
3931 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003932 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003933 + ", newRule=" + uidRulesToString(newUidRules)
3934 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003935 }
Felipe Leme781ba142016-05-09 16:24:48 -07003936
Sudheer Shankac9d94072017-02-22 22:13:55 +00003937 // Dispatch changed rule to existing listeners.
3938 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003939 }
3940 }
3941
3942 /**
3943 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3944 * listeners in case of change.
3945 * <p>
3946 * There are 3 power-related rules that affects whether an app has background access on
3947 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3948 * restriction, it's added to the equivalent firewall chain:
3949 * <ul>
3950 * <li>App is idle: {@code fw_standby} firewall chain.
3951 * <li>Device is idle: {@code fw_dozable} firewall chain.
3952 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3953 * </ul>
3954 * <p>
3955 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3956 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3957 * <p>
3958 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3959 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003960 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003961 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3962
Sudheer Shankac9d94072017-02-22 22:13:55 +00003963 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003964
Sudheer Shankac9d94072017-02-22 22:13:55 +00003965 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003966 mUidRules.delete(uid);
3967 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003968 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003969 }
3970 }
3971
3972 /**
3973 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3974 *
3975 * @param uid the uid of the app to update rules for
3976 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3977 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3978 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003979 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003980 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003981 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003982 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3983 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3984 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3985 + (paroled ? "P" : "-"));
3986 }
3987 try {
3988 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3989 } finally {
3990 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3991 }
3992 }
3993
3994 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003995 if (!isUidValidForBlacklistRules(uid)) {
3996 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003997 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003998 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003999
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004000 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004001 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004002 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004003
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07004004 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004005 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4006 int newRule = RULE_NONE;
4007
4008 // First step: define the new rule based on user restrictions and foreground state.
4009
4010 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4011 // by considering the foreground and non-foreground states.
4012 if (isForeground) {
4013 if (restrictMode) {
4014 newRule = RULE_ALLOW_ALL;
4015 }
4016 } else if (restrictMode) {
4017 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4018 }
4019
4020 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4021
4022 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004023 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004024 + ", isIdle: " + isIdle
4025 + ", mRestrictPower: " + mRestrictPower
4026 + ", mDeviceIdleMode: " + mDeviceIdleMode
4027 + ", isForeground=" + isForeground
4028 + ", isWhitelisted=" + isWhitelisted
4029 + ", oldRule=" + uidRulesToString(oldRule)
4030 + ", newRule=" + uidRulesToString(newRule)
4031 + ", newUidRules=" + uidRulesToString(newUidRules)
4032 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4033 }
4034
Felipe Leme781ba142016-05-09 16:24:48 -07004035 // Second step: notify listeners if state changed.
4036 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004037 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004038 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004039 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004040 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4041 } else {
4042 // All scenarios should have been covered above
4043 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4044 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004045 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004046 + ", newRule=" + uidRulesToString(newUidRules)
4047 + ", oldRule=" + uidRulesToString(oldUidRules));
4048 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004049 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004050 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004051
Sudheer Shankac9d94072017-02-22 22:13:55 +00004052 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004053 }
4054
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004055 private class AppIdleStateChangeListener
4056 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4057
4058 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004059 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4060 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004061 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004062 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4063 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004064 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004065 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004066 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004067 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004068 }
4069 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004070 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004071 }
4072
4073 @Override
4074 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004075 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004076 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004077 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004078 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004079 }
4080 }
4081
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004082 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4083 if (listener != null) {
4084 try {
4085 listener.onUidRulesChanged(uid, uidRules);
4086 } catch (RemoteException ignored) {
4087 }
4088 }
4089 }
4090
4091 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4092 String[] meteredIfaces) {
4093 if (listener != null) {
4094 try {
4095 listener.onMeteredIfacesChanged(meteredIfaces);
4096 } catch (RemoteException ignored) {
4097 }
4098 }
4099 }
4100
4101 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4102 boolean restrictBackground) {
4103 if (listener != null) {
4104 try {
4105 listener.onRestrictBackgroundChanged(restrictBackground);
4106 } catch (RemoteException ignored) {
4107 }
4108 }
4109 }
4110
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004111 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4112 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004113 if (listener != null) {
4114 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004115 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004116 } catch (RemoteException ignored) {
4117 }
4118 }
4119 }
4120
Jeff Sharkey9252b342018-01-19 07:58:35 +09004121 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4122 int overrideMask, int overrideValue) {
4123 if (listener != null) {
4124 try {
4125 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4126 } catch (RemoteException ignored) {
4127 }
4128 }
4129 }
4130
Makoto Onuki8e777332017-03-28 11:25:47 -07004131 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004132 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004133 public boolean handleMessage(Message msg) {
4134 switch (msg.what) {
4135 case MSG_RULES_CHANGED: {
4136 final int uid = msg.arg1;
4137 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004138 final int length = mListeners.beginBroadcast();
4139 for (int i = 0; i < length; i++) {
4140 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4141 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004142 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004143 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004144 return true;
4145 }
4146 case MSG_METERED_IFACES_CHANGED: {
4147 final String[] meteredIfaces = (String[]) msg.obj;
4148 final int length = mListeners.beginBroadcast();
4149 for (int i = 0; i < length; i++) {
4150 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004151 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004152 }
4153 mListeners.finishBroadcast();
4154 return true;
4155 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004156 case MSG_LIMIT_REACHED: {
4157 final String iface = (String) msg.obj;
4158
Felipe Lemef0823852016-06-08 13:43:08 -07004159 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004160 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004161 // force stats update to make sure we have
4162 // numbers that caused alert to trigger.
4163 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004164
Felipe Lemef0823852016-06-08 13:43:08 -07004165 updateNetworkEnabledNL();
4166 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004167 }
4168 }
4169 return true;
4170 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004171 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4172 final boolean restrictBackground = msg.arg1 != 0;
4173 final int length = mListeners.beginBroadcast();
4174 for (int i = 0; i < length; i++) {
4175 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004176 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004177 }
4178 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004179 final Intent intent =
4180 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4181 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4182 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4183 return true;
4184 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004185 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004186 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004187 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004188 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004189 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004190 final int length = mListeners.beginBroadcast();
4191 for (int i = 0; i < length; i++) {
4192 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004193 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004194 }
4195 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004196 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4197 if (notifyApp.booleanValue()) {
4198 broadcastRestrictBackgroundChanged(uid, notifyApp);
4199 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004200 return true;
4201 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004202 case MSG_ADVISE_PERSIST_THRESHOLD: {
4203 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004204 // make sure stats are recorded frequently enough; we aim
4205 // for 2MB threshold for 2GB/month rules.
4206 final long persistThreshold = lowestRule / 1000;
4207 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004208 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004209 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004210 case MSG_UPDATE_INTERFACE_QUOTA: {
4211 removeInterfaceQuota((String) msg.obj);
4212 // int params need to be stitched back into a long
4213 setInterfaceQuota((String) msg.obj,
4214 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4215 return true;
4216 }
4217 case MSG_REMOVE_INTERFACE_QUOTA: {
4218 removeInterfaceQuota((String) msg.obj);
4219 return true;
4220 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004221 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4222 resetUidFirewallRules(msg.arg1);
4223 return true;
4224 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004225 case MSG_SUBSCRIPTION_OVERRIDE: {
4226 final int overrideMask = msg.arg1;
4227 final int overrideValue = msg.arg2;
4228 final int subId = (int) msg.obj;
4229 final int length = mListeners.beginBroadcast();
4230 for (int i = 0; i < length; i++) {
4231 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4232 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4233 }
4234 mListeners.finishBroadcast();
4235 return true;
4236 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004237 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4238 final int userId = msg.arg1;
4239 final Set<String> packageNames = (Set<String>) msg.obj;
4240 setMeteredRestrictedPackagesInternal(packageNames, userId);
4241 return true;
4242 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004243 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4244 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4245 final boolean enabled = msg.arg1 != 0;
4246 setNetworkTemplateEnabledInner(template, enabled);
4247 return true;
4248 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004249 default: {
4250 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004251 }
4252 }
4253 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004254 };
4255
4256 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4257 @Override
4258 public boolean handleMessage(Message msg) {
4259 switch (msg.what) {
4260 case UID_MSG_STATE_CHANGED: {
4261 final int uid = msg.arg1;
4262 final int procState = msg.arg2;
4263 final long procStateSeq = (Long) msg.obj;
4264
4265 handleUidChanged(uid, procState, procStateSeq);
4266 return true;
4267 }
4268 case UID_MSG_GONE: {
4269 final int uid = msg.arg1;
4270 handleUidGone(uid);
4271 return true;
4272 }
4273 default: {
4274 return false;
4275 }
4276 }
4277 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004278
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004279 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004280
Makoto Onuki8e777332017-03-28 11:25:47 -07004281 void handleUidChanged(int uid, int procState, long procStateSeq) {
4282 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4283 try {
4284 synchronized (mUidRulesFirstLock) {
4285 // We received a uid state change callback, add it to the history so that it
4286 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004287 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004288 // Now update the network policy rules as per the updated uid state.
4289 updateUidStateUL(uid, procState);
4290 // Updating the network rules is done, so notify AMS about this.
4291 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4292 }
4293 } finally {
4294 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4295 }
4296 }
4297
4298 void handleUidGone(int uid) {
4299 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4300 try {
4301 synchronized (mUidRulesFirstLock) {
4302 removeUidStateUL(uid);
4303 }
4304 } finally {
4305 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4306 }
4307 }
4308
Felipe Leme57e3d312016-08-23 14:42:52 -07004309 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4310 final PackageManager pm = mContext.getPackageManager();
4311 final String[] packages = pm.getPackagesForUid(uid);
4312 if (packages != null) {
4313 final int userId = UserHandle.getUserId(uid);
4314 for (String packageName : packages) {
4315 final Intent intent =
4316 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4317 intent.setPackage(packageName);
4318 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4319 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4320 }
4321 }
4322 }
4323
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004324 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4325 // long quotaBytes split up into two ints to fit in message
4326 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4327 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4328 }
4329
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004330 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004331 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004332 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004333 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004334 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004335 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004336 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004337 }
4338 }
4339
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004340 private void removeInterfaceQuotaAsync(String iface) {
4341 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4342 }
4343
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004344 private void removeInterfaceQuota(String iface) {
4345 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004346 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004347 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004348 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004349 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004350 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004351 }
4352 }
4353
Felipe Leme70c57c22016-03-29 10:45:13 -07004354 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4355 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004356 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004357 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004358 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004359 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4360 } catch (RemoteException e) {
4361 // ignored; service lives in system_server
4362 }
4363 }
4364
4365 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4366 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4367 try {
4368 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4369 } catch (IllegalStateException e) {
4370 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004371 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004372 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004373 }
4374 }
4375
Felipe Lemebc853dd2016-09-08 13:26:55 -07004376 private static final int CHAIN_TOGGLE_NONE = 0;
4377 private static final int CHAIN_TOGGLE_ENABLE = 1;
4378 private static final int CHAIN_TOGGLE_DISABLE = 2;
4379 @Retention(RetentionPolicy.SOURCE)
4380 @IntDef(flag = false, value = {
4381 CHAIN_TOGGLE_NONE,
4382 CHAIN_TOGGLE_ENABLE,
4383 CHAIN_TOGGLE_DISABLE
4384 })
4385 public @interface ChainToggleType {
4386 }
4387
4388 /**
4389 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004390 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004391 *
4392 * @param chain firewall chain.
4393 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4394 * @param toggle whether the chain should be enabled, disabled, or not changed.
4395 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004396 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004397 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004398 if (uidRules != null) {
4399 setUidFirewallRulesUL(chain, uidRules);
4400 }
4401 if (toggle != CHAIN_TOGGLE_NONE) {
4402 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4403 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004404 }
4405
Amith Yamasani15e472352015-04-24 19:06:07 -07004406 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004407 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4408 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4409 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004410 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004411 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004412 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004413 int size = uidRules.size();
4414 int[] uids = new int[size];
4415 int[] rules = new int[size];
4416 for(int index = size - 1; index >= 0; --index) {
4417 uids[index] = uidRules.keyAt(index);
4418 rules[index] = uidRules.valueAt(index);
4419 }
4420 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004421 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004422 } catch (IllegalStateException e) {
4423 Log.wtf(TAG, "problem setting firewall uid rules", e);
4424 } catch (RemoteException e) {
4425 // ignored; service lives in system_server
4426 }
4427 }
4428
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004429 /**
4430 * Add or remove a uid to the firewall blacklist for all network ifaces.
4431 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004432 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004433 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4434 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4435 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004436 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004437 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004438 if (chain == FIREWALL_CHAIN_DOZABLE) {
4439 mUidFirewallDozableRules.put(uid, rule);
4440 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4441 mUidFirewallStandbyRules.put(uid, rule);
4442 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4443 mUidFirewallPowerSaveRules.put(uid, rule);
4444 }
4445
4446 try {
4447 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004448 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004449 } catch (IllegalStateException e) {
4450 Log.wtf(TAG, "problem setting firewall uid rules", e);
4451 } catch (RemoteException e) {
4452 // ignored; service lives in system_server
4453 }
4454 } finally {
4455 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004456 }
4457 }
4458
4459 /**
4460 * Add or remove a uid to the firewall blacklist for all network ifaces.
4461 */
Felipe Lemef0823852016-06-08 13:43:08 -07004462 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004463 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4464 mFirewallChainStates.get(chain) == enable) {
4465 // All is the same, nothing to do.
4466 return;
4467 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004468 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004469 try {
4470 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004471 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004472 } catch (IllegalStateException e) {
4473 Log.wtf(TAG, "problem enable firewall chain", e);
4474 } catch (RemoteException e) {
4475 // ignored; service lives in system_server
4476 }
4477 }
4478
Felipe Leme03e95e22016-09-09 09:25:31 -07004479 /**
4480 * Resets all firewall rules associated with an UID.
4481 */
4482 private void resetUidFirewallRules(int uid) {
4483 try {
4484 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4485 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4486 mNetworkManager
4487 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4488 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4489 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4490 } catch (IllegalStateException e) {
4491 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4492 } catch (RemoteException e) {
4493 // ignored; service lives in system_server
4494 }
4495 }
4496
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004497 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004498 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004499 return getNetworkTotalBytes(template, start, end);
4500 }
4501
4502 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004503 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004504 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004505 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004506 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004507 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004508 }
4509 }
4510
4511 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4512 try {
4513 return mNetworkStats.getNetworkUidBytes(template, start, end);
4514 } catch (RuntimeException e) {
4515 Slog.w(TAG, "Failed to read network stats: " + e);
4516 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004517 }
4518 }
4519
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004520 private boolean isBandwidthControlEnabled() {
4521 final long token = Binder.clearCallingIdentity();
4522 try {
4523 return mNetworkManager.isBandwidthControlEnabled();
4524 } catch (RemoteException e) {
4525 // ignored; service lives in system_server
4526 return false;
4527 } finally {
4528 Binder.restoreCallingIdentity(token);
4529 }
4530 }
4531
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004532 private static Intent buildAllowBackgroundDataIntent() {
4533 return new Intent(ACTION_ALLOW_BACKGROUND);
4534 }
4535
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004536 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4537 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004538 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4539 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4540 return intent;
4541 }
4542
4543 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4544 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4545 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004546 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4547 return intent;
4548 }
4549
Wei Liu546cb772016-07-21 16:19:01 -07004550 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004551 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004552 intent.setComponent(ComponentName.unflattenFromString(
4553 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004554 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4555 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4556 return intent;
4557 }
4558
Wei Liu546cb772016-07-21 16:19:01 -07004559 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004560 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004561 intent.setComponent(ComponentName.unflattenFromString(
4562 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004563 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4564 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4565 return intent;
4566 }
4567
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004568 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004569 public void addIdleHandler(IdleHandler handler) {
4570 mHandler.getLooper().getQueue().addIdleHandler(handler);
4571 }
4572
jackqdyulei29c82ab2017-03-10 14:09:16 -08004573 @VisibleForTesting
4574 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4575 mRestrictBackgroundPowerState = result;
4576
4577 boolean restrictBackground = result.batterySaverEnabled;
4578 boolean shouldInvokeRestrictBackground;
4579 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4580 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4581
4582 if (result.globalBatterySaverEnabled) {
4583 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4584 // turn it on.
4585 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4586 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4587 localRestrictBgChangedInBsm = false;
4588 } else {
4589 // Try to restore the restrictBackground if it doesn't change in bsm
4590 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4591 restrictBackground = mRestrictBackgroundBeforeBsm;
4592 }
4593
4594 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004595 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004596 }
4597
4598 // Change it at last so setRestrictBackground() won't affect this variable
4599 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4600 }
4601
Jeff Sharkey1b861272011-05-22 00:34:52 -07004602 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4603 final int size = source.size();
4604 for (int i = 0; i < size; i++) {
4605 target.put(source.keyAt(i), true);
4606 }
4607 }
4608
Stuart Scottf1fb3972015-04-02 18:00:02 -07004609 @Override
4610 public void factoryReset(String subscriber) {
4611 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4612
Stuart Scotte3e314d2015-04-20 14:07:45 -07004613 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4614 return;
4615 }
4616
Stuart Scottf1fb3972015-04-02 18:00:02 -07004617 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004618 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004619 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4620 for (NetworkPolicy policy : policies) {
4621 if (policy.template.equals(template)) {
4622 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4623 policy.inferred = false;
4624 policy.clearSnooze();
4625 }
4626 }
4627 setNetworkPolicies(policies);
4628
4629 // Turn restrict background data off
4630 setRestrictBackground(false);
4631
Stuart Scotte3e314d2015-04-20 14:07:45 -07004632 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4633 // Remove app's "restrict background data" flag
4634 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4635 setUidPolicy(uid, POLICY_NONE);
4636 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004637 }
4638 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004639
Sudheer Shankab8f23162017-08-04 13:30:10 -07004640 @Override
4641 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4642 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4643 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4644 }
4645
4646 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4647 final int uidRules;
4648 final boolean isBackgroundRestricted;
4649 synchronized (mUidRulesFirstLock) {
4650 uidRules = mUidRules.get(uid, RULE_NONE);
4651 isBackgroundRestricted = mRestrictBackground;
4652 }
4653 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004654 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004655 return true;
4656 }
4657 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004658 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004659 return false;
4660 }
4661 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004662 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004663 return true;
4664 }
4665 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004666 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004667 return false;
4668 }
4669 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004670 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004671 return false;
4672 }
4673 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004674 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004675 return true;
4676 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004677 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004678 return false;
4679 }
4680
Felipe Lemed17fda42016-04-29 11:12:45 -07004681 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4682
4683 @Override
4684 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004685 synchronized (mUidRulesFirstLock) {
4686 boolean changed = removeUserStateUL(userId, false);
4687 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004688 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004689 synchronized (mNetworkPoliciesSecondLock) {
4690 writePolicyAL();
4691 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004692 }
4693 }
4694 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004695
4696 /**
4697 * @return true if the given uid is restricted from doing networking on metered networks.
4698 */
4699 @Override
4700 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4701 final int uidRules;
4702 final boolean isBackgroundRestricted;
4703 synchronized (mUidRulesFirstLock) {
4704 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4705 isBackgroundRestricted = mRestrictBackground;
4706 }
4707 return isBackgroundRestricted
4708 && !hasRule(uidRules, RULE_ALLOW_METERED)
4709 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4710 }
4711
4712 /**
4713 * @return true if networking is blocked on the given interface for the given uid according
4714 * to current networking policies.
4715 */
4716 @Override
4717 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004718 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004719 synchronized (mNetworkPoliciesSecondLock) {
4720 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004721 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004722 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004723 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004724
4725 @Override
4726 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4727 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004728 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004729 if (added) {
4730 mPowerSaveTempWhitelistAppIds.put(appId, true);
4731 } else {
4732 mPowerSaveTempWhitelistAppIds.delete(appId);
4733 }
4734 updateRulesForTempWhitelistChangeUL(appId);
4735 }
4736 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004737
4738 @Override
4739 public SubscriptionPlan getSubscriptionPlan(Network network) {
4740 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004741 final int subId = getSubIdLocked(network);
4742 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004743 }
4744 }
4745
4746 @Override
4747 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004748 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09004749 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004750 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09004751 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004752 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06004753 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
4754 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4755 }
4756
4757 if (quotaType == QUOTA_TYPE_JOBS) {
4758 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4759 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
4760 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
4761 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
4762 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
4763 } else {
4764 return OPPORTUNISTIC_QUOTA_UNKNOWN;
4765 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004766 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004767
4768 @Override
4769 public void onAdminDataAvailable() {
4770 mAdminDataAvailableLatch.countDown();
4771 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004772
4773 @Override
4774 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4775 setMeteredRestrictedPackagesInternal(packageNames, userId);
4776 }
4777
4778 @Override
4779 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4780 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4781 userId, 0, packageNames).sendToTarget();
4782 }
4783 }
4784
4785 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4786 synchronized (mUidRulesFirstLock) {
4787 final Set<Integer> newRestrictedUids = new ArraySet<>();
4788 for (String packageName : packageNames) {
4789 final int uid = getUidForPackage(packageName, userId);
4790 if (uid >= 0) {
4791 newRestrictedUids.add(uid);
4792 }
4793 }
4794 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4795 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4796 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4797 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4798 }
4799 }
4800
4801 private int getUidForPackage(String packageName, int userId) {
4802 try {
4803 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4804 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4805 } catch (NameNotFoundException e) {
4806 return -1;
4807 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004808 }
4809
4810 private int parseSubId(NetworkState state) {
4811 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4812 int subId = INVALID_SUBSCRIPTION_ID;
4813 if (state != null && state.networkCapabilities != null
4814 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4815 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4816 if (spec instanceof StringNetworkSpecifier) {
4817 try {
4818 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4819 } catch (NumberFormatException e) {
4820 }
4821 }
4822 }
4823 return subId;
4824 }
4825
Andreas Gampea36dc622018-02-05 17:19:22 -08004826 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004827 private int getSubIdLocked(Network network) {
4828 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004829 }
4830
Andreas Gampea36dc622018-02-05 17:19:22 -08004831 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004832 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4833 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4834 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4835 }
4836
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004837 /**
4838 * This will only ever be called once - during device boot.
4839 */
4840 private void waitForAdminData() {
4841 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4842 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4843 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4844 }
4845 }
4846
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004847 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4848 Set<Integer> newRestrictedUids) {
4849 if (oldRestrictedUids == null) {
4850 for (int uid : newRestrictedUids) {
4851 updateRulesForDataUsageRestrictionsUL(uid);
4852 }
4853 return;
4854 }
4855 for (int uid : oldRestrictedUids) {
4856 if (!newRestrictedUids.contains(uid)) {
4857 updateRulesForDataUsageRestrictionsUL(uid);
4858 }
4859 }
4860 for (int uid : newRestrictedUids) {
4861 if (!oldRestrictedUids.contains(uid)) {
4862 updateRulesForDataUsageRestrictionsUL(uid);
4863 }
4864 }
4865 }
4866
4867 private boolean isRestrictedByAdminUL(int uid) {
4868 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4869 UserHandle.getUserId(uid));
4870 return restrictedUids != null && restrictedUids.contains(uid);
4871 }
4872
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004873 private static boolean hasRule(int uidRules, int rule) {
4874 return (uidRules & rule) != 0;
4875 }
4876
Jeff Sharkey2e471452018-01-19 18:02:47 +09004877 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4878 return (val != null) ? val : new NetworkState[0];
4879 }
4880
Chris Wren193ae6b2017-03-31 15:17:11 -04004881 private class NotificationId {
4882 private final String mTag;
4883 private final int mId;
4884
4885 NotificationId(NetworkPolicy policy, int type) {
4886 mTag = buildNotificationTag(policy, type);
4887 mId = type;
4888 }
4889
4890 @Override
4891 public boolean equals(Object o) {
4892 if (this == o) return true;
4893 if (!(o instanceof NotificationId)) return false;
4894 NotificationId that = (NotificationId) o;
4895 return Objects.equals(mTag, that.mTag);
4896 }
4897
4898 @Override
4899 public int hashCode() {
4900 return Objects.hash(mTag);
4901 }
4902
4903 /**
4904 * Build unique tag that identifies an active {@link NetworkPolicy}
4905 * notification of a specific type, like {@link #TYPE_LIMIT}.
4906 */
4907 private String buildNotificationTag(NetworkPolicy policy, int type) {
4908 return TAG + ":" + policy.template.hashCode() + ":" + type;
4909 }
4910
4911 public String getTag() {
4912 return mTag;
4913 }
4914
4915 public int getId() {
4916 return mId;
4917 }
4918 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004919}