blob: 0d6dadfb1ad875b0506259571b56dbc4b4055009 [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 Sharkey00072392018-04-12 14:26:32 -060074import static android.os.Trace.TRACE_TAG_NETWORK;
Jeff Sharkey36b414b2018-03-30 11:00:03 -060075import static android.provider.Settings.Global.NETPOLICY_OVERRIDE_ENABLED;
76import static android.provider.Settings.Global.NETPOLICY_QUOTA_ENABLED;
77import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_JOBS;
78import static android.provider.Settings.Global.NETPOLICY_QUOTA_FRAC_MULTIPATH;
79import static android.provider.Settings.Global.NETPOLICY_QUOTA_LIMITED;
80import static android.provider.Settings.Global.NETPOLICY_QUOTA_UNLIMITED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070081import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070082import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060083import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey0a5570d2018-04-10 12:38:29 -060084import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_NOTIFICATION_BOOL;
85import static android.telephony.CarrierConfigManager.KEY_DATA_RAPID_NOTIFICATION_BOOL;
86import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_NOTIFICATION_BOOL;
Jeff Sharkey9252b342018-01-19 07:58:35 +090087import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Felipe Leme03e689d2016-03-02 16:17:38 -080088
Jeff Sharkey854b2b12012-04-13 16:03:40 -070089import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070090import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070091import static com.android.internal.util.XmlUtils.readBooleanAttribute;
92import static com.android.internal.util.XmlUtils.readIntAttribute;
93import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060094import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070095import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
96import static com.android.internal.util.XmlUtils.writeIntAttribute;
97import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060098import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070099import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700100import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
101import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
junyulai05986c62018-08-07 19:50:45 +0800102import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_SYSTEM;
Sudheer Shanka352dc572017-09-22 17:09:38 -0700103import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
104import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
105import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
106import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
107import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700108import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600109
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700110import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800111import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700112import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700113
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700114import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700115import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900116import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700117import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700118import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800119import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700120import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700121import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700122import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700123import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700125import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700126import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700127import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700128import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700129import android.content.ComponentName;
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600130import android.content.ContentResolver;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700131import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700132import android.content.Intent;
133import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700134import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700135import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700136import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700137import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700138import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700139import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600141import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700142import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700143import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700144import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700145import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700146import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700147import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600148import android.net.Network;
149import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700150import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600152import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700153import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600154import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900155import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.net.NetworkState;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700157import android.net.NetworkStats;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700158import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900159import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700161import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700162import android.net.wifi.WifiManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700163import android.os.BestClock;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700164import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.os.Environment;
166import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700167import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700168import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700169import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700170import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700171import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700172import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700173import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700174import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600176import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800177import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700178import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700179import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600180import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700181import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700182import android.os.ShellCallback;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700183import android.os.SystemClock;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600184import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700185import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700186import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700187import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700188import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100189import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700190import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600191import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800192import android.telephony.SubscriptionManager;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600193import android.telephony.SubscriptionManager.OnSubscriptionsChangedListener;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600194import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700195import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400196import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700197import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700198import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700199import android.util.ArrayMap;
200import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700201import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900202import android.util.DataUnit;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600203import android.util.IntArray;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700204import android.util.Log;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700205import android.util.Pair;
Jeff Sharkey0fc6d032018-03-30 16:25:11 -0600206import android.util.Range;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600207import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700208import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600209import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210import android.util.SparseBooleanArray;
211import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900212import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700214
Jeff Sharkey497e4432011-06-14 17:27:29 -0700215import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700216import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400218import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500219import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700220import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800221import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800222import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600223import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700225import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600226import com.android.internal.util.Preconditions;
Makoto Onuki49392d32018-04-11 13:51:02 -0700227import com.android.internal.util.StatLogger;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700228import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700229import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700230import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800231import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600232
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600233import libcore.io.IoUtils;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600234import libcore.util.EmptyArray;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600235
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237import org.xmlpull.v1.XmlSerializer;
238
239import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700240import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241import java.io.FileInputStream;
242import java.io.FileNotFoundException;
243import java.io.FileOutputStream;
244import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700245import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700246import java.lang.annotation.Retention;
247import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100248import java.nio.charset.StandardCharsets;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700249import java.time.Clock;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900250import java.time.Instant;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600251import java.time.ZoneId;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700252import java.time.ZoneOffset;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600253import java.time.ZonedDateTime;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +0900254import java.time.temporal.ChronoUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700255import java.util.ArrayList;
Jeff Sharkey146bb332018-04-18 15:42:57 -0600256import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700257import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600258import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400259import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800260import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800261import java.util.concurrent.CountDownLatch;
262import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700264/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700265 * Service that maintains low-level network policy rules, using
266 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700267 * <p>
268 * Derives active rules by combining a given policy with other system status,
269 * and delivers to listeners, such as {@link ConnectivityManager}, for
270 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700271 *
272 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000273 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700274 * <ul>
275 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
276 * rules).
277 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
278 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000279 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
280 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700281 * </ul>
282 *
283 * <p>
284 * As such, methods that require synchronization have the following prefixes:
285 * <ul>
286 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
287 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000288 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
289 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700290 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700291 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700292public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700293 static final String TAG = NetworkPolicyLogger.TAG;
294 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
295 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700296
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +0900297 /**
298 * No opportunistic quota could be calculated from user data plan or data settings.
299 */
300 public static final int OPPORTUNISTIC_QUOTA_UNKNOWN = -1;
301
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700302 private static final int VERSION_INIT = 1;
303 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700304 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800305 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800306 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800307 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700308 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700309 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700310 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700311 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600312 private static final int VERSION_ADDED_CYCLE = 11;
313 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700314
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800315 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400316 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400318 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800319 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400320 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900321 @VisibleForTesting
322 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700323
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700324 private static final String TAG_POLICY_LIST = "policy-list";
325 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600326 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700328 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800329 private static final String TAG_WHITELIST = "whitelist";
330 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800331 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332
333 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700334 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
336 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700337 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600338 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
339 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
340 private static final String ATTR_CYCLE_START = "cycleStart";
341 private static final String ATTR_CYCLE_END = "cycleEnd";
342 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700343 private static final String ATTR_WARNING_BYTES = "warningBytes";
344 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700345 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800346 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
347 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800348 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700349 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700350 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700351 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700352 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600353 private static final String ATTR_SUB_ID = "subId";
354 private static final String ATTR_TITLE = "title";
355 private static final String ATTR_SUMMARY = "summary";
356 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
357 private static final String ATTR_USAGE_BYTES = "usageBytes";
358 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600359 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700360
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800361 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800362 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800363 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800364 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700365 private static final String ACTION_SNOOZE_RAPID =
366 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700367
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800368 /**
369 * Indicates the maximum wait time for admin data to be available;
370 */
371 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
372
Jeff Sharkey36b414b2018-03-30 11:00:03 -0600373 private static final long QUOTA_UNLIMITED_DEFAULT = DataUnit.MEBIBYTES.toBytes(20);
374 private static final float QUOTA_LIMITED_DEFAULT = 0.1f;
375 private static final float QUOTA_FRAC_JOBS_DEFAULT = 0.5f;
376 private static final float QUOTA_FRAC_MULTIPATH_DEFAULT = 0.5f;
377
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700378 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700379 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800380 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800381 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700382 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700383 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
384 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700385 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700386 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900387 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800388 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -0700389 private static final int MSG_SET_NETWORK_TEMPLATE_ENABLED = 18;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700390
Makoto Onuki8e777332017-03-28 11:25:47 -0700391 private static final int UID_MSG_STATE_CHANGED = 100;
392 private static final int UID_MSG_GONE = 101;
393
Jeff Sharkey003d3e62018-03-30 14:35:04 -0600394 private static final String PROP_SUB_PLAN_OWNER = "persist.sys.sub_plan_owner";
395
Jeff Sharkey75279902011-05-24 18:39:45 -0700396 private final Context mContext;
397 private final IActivityManager mActivityManager;
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700398 private NetworkStatsManagerInternal mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700399 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700400 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700401 private final Clock mClock;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700402 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700403 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404
405 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700406 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700407 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800408 @GuardedBy("mUidRulesFirstLock")
409 private PowerSaveState mRestrictBackgroundPowerState;
410
411 // Store the status of restrict background before turning on battery saver.
412 // Used to restore mRestrictBackground when battery saver is turned off.
413 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700414
Sudheer Shanka543339f2017-07-28 15:18:07 -0700415 // Denotes the status of restrict background read from disk.
416 private boolean mLoadedRestrictBackground;
417
Felipe Lemef0823852016-06-08 13:43:08 -0700418 // See main javadoc for instructions on how to use these locks.
419 final Object mUidRulesFirstLock = new Object();
420 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700421
Felipe Lemef0823852016-06-08 13:43:08 -0700422 @GuardedBy("allLocks") volatile boolean mSystemReady;
423
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
425 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
426 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800427 // Store whether user flipped restrict background in battery saver mode
428 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700429
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700430 private final boolean mSuppressDefaultPolicy;
431
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800432 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
433
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700434 private volatile boolean mNetworkManagerReady;
435
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700436 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600437 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800438 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700439
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600440 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600441 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600442 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600443 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600444 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600445 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600446
Jeff Sharkey9252b342018-01-19 07:58:35 +0900447 /** Map from subId to daily opportunistic quota. */
448 @GuardedBy("mNetworkPoliciesSecondLock")
449 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
450
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700451 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700452 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700453 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700454 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700455
Felipe Lemef0823852016-06-08 13:43:08 -0700456 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700457 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700459 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700460 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800461 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700462
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700463 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700465 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
466
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800467 // "Power save mode" is the concept used in the DeviceIdleController that includes various
468 // features including Doze and Battery Saver. It include Battery Saver, but "power save mode"
469 // and "battery saver" are not equivalent.
470
Jeff Sharkey32566012014-12-02 18:30:14 -0800471 /**
472 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700473 * in power save mode, except device idle (doze) still applies.
474 * TODO: An int array might be sufficient
475 */
Felipe Lemef0823852016-06-08 13:43:08 -0700476 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700477 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
478
479 /**
480 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800481 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700482 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800483 */
Felipe Lemef0823852016-06-08 13:43:08 -0700484 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700485 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700486
Felipe Lemef0823852016-06-08 13:43:08 -0700487 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700488 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
489
Felipe Lemeb85a6372016-01-14 16:16:16 -0800490 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -0800491 * UIDs that have been white-listed temporarily to be able to have network access despite being
492 * idle. Other power saving restrictions still apply.
493 */
494 @GuardedBy("mUidRulesFirstLock")
495 private final SparseBooleanArray mAppIdleTempWhitelistAppIds = new SparseBooleanArray();
496
497 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800498 * UIDs that have been initially white-listed by system to avoid restricted background.
499 */
Felipe Lemef0823852016-06-08 13:43:08 -0700500 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800501 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
502 new SparseBooleanArray();
503
504 /**
505 * UIDs that have been initially white-listed by system to avoid restricted background,
506 * but later revoked by user.
507 */
Felipe Lemef0823852016-06-08 13:43:08 -0700508 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800509 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
510 new SparseBooleanArray();
511
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700512 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700513 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800514 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700515 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700516 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800517 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700518
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700519 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700520 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400521 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700522
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700523 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700524 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800525 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700526
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600527 /** Map from network ID to last observed meteredness state */
528 @GuardedBy("mNetworkPoliciesSecondLock")
529 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +0900530 /** Map from network ID to last observed roaming state */
531 @GuardedBy("mNetworkPoliciesSecondLock")
532 private final SparseBooleanArray mNetworkRoaming = new SparseBooleanArray();
533
Jeff Sharkey9252b342018-01-19 07:58:35 +0900534 /** Map from netId to subId as of last update */
535 @GuardedBy("mNetworkPoliciesSecondLock")
536 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
537
Jeff Sharkey146bb332018-04-18 15:42:57 -0600538 /** Map from subId to subscriberId as of last update */
539 @GuardedBy("mNetworkPoliciesSecondLock")
540 private final SparseArray<String> mSubIdToSubscriberId = new SparseArray<>();
541 /** Set of all merged subscriberId as of last update */
542 @GuardedBy("mNetworkPoliciesSecondLock")
543 private String[] mMergedSubscriberIds = EmptyArray.STRING;
544
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800545 /**
546 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
547 * userId to restricted uids which belong to that user.
548 */
549 @GuardedBy("mUidRulesFirstLock")
550 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
551
Jeff Sharkey32566012014-12-02 18:30:14 -0800552 private final RemoteCallbackList<INetworkPolicyListener>
553 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700554
Dianne Hackborn497175b2014-07-01 12:56:08 -0700555 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700556 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -0800557 final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700558
559 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700560
Felipe Lemef0823852016-06-08 13:43:08 -0700561 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700562 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700563
Svet Ganov16a16892015-04-16 10:32:04 -0700564 private final AppOpsManager mAppOps;
565
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800566 private final IPackageManager mIPm;
567
Sudheer Shankae7361852017-03-07 11:51:46 -0800568 private ActivityManagerInternal mActivityManagerInternal;
569
Sudheer Shanka352dc572017-09-22 17:09:38 -0700570 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800571
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700572 // TODO: keep whitelist of system-critical services that should never have
573 // rules enforced, such as system, phone, and radio UIDs.
574
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700575 // TODO: migrate notifications to SystemUI
576
Makoto Onuki49392d32018-04-11 13:51:02 -0700577
578 interface Stats {
579 int UPDATE_NETWORK_ENABLED = 0;
580 int IS_UID_NETWORKING_BLOCKED = 1;
581
582 int COUNT = IS_UID_NETWORKING_BLOCKED + 1;
583 }
584
585 public final StatLogger mStatLogger = new StatLogger(new String[] {
586 "updateNetworkEnabledNL()",
587 "isUidNetworkingBlocked()",
588 });
589
Jeff Sharkey75279902011-05-24 18:39:45 -0700590 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700591 INetworkManagementService networkManagement) {
592 this(context, activityManager, networkManagement, AppGlobals.getPackageManager(),
593 getDefaultClock(), getDefaultSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700594 }
595
Jeff Sharkey9911a282018-02-14 22:29:11 -0700596 private static @NonNull File getDefaultSystemDir() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700597 return new File(Environment.getDataDirectory(), "system");
598 }
599
Jeff Sharkey9911a282018-02-14 22:29:11 -0700600 private static @NonNull Clock getDefaultClock() {
601 return new BestClock(ZoneOffset.UTC, SystemClock.currentNetworkTimeClock(),
602 Clock.systemUTC());
603 }
604
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700605 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700606 INetworkManagementService networkManagement, IPackageManager pm, Clock clock,
607 File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700608 mContext = checkNotNull(context, "missing context");
609 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700610 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700611 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700612 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey9911a282018-02-14 22:29:11 -0700613 mClock = checkNotNull(clock, "missing Clock");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700614 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700615 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700616 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700617
Amith Yamasani450a16b2013-09-18 16:28:50 -0700618 HandlerThread thread = new HandlerThread(TAG);
619 thread.start();
620 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700621
Makoto Onuki8e777332017-03-28 11:25:47 -0700622 // We create another thread for the UID events, which are more time-critical.
623 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
624 /*allowIo=*/ false);
625 mUidEventThread.start();
626 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
627
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700628 mSuppressDefaultPolicy = suppressDefaultPolicy;
629
Dianne Hackborne17b4452018-01-10 13:15:40 -0800630 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700631
632 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800633
Felipe Lemed17fda42016-04-29 11:12:45 -0700634 // Expose private service for system components to use.
635 LocalServices.addService(NetworkPolicyManagerInternal.class,
636 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700637 }
638
639 public void bindConnectivityManager(IConnectivityManager connManager) {
640 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700641 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700642
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700643 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700644 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700645 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700646 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
647 mPowerSaveWhitelistExceptIdleAppIds.clear();
648 if (whitelist != null) {
649 for (int uid : whitelist) {
650 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
651 }
652 }
653 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700654 mPowerSaveWhitelistAppIds.clear();
655 if (whitelist != null) {
656 for (int uid : whitelist) {
657 mPowerSaveWhitelistAppIds.put(uid, true);
658 }
659 }
660 } catch (RemoteException e) {
661 }
662 }
663
Felipe Lemea9505cc2016-02-26 10:28:41 -0800664 /**
665 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
666 * revoke the whitelist.
667 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700668 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800669 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700670 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700671 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800672 final List<UserInfo> users = mUserManager.getUsers();
673 final int numberUsers = users.size();
674
Felipe Lemea110eec2016-04-29 09:58:06 -0700675 boolean changed = false;
676 for (int i = 0; i < numberUsers; i++) {
677 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700678 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700679 }
680 return changed;
681 }
682
Andreas Gampeaae5aa32018-07-20 12:55:38 -0700683 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -0700684 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700685 final SystemConfig sysConfig = SystemConfig.getInstance();
686 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800687 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
688 boolean changed = false;
689 for (int i = 0; i < allowDataUsage.size(); i++) {
690 final String pkg = allowDataUsage.valueAt(i);
691 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700692 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
693 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800694 final ApplicationInfo app;
695 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700696 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800697 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700698 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
699 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800700 continue;
701 }
702 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700703 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
704 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800705 continue;
706 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700707 final int uid = UserHandle.getUid(userId, app.uid);
708 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
709 if (LOGD)
710 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
711 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800712 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700713 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700714 if (LOGD)
715 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
716 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700717 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700718 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800719 }
720 }
721 return changed;
722 }
723
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800724 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700725 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800726 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700727 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800728 // Boost thread's priority during system server init
729 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700730 if (!isBandwidthControlEnabled()) {
731 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
732 return;
733 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700734
Felipe Leme873a83a2016-09-07 11:34:10 -0700735 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Jeff Sharkeye0c29952018-02-20 17:24:55 -0700736 mNetworkStats = LocalServices.getService(NetworkStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700737
Felipe Leme873a83a2016-09-07 11:34:10 -0700738 synchronized (mUidRulesFirstLock) {
739 synchronized (mNetworkPoliciesSecondLock) {
740 updatePowerSaveWhitelistUL();
741 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
742 mPowerManagerInternal.registerLowPowerModeObserver(
743 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800744 @Override
745 public int getServiceType() {
746 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700747 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800748
749 @Override
750 public void onLowPowerModeChanged(PowerSaveState result) {
751 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800752 if (LOGD) {
753 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
754 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800755 synchronized (mUidRulesFirstLock) {
756 if (mRestrictPower != enabled) {
757 mRestrictPower = enabled;
758 updateRulesForRestrictPowerUL();
759 }
760 }
761 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800762 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800763 mRestrictPower = mPowerManagerInternal.getLowPowerState(
764 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700765
766 mSystemReady = true;
767
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800768 waitForAdminData();
769
Felipe Leme873a83a2016-09-07 11:34:10 -0700770 // read policy from disk
771 readPolicyAL();
772
jackqdyulei29c82ab2017-03-10 14:09:16 -0800773 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700774 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800775 mRestrictBackgroundPowerState = mPowerManagerInternal
776 .getLowPowerState(ServiceType.DATA_SAVER);
777 final boolean localRestrictBackground =
778 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700779 if (localRestrictBackground && !mLoadedRestrictBackground) {
780 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800781 }
782 mPowerManagerInternal.registerLowPowerModeObserver(
783 new PowerManagerInternal.LowPowerModeListener() {
784 @Override
785 public int getServiceType() {
786 return ServiceType.DATA_SAVER;
787 }
788
789 @Override
790 public void onLowPowerModeChanged(PowerSaveState result) {
791 synchronized (mUidRulesFirstLock) {
792 updateRestrictBackgroundByLowPowerModeUL(result);
793 }
794 }
795 });
796
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
798 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700799 }
Felipe Lemef0823852016-06-08 13:43:08 -0700800
Sudheer Shanka543339f2017-07-28 15:18:07 -0700801 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700802 updateRulesForGlobalChangeAL(false);
803 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700804 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800805 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700806
Sudheer Shankae7361852017-03-07 11:51:46 -0800807 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700808 try {
809 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000810 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Sudheer Shanka6a3c07e2018-09-11 15:21:22 -0700811 NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE, "android");
Felipe Leme873a83a2016-09-07 11:34:10 -0700812 mNetworkManager.registerObserver(mAlertObserver);
813 } catch (RemoteException e) {
814 // ignored; both services live in system_server
815 }
816
817 // listen for changes to power save whitelist
818 final IntentFilter whitelistFilter = new IntentFilter(
819 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
820 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
821
Felipe Leme873a83a2016-09-07 11:34:10 -0700822 // watch for network interfaces to be claimed
823 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
824 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
825
826 // listen for package changes to update policy
827 final IntentFilter packageFilter = new IntentFilter();
828 packageFilter.addAction(ACTION_PACKAGE_ADDED);
829 packageFilter.addDataScheme("package");
830 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
831
832 // listen for UID changes to update policy
833 mContext.registerReceiver(
834 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
835
836 // listen for user changes to update policy
837 final IntentFilter userFilter = new IntentFilter();
838 userFilter.addAction(ACTION_USER_ADDED);
839 userFilter.addAction(ACTION_USER_REMOVED);
840 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
841
842 // listen for stats update events
843 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
844 mContext.registerReceiver(
845 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
846
847 // listen for restrict background changes from notifications
848 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
849 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
850
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700851 // Listen for snooze from notifications
852 mContext.registerReceiver(mSnoozeReceiver,
853 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
854 mContext.registerReceiver(mSnoozeReceiver,
855 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700856
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600857 // listen for configured wifi networks to be loaded
858 final IntentFilter wifiFilter =
859 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
860 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700861
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700862 // listen for carrier config changes to update data cycle information
863 final IntentFilter carrierConfigFilter = new IntentFilter(
864 ACTION_CARRIER_CONFIG_CHANGED);
865 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
866
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600867 // listen for meteredness changes
868 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
869 new NetworkRequest.Builder().build(), mNetworkCallback);
870
Felipe Leme873a83a2016-09-07 11:34:10 -0700871 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Jeff Sharkey146bb332018-04-18 15:42:57 -0600872
873 // Listen for subscriber changes
874 mContext.getSystemService(SubscriptionManager.class).addOnSubscriptionsChangedListener(
875 new OnSubscriptionsChangedListener(mHandler.getLooper()) {
876 @Override
877 public void onSubscriptionsChanged() {
878 updateNetworksInternal();
879 }
880 });
881
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800882 // tell systemReady() that the service has been initialized
883 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700884 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800885 // Restore the default priority after init is done
886 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700887 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700888 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700889 }
890
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800891 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
Sudheer Shanka1536fb62018-07-05 11:52:36 -0700892 mNetworkManagerReady = true;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800893 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
894 mHandler.post(() -> initService(initCompleteSignal));
895 return initCompleteSignal;
896 }
897
898 public void systemReady(CountDownLatch initCompleteSignal) {
899 // wait for initService to complete
900 try {
901 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
902 throw new IllegalStateException("Service " + TAG +" init timeout");
903 }
904 } catch (InterruptedException e) {
905 Thread.currentThread().interrupt();
906 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
907 }
908 }
909
Sudheer Shankac9d94072017-02-22 22:13:55 +0000910 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700911 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700912 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
913 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700914 }
915
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700916 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700917 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700918 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700919
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700920 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700921 }
922
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700923 @Override public void onUidIdle(int uid, boolean disabled) {
924 }
925
926 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700927 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700928 };
929
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700931 @Override
932 public void onReceive(Context context, Intent intent) {
933 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700934 synchronized (mUidRulesFirstLock) {
935 updatePowerSaveWhitelistUL();
936 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700937 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700938 }
939 }
940 };
941
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700942 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700943 @Override
944 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700945 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700946
947 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700948 final int uid = intent.getIntExtra(EXTRA_UID, -1);
949 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700950
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700951 if (ACTION_PACKAGE_ADDED.equals(action)) {
952 // update rules for UID, since it might be subject to
953 // global background data policy
954 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700955 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700956 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700957 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700958 }
959 }
960 };
961
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700963 @Override
964 public void onReceive(Context context, Intent intent) {
965 // on background handler thread, and UID_REMOVED is protected
966
967 final int uid = intent.getIntExtra(EXTRA_UID, -1);
968 if (uid == -1) return;
969
970 // remove any policy and update rules to clean up
971 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700972 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700973 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700974 synchronized (mNetworkPoliciesSecondLock) {
975 writePolicyAL();
976 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700977 }
978 }
979 };
980
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700981 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700982 @Override
983 public void onReceive(Context context, Intent intent) {
984 // on background handler thread, and USER_ADDED and USER_REMOVED
985 // broadcasts are protected
986
987 final String action = intent.getAction();
988 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
989 if (userId == -1) return;
990
Amith Yamasani15e472352015-04-24 19:06:07 -0700991 switch (action) {
992 case ACTION_USER_REMOVED:
993 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700994 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800995 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700996 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700997 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800998 // Removing outside removeUserStateUL since that can also be called when
999 // user resets app preferences.
1000 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001001 if (action == ACTION_USER_ADDED) {
1002 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -07001003 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -07001004 }
1005 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -07001006 synchronized (mNetworkPoliciesSecondLock) {
1007 updateRulesForGlobalChangeAL(true);
1008 }
Amith Yamasani15e472352015-04-24 19:06:07 -07001009 }
1010 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001011 }
1012 }
1013 };
1014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001015 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 * Receiver that watches for {@link INetworkStatsService} updates, which we
1017 * use to check against {@link NetworkPolicy#warningBytes}.
1018 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001019 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 @Override
1021 public void onReceive(Context context, Intent intent) {
1022 // on background handler thread, and verified
1023 // READ_NETWORK_USAGE_HISTORY permission above.
1024
Felipe Lemef0823852016-06-08 13:43:08 -07001025 synchronized (mNetworkPoliciesSecondLock) {
1026 updateNetworkEnabledNL();
1027 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 }
1029 }
1030 };
1031
1032 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001033 * Receiver that watches for {@link Notification} control of
1034 * {@link #mRestrictBackground}.
1035 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001036 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001037 @Override
1038 public void onReceive(Context context, Intent intent) {
1039 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1040 // permission above.
1041
1042 setRestrictBackground(false);
1043 }
1044 };
1045
1046 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001047 * Receiver that watches for {@link Notification} control of
1048 * {@link NetworkPolicy#lastWarningSnooze}.
1049 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001050 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 @Override
1052 public void onReceive(Context context, Intent intent) {
1053 // on background handler thread, and verified MANAGE_NETWORK_POLICY
1054 // permission above.
1055
1056 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001057 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
1058 performSnooze(template, TYPE_WARNING);
1059 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
1060 performSnooze(template, TYPE_RAPID);
1061 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001062 }
1063 };
1064
1065 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001066 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001067 * we can perform upgrade logic. After initial upgrade logic, it updates
1068 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001069 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001070 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001071 @Override
1072 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001073 synchronized (mUidRulesFirstLock) {
1074 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001075 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001076 }
1077 }
1078 // Only need to perform upgrade logic once
1079 mContext.unregisterReceiver(this);
1080 }
1081 };
1082
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001083 private static boolean updateCapabilityChange(SparseBooleanArray lastValues, boolean newValue,
1084 Network network) {
1085 final boolean lastValue = lastValues.get(network.netId, false);
1086 final boolean changed = (lastValue != newValue) || lastValues.indexOfKey(network.netId) < 0;
1087 if (changed) {
1088 lastValues.put(network.netId, newValue);
1089 }
1090 return changed;
1091 }
1092
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001093 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1094 @Override
1095 public void onCapabilitiesChanged(Network network,
1096 NetworkCapabilities networkCapabilities) {
1097 if (network == null || networkCapabilities == null) return;
1098
1099 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001100 final boolean newMetered = !networkCapabilities
1101 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001102 final boolean meteredChanged = updateCapabilityChange(
1103 mNetworkMetered, newMetered, network);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001104
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001105 final boolean newRoaming = !networkCapabilities
1106 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING);
1107 final boolean roamingChanged = updateCapabilityChange(
1108 mNetworkRoaming, newRoaming, network);
1109
1110 if (meteredChanged || roamingChanged) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001111 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001112 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001113 }
1114 }
1115 }
1116 };
1117
1118 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 * Observer that watches for {@link INetworkManagementService} alerts.
1120 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001121 final private INetworkManagementEventObserver mAlertObserver
1122 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 @Override
1124 public void limitReached(String limitName, String iface) {
1125 // only someone like NMS should be calling us
1126 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1127
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001128 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1129 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001130 }
1131 }
1132 };
1133
1134 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1136 * to show visible notifications as needed.
1137 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001138 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001139 void updateNotificationsNL() {
1140 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001141 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNotificationsNL");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001143 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001144 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146
1147 // TODO: when switching to kernel notifications, compute next future
1148 // cycle boundary to recompute notifications.
1149
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001150 // examine stats for each active policy
Jeff Sharkey9911a282018-02-14 22:29:11 -07001151 final long now = mClock.millis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1153 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001154 final int subId = findRelevantSubIdNL(policy.template);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001155
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 // ignore policies that aren't relevant to user
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001157 if (subId == INVALID_SUBSCRIPTION_ID) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001158 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159
Jeff Sharkey53313d72017-07-13 16:47:32 -06001160 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1161 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001162 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1163 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1164 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001165
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001166 // Carrier might want to manage notifications themselves
1167 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1168 final boolean notifyWarning = getBooleanDefeatingNullable(config,
1169 KEY_DATA_WARNING_NOTIFICATION_BOOL, true);
1170 final boolean notifyLimit = getBooleanDefeatingNullable(config,
1171 KEY_DATA_LIMIT_NOTIFICATION_BOOL, true);
1172 final boolean notifyRapid = getBooleanDefeatingNullable(config,
1173 KEY_DATA_RAPID_NOTIFICATION_BOOL, true);
1174
1175 // Notify when data usage is over warning
1176 if (notifyWarning) {
1177 if (policy.isOverWarning(totalBytes) && !policy.isOverLimit(totalBytes)) {
1178 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1179 if (!snoozedThisCycle) {
1180 enqueueNotification(policy, TYPE_WARNING, totalBytes, null);
1181 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001182 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001183 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001184
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001185 // Notify when data usage is over limit
1186 if (notifyLimit) {
1187 if (policy.isOverLimit(totalBytes)) {
1188 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1189 if (snoozedThisCycle) {
1190 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes, null);
1191 } else {
1192 enqueueNotification(policy, TYPE_LIMIT, totalBytes, null);
1193 notifyOverLimitNL(policy.template);
1194 }
1195 } else {
1196 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001197 }
1198 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001199
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001200 // Warn if average usage over last 4 days is on track to blow pretty
1201 // far past the plan limits.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001202 if (notifyRapid && policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001203 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001204 final long recentStart = now - recentDuration;
1205 final long recentEnd = now;
1206 final long recentBytes = getTotalBytes(policy.template, recentStart, recentEnd);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001207
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001208 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001209 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001210 final long alertBytes = (policy.limitBytes * 3) / 2;
1211
1212 if (LOGD) {
1213 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1214 + projectedBytes + " alert " + alertBytes);
1215 }
1216
1217 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1218 - DateUtils.DAY_IN_MILLIS;
1219 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001220 enqueueNotification(policy, TYPE_RAPID, 0,
1221 findRapidBlame(policy.template, recentStart, recentEnd));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001222 }
1223 }
1224 }
1225
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001226 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001227 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001228 final NotificationId notificationId = beforeNotifs.valueAt(i);
1229 if (!mActiveNotifs.contains(notificationId)) {
1230 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001231 }
1232 }
Jeff Sharkey00072392018-04-12 14:26:32 -06001233
1234 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001235 }
1236
1237 /**
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001238 * Attempt to find a specific app to blame for rapid data usage during the
1239 * given time period.
1240 */
1241 private @Nullable ApplicationInfo findRapidBlame(NetworkTemplate template,
1242 long start, long end) {
1243 long totalBytes = 0;
1244 long maxBytes = 0;
1245 int maxUid = 0;
1246
1247 final NetworkStats stats = getNetworkUidBytes(template, start, end);
1248 NetworkStats.Entry entry = null;
1249 for (int i = 0; i < stats.size(); i++) {
1250 entry = stats.getValues(i, entry);
1251 final long bytes = entry.rxBytes + entry.txBytes;
1252 totalBytes += bytes;
1253 if (bytes > maxBytes) {
1254 maxBytes = bytes;
1255 maxUid = entry.uid;
1256 }
1257 }
1258
1259 // Only point blame if the majority of usage was done by a single app.
1260 // TODO: support shared UIDs
1261 if (maxBytes > 0 && maxBytes > totalBytes / 2) {
1262 final String[] packageNames = mContext.getPackageManager().getPackagesForUid(maxUid);
Jeff Sharkeyd37154e2018-03-26 16:50:59 -06001263 if (packageNames != null && packageNames.length == 1) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001264 try {
1265 return mContext.getPackageManager().getApplicationInfo(packageNames[0],
1266 MATCH_ANY_USER | MATCH_DISABLED_COMPONENTS | MATCH_DIRECT_BOOT_AWARE
1267 | MATCH_DIRECT_BOOT_UNAWARE | MATCH_UNINSTALLED_PACKAGES);
1268 } catch (NameNotFoundException ignored) {
1269 }
1270 }
1271 }
1272
1273 return null;
1274 }
1275
1276 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001277 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001278 * current device state, such as when
1279 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1280 * data connection status.
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001281 *
1282 * @return relevant subId, or {@link #INVALID_SUBSCRIPTION_ID} when no
1283 * matching subId found.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001284 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001285 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001286 private int findRelevantSubIdNL(NetworkTemplate template) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001287 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey146bb332018-04-18 15:42:57 -06001288 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1289 final int subId = mSubIdToSubscriberId.keyAt(i);
1290 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001291 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1292 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1293 true);
1294 if (template.matches(probeIdent)) {
1295 return subId;
Jeff Sharkey32566012014-12-02 18:30:14 -08001296 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001297 }
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06001298 return INVALID_SUBSCRIPTION_ID;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001299 }
1300
1301 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001302 * Notify that given {@link NetworkTemplate} is over
1303 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1304 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001305 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001306 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001307 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001308 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001309 mOverLimitNotified.add(template);
1310 }
1311 }
1312
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001313 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001314 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001315 mOverLimitNotified.remove(template);
1316 }
1317
1318 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001319 * Show notification for combined {@link NetworkPolicy} and specific type,
1320 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1321 */
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001322 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes,
1323 ApplicationInfo rapidBlame) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001324 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001325 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001326 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001327 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001328 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001329 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001330 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001331
1332 final Resources res = mContext.getResources();
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001333 final CharSequence title;
1334 final CharSequence body;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001335 switch (type) {
1336 case TYPE_WARNING: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001337 title = res.getText(R.string.data_usage_warning_title);
1338 body = res.getString(R.string.data_usage_warning_body,
1339 Formatter.formatFileSize(mContext, totalBytes));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001340
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001341 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001342
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001343 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1344 builder.setDeleteIntent(PendingIntent.getBroadcast(
1345 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1346
Wei Liu546cb772016-07-21 16:19:01 -07001347 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001348 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001349 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1350
Jeff Sharkey497e4432011-06-14 17:27:29 -07001351 break;
1352 }
1353 case TYPE_LIMIT: {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001354 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001355 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001357 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001358 case MATCH_WIFI:
1359 title = res.getText(R.string.data_usage_wifi_limit_title);
1360 break;
1361 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001362 return;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001363 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001364 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001365
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001366 builder.setOngoing(true);
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001367 builder.setSmallIcon(R.drawable.stat_notify_disabled_data);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001368
Wei Liu546cb772016-07-21 16:19:01 -07001369 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001370 builder.setContentIntent(PendingIntent.getActivity(
1371 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1372 break;
1373 }
1374 case TYPE_LIMIT_SNOOZED: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001375 switch (policy.template.getMatchRule()) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001376 case MATCH_MOBILE:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001377 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1378 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001379 case MATCH_WIFI:
1380 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1381 break;
1382 default:
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001383 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001384 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001385 final long overBytes = totalBytes - policy.limitBytes;
1386 body = res.getString(R.string.data_usage_limit_snoozed_body,
1387 Formatter.formatFileSize(mContext, overBytes));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001388
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001389 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001390 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001391 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001392
Wei Liu546cb772016-07-21 16:19:01 -07001393 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001394 builder.setContentIntent(PendingIntent.getActivity(
1395 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001396 break;
1397 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001398 case TYPE_RAPID: {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001399 title = res.getText(R.string.data_usage_rapid_title);
1400 if (rapidBlame != null) {
1401 body = res.getString(R.string.data_usage_rapid_app_body,
1402 rapidBlame.loadLabel(mContext.getPackageManager()));
1403 } else {
1404 body = res.getString(R.string.data_usage_rapid_body);
1405 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001406
Jeff Sharkey2e471452018-01-19 18:02:47 +09001407 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001408
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001409 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1410 builder.setDeleteIntent(PendingIntent.getBroadcast(
1411 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1412
1413 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001414 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001415 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001416 break;
1417 }
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001418 default: {
1419 return;
1420 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001421 }
1422
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001423 builder.setTicker(title);
1424 builder.setContentTitle(title);
1425 builder.setContentText(body);
1426 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001427
1428 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1429 notificationId.getId(), builder.build(), UserHandle.ALL);
1430 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001431 }
1432
Chris Wren193ae6b2017-03-31 15:17:11 -04001433 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001434 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1435 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001436 }
1437
1438 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001439 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001440 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001441 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001442 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001443 @Override
1444 public void onReceive(Context context, Intent intent) {
1445 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1446 // permission above.
Jeff Sharkey146bb332018-04-18 15:42:57 -06001447 updateNetworksInternal();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001448 }
1449 };
1450
Jeff Sharkey146bb332018-04-18 15:42:57 -06001451 private void updateNetworksInternal() {
1452 // Get all of our cross-process communication with telephony out of
1453 // the way before we acquire internal locks.
1454 updateSubscriptions();
1455
1456 synchronized (mUidRulesFirstLock) {
1457 synchronized (mNetworkPoliciesSecondLock) {
1458 ensureActiveMobilePolicyAL();
1459 normalizePoliciesNL();
1460 updateNetworkEnabledNL();
1461 updateNetworkRulesNL();
1462 updateNotificationsNL();
1463 }
1464 }
1465 }
1466
Jeff Sharkey2e471452018-01-19 18:02:47 +09001467 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001468 void updateNetworks() throws InterruptedException {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001469 updateNetworksInternal();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001470 final CountDownLatch latch = new CountDownLatch(1);
1471 mHandler.post(() -> {
1472 latch.countDown();
1473 });
1474 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001475 }
1476
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001477 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001478 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1479 * if necessary.
1480 *
1481 * @param subId that has its associated NetworkPolicy updated if necessary
1482 * @return if any policies were updated
1483 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001484 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey146bb332018-04-18 15:42:57 -06001485 private boolean maybeUpdateMobilePolicyCycleAL(int subId, String subscriberId) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001486 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001487
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001488 // find and update the mobile NetworkPolicy for this subscriber id
Jeff Sharkey146bb332018-04-18 15:42:57 -06001489 boolean policyUpdated = false;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001490 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001491 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001492 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1493 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1494 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001495 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1496 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001497 }
1498 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001499 return policyUpdated;
1500 }
1501
1502 /**
1503 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1504 *
1505 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1506 * to do so, it returns the fallback value.
1507 *
1508 * @param config The CarrierConfig to read the value from.
1509 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1510 * @return cycleDay to use in the mobile NetworkPolicy.
1511 */
1512 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001513 int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001514 int fallbackCycleDay) {
1515 if (config == null) {
1516 return fallbackCycleDay;
1517 }
1518 int cycleDay =
1519 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1520 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1521 return fallbackCycleDay;
1522 }
1523 // validate cycleDay value
1524 final Calendar cal = Calendar.getInstance();
1525 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1526 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1527 Slog.e(TAG, "Invalid date in "
1528 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1529 return fallbackCycleDay;
1530 }
1531 return cycleDay;
1532 }
1533
1534 /**
1535 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1536 *
1537 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1538 * to do so, it returns the fallback value.
1539 *
1540 * @param config The CarrierConfig to read the value from.
1541 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1542 * @return warningBytes to use in the mobile NetworkPolicy.
1543 */
1544 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001545 long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001546 long fallbackWarningBytes) {
1547 if (config == null) {
1548 return fallbackWarningBytes;
1549 }
1550 long warningBytes =
1551 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1552
1553 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1554 return WARNING_DISABLED;
1555 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1556 return getPlatformDefaultWarningBytes();
1557 } else if (warningBytes < 0) {
1558 Slog.e(TAG, "Invalid value in "
1559 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1560 + "non-negative value but got: " + warningBytes);
1561 return fallbackWarningBytes;
1562 }
1563
1564 return warningBytes;
1565 }
1566
1567 /**
1568 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1569 *
1570 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1571 * to do so, it returns the fallback value.
1572 *
1573 * @param config The CarrierConfig to read the value from.
1574 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1575 * @return limitBytes to use in the mobile NetworkPolicy.
1576 */
1577 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08001578 long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001579 long fallbackLimitBytes) {
1580 if (config == null) {
1581 return fallbackLimitBytes;
1582 }
1583 long limitBytes =
1584 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1585
1586 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1587 return LIMIT_DISABLED;
1588 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1589 return getPlatformDefaultLimitBytes();
1590 } else if (limitBytes < 0) {
1591 Slog.e(TAG, "Invalid value in "
1592 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1593 + "non-negative value but got: " + limitBytes);
1594 return fallbackLimitBytes;
1595 }
1596 return limitBytes;
1597 }
1598
1599 /**
1600 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1601 */
1602 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1603 @Override
1604 public void onReceive(Context context, Intent intent) {
1605 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1606 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1607
1608 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1609 return;
1610 }
1611 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkey146bb332018-04-18 15:42:57 -06001612
1613 // Get all of our cross-process communication with telephony out of
1614 // the way before we acquire internal locks.
1615 updateSubscriptions();
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001616
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001617 synchronized (mUidRulesFirstLock) {
1618 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey146bb332018-04-18 15:42:57 -06001619 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
1620 if (subscriberId != null) {
1621 ensureActiveMobilePolicyAL(subId, subscriberId);
1622 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
1623 } else {
1624 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1625 }
1626
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001627 // update network and notification rules, as the data cycle changed and it's
1628 // possible that we should be triggering warnings/limits now
1629 handleNetworkPoliciesUpdateAL(true);
1630 }
1631 }
1632 }
1633 };
1634
1635 /**
1636 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1637 * one has been updated.
1638 *
1639 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1640 * update.
1641 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001642 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001643 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1644 if (shouldNormalizePolicies) {
1645 normalizePoliciesNL();
1646 }
1647 updateNetworkEnabledNL();
1648 updateNetworkRulesNL();
1649 updateNotificationsNL();
1650 writePolicyAL();
1651 }
1652
1653 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001654 * Proactively control network data connections when they exceed
1655 * {@link NetworkPolicy#limitBytes}.
1656 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001657 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001658 void updateNetworkEnabledNL() {
1659 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001660 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkEnabledNL");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001661
1662 // TODO: reset any policy-disabled networks when any policy is removed
1663 // completely, which is currently rare case.
1664
Makoto Onuki49392d32018-04-11 13:51:02 -07001665 final long startTime = mStatLogger.getTime();
1666
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001667 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1668 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001669 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001670 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001671 setNetworkTemplateEnabled(policy.template, true);
1672 continue;
1673 }
1674
Jeff Sharkey53313d72017-07-13 16:47:32 -06001675 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1676 .cycleIterator(policy).next();
1677 final long start = cycle.first.toInstant().toEpochMilli();
1678 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001679 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001680
1681 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001682 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1683 && policy.lastLimitSnooze < start;
1684 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001685
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001686 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001687 }
Makoto Onuki49392d32018-04-11 13:51:02 -07001688
1689 mStatLogger.logDurationStat(Stats.UPDATE_NETWORK_ENABLED, startTime);
Jeff Sharkey00072392018-04-12 14:26:32 -06001690 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001691 }
1692
1693 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001694 * Proactively disable networks that match the given
1695 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001696 */
1697 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07001698 // Don't call setNetworkTemplateEnabledInner() directly because we may have a lock
1699 // held. Call it via the handler.
1700 mHandler.obtainMessage(MSG_SET_NETWORK_TEMPLATE_ENABLED, enabled ? 1 : 0, 0, template)
1701 .sendToTarget();
1702 }
1703
1704 private void setNetworkTemplateEnabledInner(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001705 // TODO: reach into ConnectivityManager to proactively disable bringing
1706 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001707
Jeff Sharkeye0c29952018-02-20 17:24:55 -07001708 if (template.getMatchRule() == MATCH_MOBILE) {
Jack Yu8781b682016-07-08 14:28:51 -07001709 // If mobile data usage hits the limit or if the user resumes the data, we need to
1710 // notify telephony.
Jack Yu8781b682016-07-08 14:28:51 -07001711
Jeff Sharkey146bb332018-04-18 15:42:57 -06001712 final IntArray matchingSubIds = new IntArray();
1713 synchronized (mNetworkPoliciesSecondLock) {
1714 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1715 final int subId = mSubIdToSubscriberId.keyAt(i);
1716 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
1717
1718 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1719 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1720 true);
1721 // Template is matched when subscriber id matches.
1722 if (template.matches(probeIdent)) {
1723 matchingSubIds.add(subId);
1724 }
Jack Yu8781b682016-07-08 14:28:51 -07001725 }
1726 }
Jeff Sharkey146bb332018-04-18 15:42:57 -06001727
1728 // Only talk with telephony outside of locks
1729 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1730 for (int i = 0; i < matchingSubIds.size(); i++) {
1731 final int subId = matchingSubIds.get(i);
1732 tm.setPolicyDataEnabled(enabled, subId);
1733 }
Jack Yu8781b682016-07-08 14:28:51 -07001734 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001735 }
1736
1737 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001738 * Collect all ifaces from a {@link NetworkState} into the given set.
1739 */
1740 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1741 final String baseIface = state.linkProperties.getInterfaceName();
1742 if (baseIface != null) {
1743 ifaces.add(baseIface);
1744 }
1745 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1746 final String stackedIface = stackedLink.getInterfaceName();
1747 if (stackedIface != null) {
1748 ifaces.add(stackedIface);
1749 }
1750 }
1751 }
1752
1753 /**
Jeff Sharkey146bb332018-04-18 15:42:57 -06001754 * Examine all currently active subscriptions from
1755 * {@link SubscriptionManager#getActiveSubscriptionIdList()} and update
1756 * internal data structures.
1757 * <p>
1758 * Callers <em>must not</em> hold any locks when this method called.
1759 */
1760 void updateSubscriptions() {
1761 if (LOGV) Slog.v(TAG, "updateSubscriptions()");
1762 Trace.traceBegin(TRACE_TAG_NETWORK, "updateSubscriptions");
1763
1764 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
1765 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1766
1767 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
1768 final String[] mergedSubscriberIds = ArrayUtils.defeatNullable(tm.getMergedSubscriberIds());
1769
1770 final SparseArray<String> subIdToSubscriberId = new SparseArray<>(subIds.length);
1771 for (int subId : subIds) {
1772 final String subscriberId = tm.getSubscriberId(subId);
1773 if (!TextUtils.isEmpty(subscriberId)) {
1774 subIdToSubscriberId.put(subId, subscriberId);
1775 } else {
1776 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
1777 }
1778 }
1779
1780 synchronized (mNetworkPoliciesSecondLock) {
1781 mSubIdToSubscriberId.clear();
1782 for (int i = 0; i < subIdToSubscriberId.size(); i++) {
1783 mSubIdToSubscriberId.put(subIdToSubscriberId.keyAt(i),
1784 subIdToSubscriberId.valueAt(i));
1785 }
1786
1787 mMergedSubscriberIds = mergedSubscriberIds;
1788 }
1789
1790 Trace.traceEnd(TRACE_TAG_NETWORK);
1791 }
1792
1793 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001794 * Examine all connected {@link NetworkState}, looking for
1795 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1796 * remaining quota based on usage cycle and historical stats.
1797 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001798 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07001799 void updateNetworkRulesNL() {
1800 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey00072392018-04-12 14:26:32 -06001801 Trace.traceBegin(TRACE_TAG_NETWORK, "updateNetworkRulesNL");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802
1803 final NetworkState[] states;
1804 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001805 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001806 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001807 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001808 return;
1809 }
1810
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001811 // First, generate identities of all connected networks so we can
1812 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001813 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001814 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001815 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001816 if (state.network != null) {
1817 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1818 }
Wei Liub8eaf452016-01-25 10:32:27 -08001819 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001820 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1821 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001822 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001823 }
1824 }
1825
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001826 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001827 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001828
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001829 // For every well-defined policy, compute remaining data based on
1830 // current cycle and historical stats, and push to kernel.
1831 final ArraySet<String> matchingIfaces = new ArraySet<>();
1832 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1833 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1834
1835 // Collect all ifaces that match this policy
1836 matchingIfaces.clear();
1837 for (int j = identified.size() - 1; j >= 0; j--) {
1838 if (policy.template.matches(identified.valueAt(j))) {
1839 collectIfaces(matchingIfaces, identified.keyAt(j));
1840 }
1841 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001842
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001843 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001844 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001845 }
1846
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001847 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001848 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001849 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001850 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001851 if (hasLimit && policy.hasCycle()) {
1852 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1853 .cycleIterator(policy).next();
1854 final long start = cycle.first.toInstant().toEpochMilli();
1855 final long end = cycle.second.toInstant().toEpochMilli();
1856 final long totalBytes = getTotalBytes(policy.template, start, end);
1857
1858 if (policy.lastLimitSnooze >= start) {
1859 // snoozing past quota, but we still need to restrict apps,
1860 // so push really high quota.
1861 quotaBytes = Long.MAX_VALUE;
1862 } else {
1863 // remaining "quota" bytes are based on total usage in
1864 // current cycle. kernel doesn't like 0-byte rules, so we
1865 // set 1-byte quota and disable the radio later.
1866 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1867 }
1868 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001869 // metered network, but no policy limit; we still need to
1870 // restrict apps, so push really high quota.
1871 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001872 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001873
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001874 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001875 // TODO: switch to shared quota once NMS supports
1876 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001877 }
1878
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001879 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1880 final String iface = matchingIfaces.valueAt(j);
1881 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001882 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001883 }
1884 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001885
1886 // keep track of lowest warning or limit of active policies
1887 if (hasWarning && policy.warningBytes < lowestRule) {
1888 lowestRule = policy.warningBytes;
1889 }
1890 if (hasLimit && policy.limitBytes < lowestRule) {
1891 lowestRule = policy.limitBytes;
1892 }
1893 }
1894
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001895 // One final pass to catch any metered ifaces that don't have explicitly
1896 // defined policies; typically Wi-Fi networks.
1897 for (NetworkState state : states) {
1898 if (state.networkInfo != null && state.networkInfo.isConnected()
1899 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1900 matchingIfaces.clear();
1901 collectIfaces(matchingIfaces, state);
1902 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1903 final String iface = matchingIfaces.valueAt(j);
1904 if (!newMeteredIfaces.contains(iface)) {
1905 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1906 newMeteredIfaces.add(iface);
1907 }
1908 }
1909 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001910 }
1911
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001912 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001913 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1914 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001915 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001916 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001917 }
1918 }
1919 mMeteredIfaces = newMeteredIfaces;
1920
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001921 final ContentResolver cr = mContext.getContentResolver();
1922 final boolean quotaEnabled = Settings.Global.getInt(cr,
1923 NETPOLICY_QUOTA_ENABLED, 1) != 0;
1924 final long quotaUnlimited = Settings.Global.getLong(cr,
1925 NETPOLICY_QUOTA_UNLIMITED, QUOTA_UNLIMITED_DEFAULT);
1926 final float quotaLimited = Settings.Global.getFloat(cr,
1927 NETPOLICY_QUOTA_LIMITED, QUOTA_LIMITED_DEFAULT);
1928
Jeff Sharkey9252b342018-01-19 07:58:35 +09001929 // Finally, calculate our opportunistic quotas
Jeff Sharkey9252b342018-01-19 07:58:35 +09001930 mSubscriptionOpportunisticQuota.clear();
1931 for (NetworkState state : states) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001932 if (!quotaEnabled) continue;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001933 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001934 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001935 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001936 if (plan == null) continue;
1937
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001938 final long quotaBytes;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001939 final long limitBytes = plan.getDataLimitBytes();
Remi NGUYEN VANed6d2ca2018-04-04 11:12:51 +09001940 if (!state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_ROAMING)) {
1941 // Clamp to 0 when roaming
1942 quotaBytes = 0;
1943 } else if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001944 quotaBytes = OPPORTUNISTIC_QUOTA_UNKNOWN;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001945 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001946 // Unlimited data; let's use 20MiB/day (600MiB/month)
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001947 quotaBytes = quotaUnlimited;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001948 } else {
1949 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001950 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
1951 final long start = cycle.getLower().toInstant().toEpochMilli();
1952 final long end = cycle.getUpper().toInstant().toEpochMilli();
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001953 final Instant now = mClock.instant();
Jeff Sharkey0fc6d032018-03-30 16:25:11 -06001954 final long startOfDay = ZonedDateTime.ofInstant(now, cycle.getLower().getZone())
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001955 .truncatedTo(ChronoUnit.DAYS)
1956 .toInstant().toEpochMilli();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001957 final long totalBytes = getTotalBytes(
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001958 NetworkTemplate.buildTemplateMobileAll(state.subscriberId),
1959 start, startOfDay);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001960 final long remainingBytes = limitBytes - totalBytes;
Remi NGUYEN VANbed7b972018-04-02 15:48:19 +09001961 // Number of remaining days including current day
1962 final long remainingDays =
1963 1 + ((end - now.toEpochMilli() - 1) / TimeUnit.DAYS.toMillis(1));
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09001964
Jeff Sharkey36b414b2018-03-30 11:00:03 -06001965 quotaBytes = Math.max(0, (long) ((remainingBytes / remainingDays) * quotaLimited));
Jeff Sharkey9252b342018-01-19 07:58:35 +09001966 }
1967
1968 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1969 }
1970
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001971 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001972 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001973
1974 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey00072392018-04-12 14:26:32 -06001975
1976 Trace.traceEnd(TRACE_TAG_NETWORK);
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001977 }
1978
1979 /**
1980 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1981 * have at least a default mobile policy defined.
1982 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07001983 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09001984 private void ensureActiveMobilePolicyAL() {
1985 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001986 if (mSuppressDefaultPolicy) return;
1987
Jeff Sharkey146bb332018-04-18 15:42:57 -06001988 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
1989 final int subId = mSubIdToSubscriberId.keyAt(i);
1990 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001991
Hugo Benichi446c9c92017-04-10 09:41:10 +09001992 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001993 }
1994 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001995
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001996 /**
1997 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1998 * have at least a default mobile policy defined.
1999 *
2000 * @param subId to build a default policy for
2001 * @param subscriberId that we check for an existing policy
2002 * @return true if a mobile network policy was added, or false one already existed.
2003 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002004 @GuardedBy("mNetworkPoliciesSecondLock")
Hugo Benichi446c9c92017-04-10 09:41:10 +09002005 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002006 // Poke around to see if we already have a policy
2007 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09002008 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08002009 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
2010 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
2011 if (template.matches(probeIdent)) {
2012 if (LOGD) {
2013 Slog.d(TAG, "Found template " + template + " which matches subscriber "
2014 + NetworkIdentity.scrubSubscriberId(subscriberId));
2015 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002016 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002017 }
2018 }
2019
Jeff Sharkey32566012014-12-02 18:30:14 -08002020 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
2021 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002022 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09002023 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002024 return true;
2025 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002026
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002027 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07002028 final int dataWarningConfig = mContext.getResources().getInteger(
2029 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07002030 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002031 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07002032 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002033 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07002034 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002035 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002036
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002037 private long getPlatformDefaultLimitBytes() {
2038 return LIMIT_DISABLED;
2039 }
2040
2041 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08002042 NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002043 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002044 final RecurrenceRule cycleRule = NetworkPolicy
2045 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002046 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002047 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
2048 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
2049 synchronized (mUidRulesFirstLock) {
2050 synchronized (mNetworkPoliciesSecondLock) {
2051 updateDefaultMobilePolicyAL(subId, policy);
2052 }
2053 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002054 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002055 }
2056
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002057 /**
2058 * Update the given {@link NetworkPolicy} based on any carrier-provided
2059 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
2060 * Leaves policy untouched if the user has modified it.
2061 *
2062 * @return if the policy was modified
2063 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002064 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002065 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
2066 if (!policy.inferred) {
2067 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
2068 return false;
2069 }
2070
2071 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
2072 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
2073 policy.lastLimitSnooze, policy.metered, policy.inferred);
2074
2075 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
2076 if (!ArrayUtils.isEmpty(plans)) {
2077 final SubscriptionPlan plan = plans[0];
2078 policy.cycleRule = plan.getCycleRule();
2079 final long planLimitBytes = plan.getDataLimitBytes();
2080 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
2081 policy.warningBytes = getPlatformDefaultWarningBytes();
2082 policy.limitBytes = getPlatformDefaultLimitBytes();
2083 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
2084 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
2085 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2086 } else {
2087 policy.warningBytes = (planLimitBytes * 9) / 10;
2088 switch (plan.getDataLimitBehavior()) {
2089 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
2090 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
2091 policy.limitBytes = planLimitBytes;
2092 break;
2093 default:
2094 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2095 break;
2096 }
2097 }
2098 } else {
2099 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
2100 final int currentCycleDay;
2101 if (policy.cycleRule.isMonthly()) {
2102 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
2103 } else {
2104 currentCycleDay = NetworkPolicy.CYCLE_NONE;
2105 }
2106 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
2107 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
2108 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
2109 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
2110 }
2111
2112 if (policy.equals(original)) {
2113 return false;
2114 } else {
2115 Slog.d(TAG, "Updated " + original + " to " + policy);
2116 return true;
2117 }
2118 }
2119
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002120 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002121 private void readPolicyAL() {
2122 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002123
2124 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002125 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002126 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002127 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002128 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002129
2130 FileInputStream fis = null;
2131 try {
2132 fis = mPolicyFile.openRead();
2133 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002134 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002135
Felipe Leme46b451f2016-08-19 08:46:17 -07002136 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
2137 // to skip UIDs that were explicitly blacklisted.
2138 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
2139
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002140 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002141 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002142 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002143 while ((type = in.next()) != END_DOCUMENT) {
2144 final String tag = in.getName();
2145 if (type == START_TAG) {
2146 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002147 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002148 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002149 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
2150 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002151 } else if (TAG_NETWORK_POLICY.equals(tag)) {
2152 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
2153 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002154 final String networkId;
2155 if (version >= VERSION_ADDED_NETWORK_ID) {
2156 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
2157 } else {
2158 networkId = null;
2159 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002160 final RecurrenceRule cycleRule;
2161 if (version >= VERSION_ADDED_CYCLE) {
2162 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2163 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2164 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2165 cycleRule = new RecurrenceRule(
2166 RecurrenceRule.convertZonedDateTime(start),
2167 RecurrenceRule.convertZonedDateTime(end),
2168 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002169 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002170 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
2171 final String cycleTimezone;
2172 if (version >= VERSION_ADDED_TIMEZONE) {
2173 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
2174 } else {
2175 cycleTimezone = "UTC";
2176 }
2177 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002178 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002179 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
2180 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002181 final long lastLimitSnooze;
2182 if (version >= VERSION_SPLIT_SNOOZE) {
2183 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
2184 } else if (version >= VERSION_ADDED_SNOOZE) {
2185 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002186 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002187 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002188 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002189 final boolean metered;
2190 if (version >= VERSION_ADDED_METERED) {
2191 metered = readBooleanAttribute(in, ATTR_METERED);
2192 } else {
2193 switch (networkTemplate) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07002194 case MATCH_MOBILE:
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002195 metered = true;
2196 break;
2197 default:
2198 metered = false;
2199 }
2200 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002201 final long lastWarningSnooze;
2202 if (version >= VERSION_SPLIT_SNOOZE) {
2203 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
2204 } else {
2205 lastWarningSnooze = SNOOZE_NEVER;
2206 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07002207 final boolean inferred;
2208 if (version >= VERSION_ADDED_INFERRED) {
2209 inferred = readBooleanAttribute(in, ATTR_INFERRED);
2210 } else {
2211 inferred = false;
2212 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002213
Jeff Sharkey32566012014-12-02 18:30:14 -08002214 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2215 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002216 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002217 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2218 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002219 lastLimitSnooze, metered, inferred));
2220 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002221
2222 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2223 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2224 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2225 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2226 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2227 RecurrenceRule.convertZonedDateTime(start),
2228 RecurrenceRule.convertZonedDateTime(end),
2229 RecurrenceRule.convertPeriod(period));
2230 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2231 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2232
2233 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2234 SubscriptionPlan.BYTES_UNKNOWN);
2235 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2236 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2237 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2238 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2239 builder.setDataLimit(limitBytes, limitBehavior);
2240 }
2241
2242 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2243 SubscriptionPlan.BYTES_UNKNOWN);
2244 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2245 SubscriptionPlan.TIME_UNKNOWN);
2246 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2247 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2248 builder.setDataUsage(usageBytes, usageTime);
2249 }
2250
2251 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2252 final SubscriptionPlan plan = builder.build();
2253 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2254 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2255
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002256 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2257 mSubscriptionPlansOwner.put(subId, ownerPackage);
2258
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002259 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002260 final int uid = readIntAttribute(in, ATTR_UID);
2261 final int policy = readIntAttribute(in, ATTR_POLICY);
2262
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002263 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002264 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002265 } else {
2266 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2267 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002268 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002269 final int appId = readIntAttribute(in, ATTR_APP_ID);
2270 final int policy = readIntAttribute(in, ATTR_POLICY);
2271
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002272 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002273 // app policy is deprecated so this is only used in pre system user split.
2274 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002275 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002276 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002277 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002278 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002279 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002280 } else if (TAG_WHITELIST.equals(tag)) {
2281 insideWhitelist = true;
2282 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2283 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002284 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002285 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2286 final int uid = readIntAttribute(in, ATTR_UID);
2287 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002288 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002289 } else if (type == END_TAG) {
2290 if (TAG_WHITELIST.equals(tag)) {
2291 insideWhitelist = false;
2292 }
2293
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002294 }
2295 }
2296
Felipe Leme46b451f2016-08-19 08:46:17 -07002297 final int size = whitelistedRestrictBackground.size();
2298 for (int i = 0; i < size; i++) {
2299 final int uid = whitelistedRestrictBackground.keyAt(i);
2300 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2301 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2302 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2303 + " because its policy is " + uidPoliciesToString(policy));
2304 continue;
2305 }
2306 if (UserHandle.isApp(uid)) {
2307 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2308 if (LOGV)
2309 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2310 setUidPolicyUncheckedUL(uid, newPolicy, false);
2311 } else {
2312 Slog.w(TAG, "unable to update policy on UID " + uid);
2313 }
2314 }
2315
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002316 } catch (FileNotFoundException e) {
2317 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002318 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002319 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002320 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002321 } finally {
2322 IoUtils.closeQuietly(fis);
2323 }
2324 }
2325
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002326 /**
2327 * Upgrade legacy background data flags, notifying listeners of one last
2328 * change to always-true.
2329 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002330 private void upgradeDefaultBackgroundDataUL() {
2331 // This method is only called when we're unable to find the network policy flag, which
2332 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002333
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002334 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002335 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002336 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2337
2338 // NOTE: We used to read the legacy setting here :
2339 //
2340 // final int legacyFlagValue = Settings.Secure.getInt(
2341 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2342 //
2343 // This is no longer necessary because we will never upgrade directly from Gingerbread
2344 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2345 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002346 }
2347
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002348 /**
2349 * Perform upgrade step of moving any user-defined meterness overrides over
2350 * into {@link WifiConfiguration}.
2351 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002352 @GuardedBy({"mNetworkPoliciesSecondLock", "mUidRulesFirstLock"})
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002353 private void upgradeWifiMeteredOverrideAL() {
2354 boolean modified = false;
2355 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2356 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2357 for (int i = 0; i < mNetworkPolicy.size(); ) {
2358 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2359 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2360 && !policy.inferred) {
2361 mNetworkPolicy.removeAt(i);
2362 modified = true;
2363
2364 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2365 for (WifiConfiguration config : configs) {
2366 if (Objects.equals(resolveNetworkId(config), networkId)) {
2367 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2368 config.meteredOverride = policy.metered
2369 ? WifiConfiguration.METERED_OVERRIDE_METERED
2370 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2371 wm.updateNetwork(config);
2372 }
2373 }
2374 } else {
2375 i++;
2376 }
2377 }
2378 if (modified) {
2379 writePolicyAL();
2380 }
2381 }
2382
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002383 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07002384 void writePolicyAL() {
2385 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002386
2387 FileOutputStream fos = null;
2388 try {
2389 fos = mPolicyFile.startWrite();
2390
2391 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002392 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002393 out.startDocument(null, true);
2394
2395 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002396 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002397 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002398
2399 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002400 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2401 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002402 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002403 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002404
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002405 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002406 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2407 final String subscriberId = template.getSubscriberId();
2408 if (subscriberId != null) {
2409 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002410 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002411 final String networkId = template.getNetworkId();
2412 if (networkId != null) {
2413 out.attribute(null, ATTR_NETWORK_ID, networkId);
2414 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002415 writeStringAttribute(out, ATTR_CYCLE_START,
2416 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2417 writeStringAttribute(out, ATTR_CYCLE_END,
2418 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2419 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2420 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002421 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2422 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002423 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2424 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002425 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002426 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002427 out.endTag(null, TAG_NETWORK_POLICY);
2428 }
2429
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002430 // write all known subscription plans
2431 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2432 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002433 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002434 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2435 if (ArrayUtils.isEmpty(plans)) continue;
2436
2437 for (SubscriptionPlan plan : plans) {
2438 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2439 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002440 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002441 final RecurrenceRule cycleRule = plan.getCycleRule();
2442 writeStringAttribute(out, ATTR_CYCLE_START,
2443 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2444 writeStringAttribute(out, ATTR_CYCLE_END,
2445 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2446 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2447 RecurrenceRule.convertPeriod(cycleRule.period));
2448 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2449 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2450 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2451 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2452 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2453 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2454 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2455 }
2456 }
2457
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002458 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002459 for (int i = 0; i < mUidPolicy.size(); i++) {
2460 final int uid = mUidPolicy.keyAt(i);
2461 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002462
Jeff Sharkey497e4432011-06-14 17:27:29 -07002463 // skip writing empty policies
2464 if (policy == POLICY_NONE) continue;
2465
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002466 out.startTag(null, TAG_UID_POLICY);
2467 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002468 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002469 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002470 }
2471
2472 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002473
2474 // write all whitelists
2475 out.startTag(null, TAG_WHITELIST);
2476
Felipe Lemea9505cc2016-02-26 10:28:41 -08002477 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002478 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002479 for (int i = 0; i < size; i++) {
2480 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2481 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2482 writeIntAttribute(out, ATTR_UID, uid);
2483 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2484 }
2485
Felipe Lemeb85a6372016-01-14 16:16:16 -08002486 out.endTag(null, TAG_WHITELIST);
2487
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002488 out.endDocument();
2489
2490 mPolicyFile.finishWrite(fos);
2491 } catch (IOException e) {
2492 if (fos != null) {
2493 mPolicyFile.failWrite(fos);
2494 }
2495 }
2496 }
2497
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002498 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002499 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002500 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002501
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002502 if (!UserHandle.isApp(uid)) {
2503 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002504 }
Felipe Lemef0823852016-06-08 13:43:08 -07002505 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002506 final long token = Binder.clearCallingIdentity();
2507 try {
2508 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2509 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002510 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002511 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002512 }
2513 } finally {
2514 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002515 }
2516 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002517 }
2518
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002519 @Override
2520 public void addUidPolicy(int uid, int policy) {
2521 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002522
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002523 if (!UserHandle.isApp(uid)) {
2524 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2525 }
2526
Felipe Lemef0823852016-06-08 13:43:08 -07002527 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002528 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2529 policy |= oldPolicy;
2530 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002531 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002532 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002533 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002534 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002535 }
2536
2537 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002538 public void removeUidPolicy(int uid, int policy) {
2539 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2540
2541 if (!UserHandle.isApp(uid)) {
2542 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2543 }
2544
Felipe Lemef0823852016-06-08 13:43:08 -07002545 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002546 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2547 policy = oldPolicy & ~policy;
2548 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002549 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002550 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002551 }
2552 }
2553 }
2554
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002555 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002556 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002557 setUidPolicyUncheckedUL(uid, policy, false);
Felipe Leme923845f2016-03-02 13:42:48 -08002558
Felipe Leme57e3d312016-08-23 14:42:52 -07002559 final boolean notifyApp;
2560 if (!isUidValidForWhitelistRules(uid)) {
2561 notifyApp = false;
2562 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002563 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2564 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2565 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2566 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002567 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2568 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002569 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2570 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2571 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2572 if (LOGD)
2573 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2574 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2575 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002576 notifyApp = wasBlocked != isBlocked;
2577 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002578 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2579 .sendToTarget();
Sudheer Shanka5723ccb2018-02-13 11:08:19 -08002580 if (persist) {
2581 synchronized (mNetworkPoliciesSecondLock) {
2582 writePolicyAL();
2583 }
2584 }
Felipe Leme923845f2016-03-02 13:42:48 -08002585 }
2586
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002587 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002588 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002589 if (policy == POLICY_NONE) {
2590 mUidPolicy.delete(uid);
2591 } else {
2592 mUidPolicy.put(uid, policy);
2593 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002594
2595 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002596 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002597 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002598 synchronized (mNetworkPoliciesSecondLock) {
2599 writePolicyAL();
2600 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002601 }
2602 }
2603
2604 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002605 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002606 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2607
Felipe Lemef0823852016-06-08 13:43:08 -07002608 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002609 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002610 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002611 }
2612
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002613 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002614 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002615 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2616
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002617 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002618 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002619 for (int i = 0; i < mUidPolicy.size(); i++) {
2620 final int uid = mUidPolicy.keyAt(i);
2621 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002622 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2623 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002624 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002625 }
2626 }
2627 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002628 return uids;
2629 }
2630
2631 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002632 * Removes any persistable state associated with given {@link UserHandle}, persisting
2633 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002634 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002635 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002636 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002637
Sudheer Shanka352dc572017-09-22 17:09:38 -07002638 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002639 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002640
Felipe Lemea110eec2016-04-29 09:58:06 -07002641 // Remove entries from revoked default restricted background UID whitelist
2642 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2643 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2644 if (UserHandle.getUserId(uid) == userId) {
2645 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002646 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002647 }
2648 }
2649
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002650 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002651 int[] uids = new int[0];
2652 for (int i = 0; i < mUidPolicy.size(); i++) {
2653 final int uid = mUidPolicy.keyAt(i);
2654 if (UserHandle.getUserId(uid) == userId) {
2655 uids = appendInt(uids, uid);
2656 }
2657 }
2658
2659 if (uids.length > 0) {
2660 for (int uid : uids) {
2661 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002662 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002663 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002664 }
Felipe Lemef0823852016-06-08 13:43:08 -07002665 synchronized (mNetworkPoliciesSecondLock) {
2666 updateRulesForGlobalChangeAL(true);
2667 if (writePolicy && changed) {
2668 writePolicyAL();
2669 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002670 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002671 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002672 }
2673
2674 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002675 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002676 // TODO: create permission for observing network policy
2677 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002678 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002679 }
2680
2681 @Override
2682 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002683 // TODO: create permission for observing network policy
2684 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002685 mListeners.unregister(listener);
2686 }
2687
Jeff Sharkey1b861272011-05-22 00:34:52 -07002688 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002689 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002690 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2691
Felipe Leme6a05eee2016-02-19 14:43:51 -08002692 final long token = Binder.clearCallingIdentity();
2693 try {
Felipe Lemef0823852016-06-08 13:43:08 -07002694 synchronized (mUidRulesFirstLock) {
2695 synchronized (mNetworkPoliciesSecondLock) {
2696 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002697 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002698 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002699 }
2700 } finally {
2701 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002702 }
2703 }
2704
Hugo Benichi446c9c92017-04-10 09:41:10 +09002705 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002706 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002707 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2708 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002709 }
2710
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002711 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002712 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002713 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002714 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002715 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2716 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2717 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002718 } catch (SecurityException e) {
2719 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002720
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002721 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2722 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2723 return new NetworkPolicy[0];
2724 }
Svet Ganov16a16892015-04-16 10:32:04 -07002725 }
2726
Felipe Lemef0823852016-06-08 13:43:08 -07002727 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002728 final int size = mNetworkPolicy.size();
2729 final NetworkPolicy[] policies = new NetworkPolicy[size];
2730 for (int i = 0; i < size; i++) {
2731 policies[i] = mNetworkPolicy.valueAt(i);
2732 }
2733 return policies;
2734 }
2735 }
2736
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002737 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002738 private void normalizePoliciesNL() {
2739 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002740 }
2741
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002742 @GuardedBy("mNetworkPoliciesSecondLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002743 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002744 mNetworkPolicy.clear();
2745 for (NetworkPolicy policy : policies) {
Annie Meng20b4d842018-05-18 15:00:49 +01002746 if (policy == null) {
2747 continue;
2748 }
Jeff Sharkey32566012014-12-02 18:30:14 -08002749 // When two normalized templates conflict, prefer the most
2750 // restrictive policy
Jeff Sharkey146bb332018-04-18 15:42:57 -06002751 policy.template = NetworkTemplate.normalize(policy.template, mMergedSubscriberIds);
Jeff Sharkey32566012014-12-02 18:30:14 -08002752 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2753 if (existing == null || existing.compareTo(policy) > 0) {
2754 if (existing != null) {
2755 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2756 }
2757 mNetworkPolicy.put(policy.template, policy);
2758 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002759 }
2760 }
2761
2762 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002763 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002764 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002765
2766 final long token = Binder.clearCallingIdentity();
2767 try {
2768 performSnooze(template, TYPE_LIMIT);
2769 } finally {
2770 Binder.restoreCallingIdentity(token);
2771 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002772 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002773
Dianne Hackborn497175b2014-07-01 12:56:08 -07002774 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey9911a282018-02-14 22:29:11 -07002775 final long currentTime = mClock.millis();
Felipe Lemef0823852016-06-08 13:43:08 -07002776 synchronized (mUidRulesFirstLock) {
2777 synchronized (mNetworkPoliciesSecondLock) {
2778 // find and snooze local policy that matches
2779 final NetworkPolicy policy = mNetworkPolicy.get(template);
2780 if (policy == null) {
2781 throw new IllegalArgumentException("unable to find policy for " + template);
2782 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002783
Felipe Lemef0823852016-06-08 13:43:08 -07002784 switch (type) {
2785 case TYPE_WARNING:
2786 policy.lastWarningSnooze = currentTime;
2787 break;
2788 case TYPE_LIMIT:
2789 policy.lastLimitSnooze = currentTime;
2790 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002791 case TYPE_RAPID:
2792 policy.lastRapidSnooze = currentTime;
2793 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002794 default:
2795 throw new IllegalArgumentException("unexpected type");
2796 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002797
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002798 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002799 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002800 }
2801 }
2802
2803 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002804 public void onTetheringChanged(String iface, boolean tethering) {
2805 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002806 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002807 if (mRestrictBackground && tethering) {
2808 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2809 setRestrictBackground(false);
2810 }
2811 }
2812 }
2813
2814 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002815 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002816 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002817 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002818 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2819 final long token = Binder.clearCallingIdentity();
2820 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002821 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002822 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002823 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002824 } finally {
2825 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002826 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002827 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002828 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002829 }
2830 }
2831
Andreas Gampeaae5aa32018-07-20 12:55:38 -07002832 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07002833 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002834 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002835 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002836 if (restrictBackground == mRestrictBackground) {
2837 // Ideally, UI should never allow this scenario...
2838 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002839 return;
2840 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002841 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2842 final boolean oldRestrictBackground = mRestrictBackground;
2843 mRestrictBackground = restrictBackground;
2844 // Must whitelist foreground apps before turning data saver mode on.
2845 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2846 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2847 updateRulesForRestrictBackgroundUL();
2848 try {
2849 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2850 Slog.e(TAG,
2851 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2852 mRestrictBackground = oldRestrictBackground;
2853 // TODO: if it knew the foreground apps (see TODO above), it could call
2854 // updateRulesForRestrictBackgroundUL() again to restore state.
2855 return;
2856 }
2857 } catch (RemoteException e) {
2858 // ignored; service lives in system_server
2859 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002860
Sudheer Shanka543339f2017-07-28 15:18:07 -07002861 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002862 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002863
2864 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2865 mRestrictBackgroundChangedInBsm = true;
2866 }
2867 synchronized (mNetworkPoliciesSecondLock) {
2868 updateNotificationsNL();
2869 writePolicyAL();
2870 }
2871 } finally {
2872 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002873 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002874 }
2875
2876 private void sendRestrictBackgroundChangedMsg() {
2877 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2878 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2879 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002880 }
2881
Felipe Lemeb85a6372016-01-14 16:16:16 -08002882 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002883 public int getRestrictBackgroundByCaller() {
2884 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2885 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002886
Felipe Lemef0823852016-06-08 13:43:08 -07002887 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002888 // Must clear identity because getUidPolicy() is restricted to system.
2889 final long token = Binder.clearCallingIdentity();
2890 final int policy;
2891 try {
2892 policy = getUidPolicy(uid);
2893 } finally {
2894 Binder.restoreCallingIdentity(token);
2895 }
2896 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2897 // App is blacklisted.
2898 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2899 }
Felipe Leme1b103232016-01-22 09:44:57 -08002900 if (!mRestrictBackground) {
2901 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2902 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002903 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002904 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2905 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2906 }
2907 }
2908
2909 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002910 public boolean getRestrictBackground() {
2911 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2912
Felipe Lemef0823852016-06-08 13:43:08 -07002913 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002914 return mRestrictBackground;
2915 }
2916 }
2917
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002918 @Override
2919 public void setDeviceIdleMode(boolean enabled) {
2920 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002921 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2922 try {
2923 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002924 if (mDeviceIdleMode == enabled) {
2925 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002926 }
Felipe Lemeea014392016-09-06 13:59:54 -07002927 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002928 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002929 if (mSystemReady) {
2930 // Device idle change means we need to rebuild rules for all
2931 // known apps, so do a global refresh.
2932 updateRulesForRestrictPowerUL();
2933 }
2934 }
2935 if (enabled) {
2936 EventLogTags.writeDeviceIdleOnPhase("net");
2937 } else {
2938 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002939 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002940 } finally {
2941 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002942 }
2943 }
2944
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002945 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002946 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2947 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002948 final long token = Binder.clearCallingIdentity();
2949 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002950 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2951 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2952 for (WifiConfiguration config : configs) {
2953 if (Objects.equals(resolveNetworkId(config), networkId)) {
2954 config.meteredOverride = meteredOverride;
2955 wm.updateNetwork(config);
2956 }
2957 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002958 } finally {
2959 Binder.restoreCallingIdentity(token);
2960 }
2961 }
2962
Jeff Sharkey46645002011-07-27 21:11:21 -07002963 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002964 @Deprecated
2965 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2966 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2967 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2968 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002969 }
2970
Jeff Sharkey53313d72017-07-13 16:47:32 -06002971 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2972 // Verify they're not lying about package name
2973 mAppOps.checkPackage(callingUid, callingPackage);
2974
Jeff Sharkey53313d72017-07-13 16:47:32 -06002975 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002976 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002977 final long token = Binder.clearCallingIdentity();
2978 try {
2979 si = mContext.getSystemService(SubscriptionManager.class)
2980 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002981 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002982 } finally {
2983 Binder.restoreCallingIdentity(token);
2984 }
2985
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002986 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002987 if (si != null) {
2988 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2989 return;
2990 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002991 }
2992
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002993 // Second check: has the CarrierService delegated access?
2994 if (config != null) {
2995 final String overridePackage = config
2996 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2997 if (!TextUtils.isEmpty(overridePackage)
2998 && Objects.equals(overridePackage, callingPackage)) {
2999 return;
3000 }
3001 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003002
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003003 // Third check: is caller the fallback/default CarrierService?
3004 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
3005 if (!TextUtils.isEmpty(defaultPackage)
3006 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06003007 return;
3008 }
3009
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003010 // Fourth check: is caller a testing app?
3011 final String testPackage = SystemProperties.get(PROP_SUB_PLAN_OWNER + "." + subId, null);
3012 if (!TextUtils.isEmpty(testPackage)
3013 && Objects.equals(testPackage, callingPackage)) {
3014 return;
3015 }
3016
3017 // Fifth check: is caller a legacy testing app?
3018 final String legacyTestPackage = SystemProperties.get("fw.sub_plan_owner." + subId, null);
3019 if (!TextUtils.isEmpty(legacyTestPackage)
3020 && Objects.equals(legacyTestPackage, callingPackage)) {
Jeff Sharkeya7f50462018-02-14 14:26:10 -07003021 return;
3022 }
3023
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003024 // Final check: does the caller hold a permission?
3025 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003026 }
3027
3028 @Override
3029 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
3030 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3031
Jeff Sharkey53313d72017-07-13 16:47:32 -06003032 final String fake = SystemProperties.get("fw.fake_plan");
3033 if (!TextUtils.isEmpty(fake)) {
3034 final List<SubscriptionPlan> plans = new ArrayList<>();
3035 if ("month_hard".equals(fake)) {
3036 plans.add(SubscriptionPlan.Builder
3037 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3038 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003039 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3040 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3041 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3042 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3043 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003044 plans.add(SubscriptionPlan.Builder
3045 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3046 .setTitle("G-Mobile Happy")
3047 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3048 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3049 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3050 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3051 .build());
3052 plans.add(SubscriptionPlan.Builder
3053 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3054 .setTitle("G-Mobile, Charged after limit")
3055 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3056 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
3057 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3058 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
3059 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003060 } else if ("month_soft".equals(fake)) {
3061 plans.add(SubscriptionPlan.Builder
3062 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3063 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3064 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
3065 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06003066 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3067 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3068 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
3069 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3070 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003071 plans.add(SubscriptionPlan.Builder
3072 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3073 .setTitle("G-Mobile, Throttled after limit")
3074 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3075 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3076 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3077 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3078 .build());
3079 plans.add(SubscriptionPlan.Builder
3080 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3081 .setTitle("G-Mobile, No data connection after limit")
3082 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3083 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3084 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3085 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3086 .build());
3087
Sundeep Ghuman09e0f572018-03-14 23:20:23 -07003088 } else if ("month_over".equals(fake)) {
3089 plans.add(SubscriptionPlan.Builder
3090 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3091 .setTitle("G-Mobile is the carriers name who this plan belongs to")
3092 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3093 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3094 .setDataUsage(6 * TrafficStats.GB_IN_BYTES,
3095 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3096 .build());
3097 plans.add(SubscriptionPlan.Builder
3098 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3099 .setTitle("G-Mobile, Throttled after limit")
3100 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3101 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3102 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3103 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3104 .build());
3105 plans.add(SubscriptionPlan.Builder
3106 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
3107 .setTitle("G-Mobile, No data connection after limit")
3108 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3109 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3110 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
3111 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3112 .build());
3113
Jeff Sharkey53313d72017-07-13 16:47:32 -06003114 } else if ("month_none".equals(fake)) {
3115 plans.add(SubscriptionPlan.Builder
3116 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
3117 .setTitle("G-Mobile")
3118 .build());
3119 } else if ("prepaid".equals(fake)) {
3120 plans.add(SubscriptionPlan.Builder
3121 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3122 ZonedDateTime.now().plusDays(10))
3123 .setTitle("G-Mobile")
3124 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3125 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3126 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3127 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3128 .build());
3129 } else if ("prepaid_crazy".equals(fake)) {
3130 plans.add(SubscriptionPlan.Builder
3131 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3132 ZonedDateTime.now().plusDays(10))
3133 .setTitle("G-Mobile Anytime")
3134 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
3135 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
3136 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
3137 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3138 .build());
3139 plans.add(SubscriptionPlan.Builder
3140 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3141 ZonedDateTime.now().plusDays(20))
3142 .setTitle("G-Mobile Nickel Nights")
3143 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003144 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
3145 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06003146 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
3147 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
3148 .build());
3149 plans.add(SubscriptionPlan.Builder
3150 .createNonrecurring(ZonedDateTime.now().minusDays(10),
3151 ZonedDateTime.now().plusDays(20))
3152 .setTitle("G-Mobile Bonus 3G")
3153 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003154 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06003155 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3156 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
3157 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
3158 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07003159 } else if ("unlimited".equals(fake)) {
3160 plans.add(SubscriptionPlan.Builder
3161 .createNonrecurring(ZonedDateTime.now().minusDays(20),
3162 ZonedDateTime.now().plusDays(10))
3163 .setTitle("G-Mobile Awesome")
3164 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
3165 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
3166 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
3167 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
3168 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06003169 }
3170 return plans.toArray(new SubscriptionPlan[plans.size()]);
3171 }
3172
Jeff Sharkey4635f102017-09-01 11:27:13 -06003173 synchronized (mNetworkPoliciesSecondLock) {
3174 // Only give out plan details to the package that defined them,
3175 // so that we don't risk leaking plans between apps. We always
3176 // let in core system components (like the Settings app).
3177 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
3178 if (Objects.equals(ownerPackage, callingPackage)
3179 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
3180 return mSubscriptionPlans.get(subId);
3181 } else {
3182 Log.w(TAG, "Not returning plans because caller " + callingPackage
3183 + " doesn't match owner " + ownerPackage);
3184 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06003185 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003186 }
3187 }
3188
3189 @Override
3190 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
3191 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3192
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003193 for (SubscriptionPlan plan : plans) {
3194 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003195 }
3196
3197 final long token = Binder.clearCallingIdentity();
3198 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003199 synchronized (mUidRulesFirstLock) {
3200 synchronized (mNetworkPoliciesSecondLock) {
3201 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06003202 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003203
Jeff Sharkey146bb332018-04-18 15:42:57 -06003204 final String subscriberId = mSubIdToSubscriberId.get(subId, null);
3205 if (subscriberId != null) {
3206 ensureActiveMobilePolicyAL(subId, subscriberId);
3207 maybeUpdateMobilePolicyCycleAL(subId, subscriberId);
3208 } else {
3209 Slog.wtf(TAG, "Missing subscriberId for subId " + subId);
3210 }
3211
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003212 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06003213 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06003214 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07003215
3216 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
3217 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3218 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
3219 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06003220 } finally {
3221 Binder.restoreCallingIdentity(token);
3222 }
3223 }
3224
Jeff Sharkey003d3e62018-03-30 14:35:04 -06003225 /**
3226 * Only visible for testing purposes. This doesn't give any access to
3227 * existing plans; it simply lets the debug package define new plans.
3228 */
3229 void setSubscriptionPlansOwner(int subId, String packageName) {
3230 SystemProperties.set(PROP_SUB_PLAN_OWNER + "." + subId, packageName);
3231 }
3232
Jeff Sharkey53313d72017-07-13 16:47:32 -06003233 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07003234 public String getSubscriptionPlansOwner(int subId) {
3235 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
3236 throw new SecurityException();
3237 }
3238
3239 synchronized (mNetworkPoliciesSecondLock) {
3240 return mSubscriptionPlansOwner.get(subId);
3241 }
3242 }
3243
3244 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09003245 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
3246 long timeoutMillis, String callingPackage) {
3247 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
3248
3249 // We can only override when carrier told us about plans
3250 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003251 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
3252 if (plan == null
3253 || plan.getDataLimitBehavior() == SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09003254 throw new IllegalStateException(
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06003255 "Must provide valid SubscriptionPlan to enable overriding");
Jeff Sharkey9252b342018-01-19 07:58:35 +09003256 }
3257 }
3258
Jeff Sharkey36b414b2018-03-30 11:00:03 -06003259 // Only allow overrides when feature is enabled. However, we always
3260 // allow disabling of overrides for safety reasons.
3261 final boolean overrideEnabled = Settings.Global.getInt(mContext.getContentResolver(),
3262 NETPOLICY_OVERRIDE_ENABLED, 1) != 0;
3263 if (overrideEnabled || overrideValue == 0) {
3264 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3265 overrideMask, overrideValue, subId));
3266 if (timeoutMillis > 0) {
3267 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
3268 overrideMask, 0, subId), timeoutMillis);
3269 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09003270 }
3271 }
3272
3273 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003274 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06003275 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07003276
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07003277 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
3278
Dianne Hackborn497175b2014-07-01 12:56:08 -07003279 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003280 for (String arg : args) {
3281 argSet.add(arg);
3282 }
3283
Felipe Lemef0823852016-06-08 13:43:08 -07003284 synchronized (mUidRulesFirstLock) {
3285 synchronized (mNetworkPoliciesSecondLock) {
3286 if (argSet.contains("--unsnooze")) {
3287 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3288 mNetworkPolicy.valueAt(i).clearSnooze();
3289 }
3290
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003291 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003292
3293 fout.println("Cleared snooze timestamps");
3294 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003295 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003296
Felipe Lemef0823852016-06-08 13:43:08 -07003297 fout.print("System ready: "); fout.println(mSystemReady);
3298 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3299 fout.print("Restrict power: "); fout.println(mRestrictPower);
3300 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003301 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3302
3303 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003304 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003305 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003306 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3307 fout.println(mNetworkPolicy.valueAt(i).toString());
3308 }
3309 fout.decreaseIndent();
3310
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003311 fout.println();
3312 fout.println("Subscription plans:");
3313 fout.increaseIndent();
3314 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3315 final int subId = mSubscriptionPlans.keyAt(i);
3316 fout.println("Subscriber ID " + subId + ":");
3317 fout.increaseIndent();
3318 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3319 if (!ArrayUtils.isEmpty(plans)) {
3320 for (SubscriptionPlan plan : plans) {
3321 fout.println(plan);
3322 }
3323 }
3324 fout.decreaseIndent();
3325 }
3326 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003327
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003328 fout.println();
Jeff Sharkey146bb332018-04-18 15:42:57 -06003329 fout.println("Active subscriptions:");
3330 fout.increaseIndent();
3331 for (int i = 0; i < mSubIdToSubscriberId.size(); i++) {
3332 final int subId = mSubIdToSubscriberId.keyAt(i);
3333 final String subscriberId = mSubIdToSubscriberId.valueAt(i);
3334
3335 fout.println(subId + "=" + NetworkIdentity.scrubSubscriberId(subscriberId));
3336 }
3337 fout.decreaseIndent();
3338
3339 fout.println();
3340 fout.println("Merged subscriptions: "
3341 + Arrays.toString(NetworkIdentity.scrubSubscriberId(mMergedSubscriberIds)));
3342
3343 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003344 fout.println("Policy for UIDs:");
3345 fout.increaseIndent();
3346 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003347 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003348 final int uid = mUidPolicy.keyAt(i);
3349 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003350 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003351 fout.print(uid);
3352 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003353 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003354 fout.println();
3355 }
3356 fout.decreaseIndent();
3357
3358 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3359 if (size > 0) {
3360 fout.println("Power save whitelist (except idle) app ids:");
3361 fout.increaseIndent();
3362 for (int i = 0; i < size; i++) {
3363 fout.print("UID=");
3364 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3365 fout.print(": ");
3366 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3367 fout.println();
3368 }
3369 fout.decreaseIndent();
3370 }
3371
3372 size = mPowerSaveWhitelistAppIds.size();
3373 if (size > 0) {
3374 fout.println("Power save whitelist app ids:");
3375 fout.increaseIndent();
3376 for (int i = 0; i < size; i++) {
3377 fout.print("UID=");
3378 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3379 fout.print(": ");
3380 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3381 fout.println();
3382 }
3383 fout.decreaseIndent();
3384 }
3385
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003386 size = mAppIdleTempWhitelistAppIds.size();
3387 if (size > 0) {
3388 fout.println("App idle whitelist app ids:");
3389 fout.increaseIndent();
3390 for (int i = 0; i < size; i++) {
3391 fout.print("UID=");
3392 fout.print(mAppIdleTempWhitelistAppIds.keyAt(i));
3393 fout.print(": ");
3394 fout.print(mAppIdleTempWhitelistAppIds.valueAt(i));
3395 fout.println();
3396 }
3397 fout.decreaseIndent();
3398 }
3399
Felipe Lemef0823852016-06-08 13:43:08 -07003400 size = mDefaultRestrictBackgroundWhitelistUids.size();
3401 if (size > 0) {
3402 fout.println("Default restrict background whitelist uids:");
3403 fout.increaseIndent();
3404 for (int i = 0; i < size; i++) {
3405 fout.print("UID=");
3406 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3407 fout.println();
3408 }
3409 fout.decreaseIndent();
3410 }
3411
3412 size = mRestrictBackgroundWhitelistRevokedUids.size();
3413 if (size > 0) {
3414 fout.println("Default restrict background whitelist uids revoked by users:");
3415 fout.increaseIndent();
3416 for (int i = 0; i < size; i++) {
3417 fout.print("UID=");
3418 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3419 fout.println();
3420 }
3421 fout.decreaseIndent();
3422 }
3423
3424 final SparseBooleanArray knownUids = new SparseBooleanArray();
3425 collectKeys(mUidState, knownUids);
3426 collectKeys(mUidRules, knownUids);
3427
3428 fout.println("Status for all known UIDs:");
3429 fout.increaseIndent();
3430 size = knownUids.size();
3431 for (int i = 0; i < size; i++) {
3432 final int uid = knownUids.keyAt(i);
3433 fout.print("UID=");
3434 fout.print(uid);
3435
3436 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3437 fout.print(" state=");
3438 fout.print(state);
3439 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3440 fout.print(" (fg)");
3441 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003442 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003443 ? " (fg svc)" : " (bg)");
3444 }
3445
3446 final int uidRules = mUidRules.get(uid, RULE_NONE);
3447 fout.print(" rules=");
3448 fout.print(uidRulesToString(uidRules));
3449 fout.println();
3450 }
3451 fout.decreaseIndent();
3452
3453 fout.println("Status for just UIDs with rules:");
3454 fout.increaseIndent();
3455 size = mUidRules.size();
3456 for (int i = 0; i < size; i++) {
3457 final int uid = mUidRules.keyAt(i);
3458 fout.print("UID=");
3459 fout.print(uid);
3460 final int uidRules = mUidRules.get(uid, RULE_NONE);
3461 fout.print(" rules=");
3462 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003463 fout.println();
3464 }
3465 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003466
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003467 fout.println("Admin restricted uids for metered data:");
3468 fout.increaseIndent();
3469 size = mMeteredRestrictedUids.size();
3470 for (int i = 0; i < size; ++i) {
3471 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3472 fout.println(mMeteredRestrictedUids.valueAt(i));
3473 }
3474 fout.decreaseIndent();
3475
Makoto Onuki49392d32018-04-11 13:51:02 -07003476 fout.println();
3477 mStatLogger.dump(fout);
3478
Sudheer Shanka352dc572017-09-22 17:09:38 -07003479 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003480 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003481 }
3482 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003483
3484 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003485 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003486 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003487 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003488 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003489 }
3490
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003491 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003492 boolean isUidForeground(int uid) {
Felipe Lemef0823852016-06-08 13:43:08 -07003493 synchronized (mUidRulesFirstLock) {
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003494 return isUidStateForeground(
3495 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003496 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003497 }
3498
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003499 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003500 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003501 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003502 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003503 }
3504
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003505 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003506 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003507 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3508 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3509 }
3510
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003511 private boolean isUidStateForeground(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003512 // only really in foreground when screen is also on
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003513 return state <= NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003514 }
3515
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003516 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003517 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003518 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3519 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003520 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003521 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00003522 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003523 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3524 try {
3525 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3526 if (oldUidState != uidState) {
3527 // state changed, push updated rules
3528 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003529 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3530 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3531 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003532 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003533 if (mDeviceIdleMode) {
3534 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003535 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003536 if (mRestrictPower) {
3537 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003538 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003539 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003540 }
Sudheer Shankad993dcf2018-02-11 12:22:16 -08003541 updateNetworkStats(uid, isUidStateForeground(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003542 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003543 } finally {
3544 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003545 }
3546 }
3547
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003548 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003549 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003550 final int index = mUidState.indexOfKey(uid);
3551 if (index >= 0) {
3552 final int oldUidState = mUidState.valueAt(index);
3553 mUidState.removeAt(index);
3554 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003555 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003556 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003557 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003558 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003559 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003560 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003561 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003562 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003563 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003564 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003565 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003566 }
3567 }
3568
Felipe Lemef28983d2016-03-25 12:18:23 -07003569 // adjust stats accounting based on foreground status
3570 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003571 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3572 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3573 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3574 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003575 try {
3576 mNetworkStats.setUidForeground(uid, uidForeground);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003577 } finally {
3578 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003579 }
3580 }
3581
Sudheer Shankac9d94072017-02-22 22:13:55 +00003582 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3583 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003584 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003585 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003586 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003587 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003588 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003589 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003590 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003591 }
3592
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003593 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003594 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003595 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3596 try {
3597 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3598 mUidFirewallPowerSaveRules);
3599 } finally {
3600 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3601 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003602 }
3603
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003604 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003605 void updateRuleForRestrictPowerUL(int uid) {
3606 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003607 }
3608
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003609 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003610 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003611 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3612 try {
3613 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3614 mUidFirewallDozableRules);
3615 } finally {
3616 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3617 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003618 }
3619
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003620 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003621 void updateRuleForDeviceIdleUL(int uid) {
3622 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003623 }
3624
Felipe Lemef28983d2016-03-25 12:18:23 -07003625 // NOTE: since both fw_dozable and fw_powersave uses the same map
3626 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003627 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003628 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003629 SparseIntArray rules) {
3630 if (enabled) {
3631 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003632 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003633 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003634 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003635 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003636 for (int ui = users.size() - 1; ui >= 0; ui--) {
3637 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003638 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3639 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3640 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3641 updateRulesForWhitelistedAppIds(uidRules,
3642 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003643 }
3644 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003645 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003646 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003647 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3648 }
3649 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003650 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003651 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003652 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003653 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003654 }
3655
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003656 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3657 final SparseBooleanArray whitelistedAppIds, int userId) {
3658 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3659 if (whitelistedAppIds.valueAt(i)) {
3660 final int appId = whitelistedAppIds.keyAt(i);
3661 final int uid = UserHandle.getUid(userId, appId);
3662 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3663 }
3664 }
3665 }
3666
3667 /**
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003668 * Returns whether a uid is whitelisted from power saving restrictions (eg: Battery Saver, Doze
3669 * mode, and app idle).
3670 *
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003671 * @param deviceIdleMode if true then we don't consider
3672 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3673 * whitelisted.
3674 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003675 @GuardedBy("mUidRulesFirstLock")
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003676 private boolean isWhitelistedFromPowerSaveUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003677 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003678 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3679 || mPowerSaveWhitelistAppIds.get(appId);
3680 if (!deviceIdleMode) {
3681 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3682 }
3683 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003684 }
3685
Felipe Lemef28983d2016-03-25 12:18:23 -07003686 // NOTE: since both fw_dozable and fw_powersave uses the same map
3687 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003688 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003689 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003690 if (enabled) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003691 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid,
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003692 chain == FIREWALL_CHAIN_DOZABLE);
3693 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003694 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003695 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003696 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003697 }
3698 }
3699 }
3700
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003701 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003702 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003703 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3704 try {
3705 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3706 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003707
Felipe Leme873a83a2016-09-07 11:34:10 -07003708 // Fully update the app idle firewall chain.
3709 final List<UserInfo> users = mUserManager.getUsers();
3710 for (int ui = users.size() - 1; ui >= 0; ui--) {
3711 UserInfo user = users.get(ui);
3712 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3713 for (int uid : idleUids) {
3714 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3715 // quick check: if this uid doesn't have INTERNET permission, it
3716 // doesn't have network access anyway, so it is a waste to mess
3717 // with it here.
3718 if (hasInternetPermissions(uid)) {
3719 uidRules.put(uid, FIREWALL_RULE_DENY);
3720 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003721 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003722 }
3723 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003724
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003725 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003726 } finally {
3727 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3728 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003729 }
3730
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003731 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003732 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003733 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003734
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003735 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3736 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3737 }
3738 try {
3739 int appId = UserHandle.getAppId(uid);
3740 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3741 && !isUidForegroundOnRestrictPowerUL(uid)) {
3742 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003743 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL DENY " + uid);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003744 } else {
3745 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003746 if (LOGD) Log.d(TAG, "updateRuleForAppIdleUL " + uid + " to DEFAULT");
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003747 }
3748 } finally {
3749 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003750 }
3751 }
3752
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003753 /**
3754 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3755 * changed.
3756 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003757 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003758 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003759 boolean paroled = mUsageStats.isAppIdleParoleOn();
3760 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003761 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003762
3763 int ruleCount = mUidFirewallStandbyRules.size();
3764 for (int i = 0; i < ruleCount; i++) {
3765 int uid = mUidFirewallStandbyRules.keyAt(i);
3766 int oldRules = mUidRules.get(uid);
3767 if (enableChain) {
3768 // Chain wasn't enabled before and the other power-related
3769 // chains are whitelists, so we can clear the
3770 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3771 // the effective rules result in blocking network access.
3772 oldRules &= MASK_METERED_NETWORKS;
3773 } else {
3774 // Skip if it had no restrictions to begin with
3775 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3776 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003777 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3778 if (newUidRules == RULE_NONE) {
3779 mUidRules.delete(uid);
3780 } else {
3781 mUidRules.put(uid, newUidRules);
3782 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003783 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003784 }
3785
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003786 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003787 * Update rules that might be changed by {@link #mRestrictBackground},
3788 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003789 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003790 @GuardedBy({"mUidRulesFirstLock", "mNetworkPoliciesSecondLock"})
Felipe Lemef0823852016-06-08 13:43:08 -07003791 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003792 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3793 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3794 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3795 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003796 try {
Felipe Leme09700462016-09-08 09:33:48 -07003797 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003798 updateRulesForRestrictPowerUL();
3799 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003800
Felipe Leme873a83a2016-09-07 11:34:10 -07003801 // If the set of restricted networks may have changed, re-evaluate those.
3802 if (restrictedNetworksChanged) {
3803 normalizePoliciesNL();
3804 updateNetworkRulesNL();
3805 }
3806 } finally {
3807 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003808 }
3809 }
3810
Felipe Leme09700462016-09-08 09:33:48 -07003811 // TODO: rename / document to make it clear these are global (not app-specific) rules
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003812 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003813 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003814 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3815 try {
3816 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003817 updateRulesForPowerSaveUL();
3818 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3819 } finally {
3820 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3821 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003822 }
3823
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003824 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003825 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003826 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3827 try {
3828 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3829 } finally {
3830 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3831 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003832 }
3833
3834 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3835 private static final int TYPE_RESTRICT_POWER = 2;
3836 @Retention(RetentionPolicy.SOURCE)
3837 @IntDef(flag = false, value = {
3838 TYPE_RESTRICT_BACKGROUND,
3839 TYPE_RESTRICT_POWER,
3840 })
3841 public @interface RestrictType {
3842 }
3843
3844 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003845 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07003846 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003847 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3848 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3849 }
3850 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003851 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003852
3853 final PackageManager pm = mContext.getPackageManager();
3854 final List<UserInfo> users;
3855 final List<ApplicationInfo> apps;
3856
3857 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3858 try {
3859 users = mUserManager.getUsers();
3860 } finally {
3861 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3862 }
3863 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3864 try {
3865 apps = pm.getInstalledApplications(
3866 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3867 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3868 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3869 } finally {
3870 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3871 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003872
Felipe Leme873a83a2016-09-07 11:34:10 -07003873 final int usersSize = users.size();
3874 final int appsSize = apps.size();
3875 for (int i = 0; i < usersSize; i++) {
3876 final UserInfo user = users.get(i);
3877 for (int j = 0; j < appsSize; j++) {
3878 final ApplicationInfo app = apps.get(j);
3879 final int uid = UserHandle.getUid(user.id, app.uid);
3880 switch (type) {
3881 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003882 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003883 break;
3884 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003885 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003886 break;
3887 default:
3888 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3889 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003890 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003891 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003892 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003893 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003894 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003895 }
3896
Andreas Gampeaae5aa32018-07-20 12:55:38 -07003897 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003898 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003899 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003900 final int numUsers = users.size();
3901 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003902 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003903 int uid = UserHandle.getUid(user.id, appId);
3904 // Update external firewall rules.
3905 updateRuleForAppIdleUL(uid);
3906 updateRuleForDeviceIdleUL(uid);
3907 updateRuleForRestrictPowerUL(uid);
3908 // Update internal rules.
3909 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003910 }
3911 }
3912
Felipe Leme70c57c22016-03-29 10:45:13 -07003913 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3914 // methods below could be merged into a isUidValidForRules() method.
3915 private boolean isUidValidForBlacklistRules(int uid) {
3916 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003917 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003918 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003919 return true;
3920 }
3921
3922 return false;
3923 }
3924
Felipe Leme70c57c22016-03-29 10:45:13 -07003925 private boolean isUidValidForWhitelistRules(int uid) {
3926 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3927 }
3928
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003929 /**
3930 * Set whether or not an app should be whitelisted for network access while in app idle. Other
3931 * power saving restrictions may still apply.
3932 */
3933 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003934 void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
Sudheer Shankadb02ccd2018-11-29 11:27:21 -08003935 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3936
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003937 synchronized (mUidRulesFirstLock) {
3938 if (mAppIdleTempWhitelistAppIds.get(uid) == shouldWhitelist) {
3939 // No change.
3940 return;
3941 }
3942
3943 final long token = Binder.clearCallingIdentity();
3944 try {
3945 mLogger.appIdleWlChanged(uid, shouldWhitelist);
3946 if (shouldWhitelist) {
3947 mAppIdleTempWhitelistAppIds.put(uid, true);
3948 } else {
3949 mAppIdleTempWhitelistAppIds.delete(uid);
3950 }
3951 updateRuleForAppIdleUL(uid);
3952 updateRulesForPowerRestrictionsUL(uid);
3953 } finally {
3954 Binder.restoreCallingIdentity(token);
3955 }
3956 }
3957 }
3958
3959 /** Return the list of UIDs currently in the app idle whitelist. */
3960 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003961 int[] getAppIdleWhitelist() {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003962 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3963
3964 synchronized (mUidRulesFirstLock) {
3965 final int len = mAppIdleTempWhitelistAppIds.size();
3966 int[] uids = new int[len];
3967 for (int i = 0; i < len; ++i) {
3968 uids[i] = mAppIdleTempWhitelistAppIds.keyAt(i);
3969 }
3970 return uids;
3971 }
3972 }
3973
3974 /** Returns if the UID is currently considered idle. */
3975 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08003976 boolean isUidIdle(int uid) {
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08003977 synchronized (mUidRulesFirstLock) {
3978 if (mAppIdleTempWhitelistAppIds.get(uid)) {
3979 // UID is temporarily whitelisted.
3980 return false;
3981 }
3982 }
3983
Amith Yamasani15e472352015-04-24 19:06:07 -07003984 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3985 final int userId = UserHandle.getUserId(uid);
3986
songjinshi0655edd2016-05-18 19:55:32 +08003987 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003988 for (String packageName : packages) {
3989 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3990 return false;
3991 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003992 }
3993 }
3994 return true;
3995 }
3996
3997 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003998 * Checks if an uid has INTERNET permissions.
3999 * <p>
4000 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07004001 */
Felipe Leme47585ba2016-02-09 16:56:32 -08004002 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004003 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08004004 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004005 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08004006 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004007 }
4008 } catch (RemoteException e) {
4009 }
Felipe Leme47585ba2016-02-09 16:56:32 -08004010 return true;
4011 }
4012
4013 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07004014 * Clears all state - internal and external - associated with an UID.
4015 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004016 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004017 private void onUidDeletedUL(int uid) {
4018 // First cleanup in-memory state synchronously...
4019 mUidRules.delete(uid);
4020 mUidPolicy.delete(uid);
4021 mUidFirewallStandbyRules.delete(uid);
4022 mUidFirewallDozableRules.delete(uid);
4023 mUidFirewallPowerSaveRules.delete(uid);
4024 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
4025 mPowerSaveWhitelistAppIds.delete(uid);
4026 mPowerSaveTempWhitelistAppIds.delete(uid);
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004027 mAppIdleTempWhitelistAppIds.delete(uid);
Felipe Leme03e95e22016-09-09 09:25:31 -07004028
4029 // ...then update iptables asynchronously.
4030 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
4031 }
4032
4033 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07004034 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07004035 *
Felipe Leme781ba142016-05-09 16:24:48 -07004036 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07004037 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004038 * <li>Doze mode
4039 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07004040 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07004041 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07004042 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07004043 *
4044 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08004045 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004046 @GuardedBy("mUidRulesFirstLock")
Felipe Leme03e95e22016-09-09 09:25:31 -07004047 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07004048 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07004049 updateRuleForDeviceIdleUL(uid);
4050 updateRuleForAppIdleUL(uid);
4051 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004052
4053 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004054 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004055
4056 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00004057 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07004058 }
4059
Felipe Leme70c57c22016-03-29 10:45:13 -07004060 /**
4061 * Applies network rules to bandwidth controllers based on process state and user-defined
4062 * restrictions (blacklist / whitelist).
4063 *
4064 * <p>
4065 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
4066 * networks:
4067 * <ul>
4068 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
4069 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
4070 * also blacklisted.
4071 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004072 * no UIDs other than those whitelisted will have access.
Felipe Leme70c57c22016-03-29 10:45:13 -07004073 * <ul>
4074 *
4075 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
4076 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
4077 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
4078 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07004079 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07004080 * {@link INetworkManagementService}, but this method should also be called in events (like
4081 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
4082 * following rules should also be applied:
4083 *
4084 * <ul>
4085 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
4086 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
4087 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
4088 * {@code bw_penalty_box}.
4089 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
4090 * </ul>
4091 *
4092 * <p>For optimization, the rules are only applied on user apps that have internet access
4093 * permission, since there is no need to change the {@code iptables} rule if the app does not
4094 * have permission to use the internet.
4095 *
4096 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07004097 *
Felipe Leme70c57c22016-03-29 10:45:13 -07004098 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004099 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004100 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4101 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4102 "updateRulesForDataUsageRestrictionsUL: " + uid);
4103 }
4104 try {
4105 updateRulesForDataUsageRestrictionsULInner(uid);
4106 } finally {
4107 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4108 }
4109 }
4110
4111 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07004112 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004113 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004114 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07004115 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004116
Dianne Hackborn497175b2014-07-01 12:56:08 -07004117 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004118 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07004119 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004120 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004121
Felipe Leme781ba142016-05-09 16:24:48 -07004122 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07004123 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07004124 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
4125 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07004126
Felipe Leme70c57c22016-03-29 10:45:13 -07004127 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004128 if (isRestrictedByAdmin) {
4129 newRule = RULE_REJECT_METERED;
4130 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07004131 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
4132 newRule = RULE_TEMPORARY_ALLOW_METERED;
4133 } else if (isWhitelisted) {
4134 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004135 }
4136 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004137 if (isBlacklisted) {
4138 newRule = RULE_REJECT_METERED;
4139 } else if (mRestrictBackground && isWhitelisted) {
4140 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004141 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004142 }
Felipe Leme781ba142016-05-09 16:24:48 -07004143 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07004144
Felipe Lemef28983d2016-03-25 12:18:23 -07004145 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07004146 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004147 + ": isForeground=" +isForeground
4148 + ", isBlacklisted=" + isBlacklisted
4149 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004150 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07004151 + ", oldRule=" + uidRulesToString(oldRule)
4152 + ", newRule=" + uidRulesToString(newRule)
4153 + ", newUidRules=" + uidRulesToString(newUidRules)
4154 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07004155 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004156
Felipe Leme46c4fc32016-05-04 09:21:43 -07004157 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07004158 mUidRules.delete(uid);
4159 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07004160 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07004161 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07004162
Felipe Leme70c57c22016-03-29 10:45:13 -07004163 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07004164 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004165 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004166 // Temporarily whitelist foreground app, removing from blacklist if necessary
4167 // (since bw_penalty_box prevails over bw_happy_box).
4168
4169 setMeteredNetworkWhitelist(uid, true);
4170 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
4171 // but ideally it should be just:
4172 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004173 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004174 setMeteredNetworkBlacklist(uid, false);
4175 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004176 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004177 // Remove temporary whitelist from app that is not on foreground anymore.
4178
4179 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
4180 // but ideally they should be just:
4181 // setMeteredNetworkWhitelist(uid, isWhitelisted);
4182 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07004183 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004184 setMeteredNetworkWhitelist(uid, false);
4185 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004186 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004187 setMeteredNetworkBlacklist(uid, true);
4188 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004189 } else if (hasRule(newRule, RULE_REJECT_METERED)
4190 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004191 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004192 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09004193 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004194 // Since blacklist prevails over whitelist, we need to handle the special case
4195 // where app is whitelisted and blacklisted at the same time (although such
4196 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07004197 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004198 }
Hugo Benichi2966c182017-03-28 17:17:13 +09004199 } else if (hasRule(newRule, RULE_ALLOW_METERED)
4200 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004201 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07004202 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07004203 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07004204 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07004205 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
4206 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004207 + ", whitelisted=" + isWhitelisted
4208 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004209 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07004210 + ", newRule=" + uidRulesToString(newUidRules)
4211 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07004212 }
Felipe Leme781ba142016-05-09 16:24:48 -07004213
Sudheer Shankac9d94072017-02-22 22:13:55 +00004214 // Dispatch changed rule to existing listeners.
4215 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07004216 }
4217 }
4218
4219 /**
4220 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
4221 * listeners in case of change.
4222 * <p>
4223 * There are 3 power-related rules that affects whether an app has background access on
4224 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
4225 * restriction, it's added to the equivalent firewall chain:
4226 * <ul>
4227 * <li>App is idle: {@code fw_standby} firewall chain.
4228 * <li>Device is idle: {@code fw_dozable} firewall chain.
4229 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
4230 * </ul>
4231 * <p>
4232 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
4233 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
4234 * <p>
4235 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
4236 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004237 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankac9d94072017-02-22 22:13:55 +00004238 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004239 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
4240
Sudheer Shankac9d94072017-02-22 22:13:55 +00004241 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004242
Sudheer Shankac9d94072017-02-22 22:13:55 +00004243 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004244 mUidRules.delete(uid);
4245 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00004246 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004247 }
4248 }
4249
4250 /**
4251 * Similar to above but ignores idle state if app standby is currently disabled by parole.
4252 *
4253 * @param uid the uid of the app to update rules for
4254 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
4255 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
4256 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00004257 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004258 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00004259 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004260 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4261 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4262 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
4263 + (paroled ? "P" : "-"));
4264 }
4265 try {
4266 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
4267 } finally {
4268 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4269 }
4270 }
4271
4272 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07004273 if (!isUidValidForBlacklistRules(uid)) {
4274 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004275 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07004276 }
Felipe Lemef28983d2016-03-25 12:18:23 -07004277
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004278 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004279 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07004280 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07004281
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08004282 final boolean isWhitelisted = isWhitelistedFromPowerSaveUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07004283 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
4284 int newRule = RULE_NONE;
4285
4286 // First step: define the new rule based on user restrictions and foreground state.
4287
4288 // NOTE: if statements below could be inlined, but it's easier to understand the logic
4289 // by considering the foreground and non-foreground states.
4290 if (isForeground) {
4291 if (restrictMode) {
4292 newRule = RULE_ALLOW_ALL;
4293 }
4294 } else if (restrictMode) {
4295 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
4296 }
4297
4298 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
4299
4300 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07004301 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07004302 + ", isIdle: " + isIdle
4303 + ", mRestrictPower: " + mRestrictPower
4304 + ", mDeviceIdleMode: " + mDeviceIdleMode
4305 + ", isForeground=" + isForeground
4306 + ", isWhitelisted=" + isWhitelisted
4307 + ", oldRule=" + uidRulesToString(oldRule)
4308 + ", newRule=" + uidRulesToString(newRule)
4309 + ", newUidRules=" + uidRulesToString(newUidRules)
4310 + ", oldUidRules=" + uidRulesToString(oldUidRules));
4311 }
4312
Felipe Leme781ba142016-05-09 16:24:48 -07004313 // Second step: notify listeners if state changed.
4314 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09004315 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004316 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09004317 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07004318 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
4319 } else {
4320 // All scenarios should have been covered above
4321 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
4322 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07004323 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07004324 + ", newRule=" + uidRulesToString(newUidRules)
4325 + ", oldRule=" + uidRulesToString(oldUidRules));
4326 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004327 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07004328 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07004329
Sudheer Shankac9d94072017-02-22 22:13:55 +00004330 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004331 }
4332
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004333 private class AppIdleStateChangeListener
4334 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4335
4336 @Override
Amith Yamasani119be9a2018-02-18 22:23:00 -08004337 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket,
4338 int reason) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004339 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07004340 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
4341 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07004342 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004343 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07004344 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00004345 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004346 }
4347 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004348 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004349 }
4350
4351 @Override
4352 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07004353 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004354 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07004355 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004356 }
Amith Yamasani15e472352015-04-24 19:06:07 -07004357 }
4358 }
4359
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004360 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
4361 if (listener != null) {
4362 try {
4363 listener.onUidRulesChanged(uid, uidRules);
4364 } catch (RemoteException ignored) {
4365 }
4366 }
4367 }
4368
4369 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
4370 String[] meteredIfaces) {
4371 if (listener != null) {
4372 try {
4373 listener.onMeteredIfacesChanged(meteredIfaces);
4374 } catch (RemoteException ignored) {
4375 }
4376 }
4377 }
4378
4379 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
4380 boolean restrictBackground) {
4381 if (listener != null) {
4382 try {
4383 listener.onRestrictBackgroundChanged(restrictBackground);
4384 } catch (RemoteException ignored) {
4385 }
4386 }
4387 }
4388
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004389 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
4390 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004391 if (listener != null) {
4392 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004393 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004394 } catch (RemoteException ignored) {
4395 }
4396 }
4397 }
4398
Jeff Sharkey9252b342018-01-19 07:58:35 +09004399 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4400 int overrideMask, int overrideValue) {
4401 if (listener != null) {
4402 try {
4403 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4404 } catch (RemoteException ignored) {
4405 }
4406 }
4407 }
4408
Makoto Onuki8e777332017-03-28 11:25:47 -07004409 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004410 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004411 public boolean handleMessage(Message msg) {
4412 switch (msg.what) {
4413 case MSG_RULES_CHANGED: {
4414 final int uid = msg.arg1;
4415 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004416 final int length = mListeners.beginBroadcast();
4417 for (int i = 0; i < length; i++) {
4418 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4419 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004420 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004421 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004422 return true;
4423 }
4424 case MSG_METERED_IFACES_CHANGED: {
4425 final String[] meteredIfaces = (String[]) msg.obj;
4426 final int length = mListeners.beginBroadcast();
4427 for (int i = 0; i < length; i++) {
4428 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004429 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004430 }
4431 mListeners.finishBroadcast();
4432 return true;
4433 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004434 case MSG_LIMIT_REACHED: {
4435 final String iface = (String) msg.obj;
4436
Felipe Lemef0823852016-06-08 13:43:08 -07004437 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004438 if (mMeteredIfaces.contains(iface)) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004439 // force stats update to make sure we have
4440 // numbers that caused alert to trigger.
4441 mNetworkStats.forceUpdate();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004442
Felipe Lemef0823852016-06-08 13:43:08 -07004443 updateNetworkEnabledNL();
4444 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004445 }
4446 }
4447 return true;
4448 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004449 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4450 final boolean restrictBackground = msg.arg1 != 0;
4451 final int length = mListeners.beginBroadcast();
4452 for (int i = 0; i < length; i++) {
4453 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004454 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004455 }
4456 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004457 final Intent intent =
4458 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4459 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4460 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4461 return true;
4462 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004463 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004464 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004465 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004466 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004467 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004468 final int length = mListeners.beginBroadcast();
4469 for (int i = 0; i < length; i++) {
4470 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004471 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004472 }
4473 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004474 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4475 if (notifyApp.booleanValue()) {
4476 broadcastRestrictBackgroundChanged(uid, notifyApp);
4477 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004478 return true;
4479 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004480 case MSG_ADVISE_PERSIST_THRESHOLD: {
4481 final long lowestRule = (Long) msg.obj;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004482 // make sure stats are recorded frequently enough; we aim
4483 // for 2MB threshold for 2GB/month rules.
4484 final long persistThreshold = lowestRule / 1000;
4485 mNetworkStats.advisePersistThreshold(persistThreshold);
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004486 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004487 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004488 case MSG_UPDATE_INTERFACE_QUOTA: {
4489 removeInterfaceQuota((String) msg.obj);
4490 // int params need to be stitched back into a long
4491 setInterfaceQuota((String) msg.obj,
4492 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4493 return true;
4494 }
4495 case MSG_REMOVE_INTERFACE_QUOTA: {
4496 removeInterfaceQuota((String) msg.obj);
4497 return true;
4498 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004499 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4500 resetUidFirewallRules(msg.arg1);
4501 return true;
4502 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004503 case MSG_SUBSCRIPTION_OVERRIDE: {
4504 final int overrideMask = msg.arg1;
4505 final int overrideValue = msg.arg2;
4506 final int subId = (int) msg.obj;
4507 final int length = mListeners.beginBroadcast();
4508 for (int i = 0; i < length; i++) {
4509 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4510 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4511 }
4512 mListeners.finishBroadcast();
4513 return true;
4514 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004515 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4516 final int userId = msg.arg1;
4517 final Set<String> packageNames = (Set<String>) msg.obj;
4518 setMeteredRestrictedPackagesInternal(packageNames, userId);
4519 return true;
4520 }
Makoto Onuki3f1bf5f2018-04-04 15:29:00 -07004521 case MSG_SET_NETWORK_TEMPLATE_ENABLED: {
4522 final NetworkTemplate template = (NetworkTemplate) msg.obj;
4523 final boolean enabled = msg.arg1 != 0;
4524 setNetworkTemplateEnabledInner(template, enabled);
4525 return true;
4526 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004527 default: {
4528 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004529 }
4530 }
4531 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004532 };
4533
4534 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4535 @Override
4536 public boolean handleMessage(Message msg) {
4537 switch (msg.what) {
4538 case UID_MSG_STATE_CHANGED: {
4539 final int uid = msg.arg1;
4540 final int procState = msg.arg2;
4541 final long procStateSeq = (Long) msg.obj;
4542
4543 handleUidChanged(uid, procState, procStateSeq);
4544 return true;
4545 }
4546 case UID_MSG_GONE: {
4547 final int uid = msg.arg1;
4548 handleUidGone(uid);
4549 return true;
4550 }
4551 default: {
4552 return false;
4553 }
4554 }
4555 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004556
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004557 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004558
Makoto Onuki8e777332017-03-28 11:25:47 -07004559 void handleUidChanged(int uid, int procState, long procStateSeq) {
4560 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4561 try {
4562 synchronized (mUidRulesFirstLock) {
4563 // We received a uid state change callback, add it to the history so that it
4564 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004565 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004566 // Now update the network policy rules as per the updated uid state.
4567 updateUidStateUL(uid, procState);
4568 // Updating the network rules is done, so notify AMS about this.
4569 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4570 }
4571 } finally {
4572 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4573 }
4574 }
4575
4576 void handleUidGone(int uid) {
4577 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4578 try {
4579 synchronized (mUidRulesFirstLock) {
4580 removeUidStateUL(uid);
4581 }
4582 } finally {
4583 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4584 }
4585 }
4586
Felipe Leme57e3d312016-08-23 14:42:52 -07004587 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4588 final PackageManager pm = mContext.getPackageManager();
4589 final String[] packages = pm.getPackagesForUid(uid);
4590 if (packages != null) {
4591 final int userId = UserHandle.getUserId(uid);
4592 for (String packageName : packages) {
4593 final Intent intent =
4594 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4595 intent.setPackage(packageName);
4596 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4597 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4598 }
4599 }
4600 }
4601
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004602 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4603 // long quotaBytes split up into two ints to fit in message
4604 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4605 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4606 }
4607
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004608 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004609 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004610 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004611 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004612 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004613 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004614 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004615 }
4616 }
4617
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004618 private void removeInterfaceQuotaAsync(String iface) {
4619 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4620 }
4621
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004622 private void removeInterfaceQuota(String iface) {
4623 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004624 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004625 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004626 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004627 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004628 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004629 }
4630 }
4631
Felipe Leme70c57c22016-03-29 10:45:13 -07004632 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4633 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004634 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004635 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004636 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004637 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4638 } catch (RemoteException e) {
4639 // ignored; service lives in system_server
4640 }
4641 }
4642
4643 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4644 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4645 try {
4646 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4647 } catch (IllegalStateException e) {
4648 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004649 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004650 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004651 }
4652 }
4653
Felipe Lemebc853dd2016-09-08 13:26:55 -07004654 private static final int CHAIN_TOGGLE_NONE = 0;
4655 private static final int CHAIN_TOGGLE_ENABLE = 1;
4656 private static final int CHAIN_TOGGLE_DISABLE = 2;
4657 @Retention(RetentionPolicy.SOURCE)
4658 @IntDef(flag = false, value = {
4659 CHAIN_TOGGLE_NONE,
4660 CHAIN_TOGGLE_ENABLE,
4661 CHAIN_TOGGLE_DISABLE
4662 })
4663 public @interface ChainToggleType {
4664 }
4665
4666 /**
4667 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004668 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004669 *
4670 * @param chain firewall chain.
4671 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4672 * @param toggle whether the chain should be enabled, disabled, or not changed.
4673 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004674 @GuardedBy("mUidRulesFirstLock")
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004675 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004676 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004677 if (uidRules != null) {
4678 setUidFirewallRulesUL(chain, uidRules);
4679 }
4680 if (toggle != CHAIN_TOGGLE_NONE) {
4681 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4682 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004683 }
4684
Amith Yamasani15e472352015-04-24 19:06:07 -07004685 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004686 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4687 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4688 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004689 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004690 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004691 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004692 int size = uidRules.size();
4693 int[] uids = new int[size];
4694 int[] rules = new int[size];
4695 for(int index = size - 1; index >= 0; --index) {
4696 uids[index] = uidRules.keyAt(index);
4697 rules[index] = uidRules.valueAt(index);
4698 }
4699 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004700 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004701 } catch (IllegalStateException e) {
4702 Log.wtf(TAG, "problem setting firewall uid rules", e);
4703 } catch (RemoteException e) {
4704 // ignored; service lives in system_server
4705 }
4706 }
4707
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004708 /**
4709 * Add or remove a uid to the firewall blacklist for all network ifaces.
4710 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004711 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004712 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4713 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4714 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004715 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004716 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004717 if (chain == FIREWALL_CHAIN_DOZABLE) {
4718 mUidFirewallDozableRules.put(uid, rule);
4719 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4720 mUidFirewallStandbyRules.put(uid, rule);
4721 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4722 mUidFirewallPowerSaveRules.put(uid, rule);
4723 }
4724
4725 try {
4726 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004727 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004728 } catch (IllegalStateException e) {
4729 Log.wtf(TAG, "problem setting firewall uid rules", e);
4730 } catch (RemoteException e) {
4731 // ignored; service lives in system_server
4732 }
4733 } finally {
4734 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004735 }
4736 }
4737
4738 /**
4739 * Add or remove a uid to the firewall blacklist for all network ifaces.
4740 */
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004741 @GuardedBy("mUidRulesFirstLock")
Felipe Lemef0823852016-06-08 13:43:08 -07004742 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004743 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4744 mFirewallChainStates.get(chain) == enable) {
4745 // All is the same, nothing to do.
4746 return;
4747 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004748 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004749 try {
4750 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004751 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004752 } catch (IllegalStateException e) {
4753 Log.wtf(TAG, "problem enable firewall chain", e);
4754 } catch (RemoteException e) {
4755 // ignored; service lives in system_server
4756 }
4757 }
4758
Felipe Leme03e95e22016-09-09 09:25:31 -07004759 /**
4760 * Resets all firewall rules associated with an UID.
4761 */
4762 private void resetUidFirewallRules(int uid) {
4763 try {
4764 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4765 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4766 mNetworkManager
4767 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4768 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4769 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4770 } catch (IllegalStateException e) {
4771 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4772 } catch (RemoteException e) {
4773 // ignored; service lives in system_server
4774 }
4775 }
4776
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004777 @Deprecated
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004778 private long getTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004779 return getNetworkTotalBytes(template, start, end);
4780 }
4781
4782 private long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004783 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004784 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004785 } catch (RuntimeException e) {
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004786 Slog.w(TAG, "Failed to read network stats: " + e);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004787 return 0;
Jeff Sharkeye0c29952018-02-20 17:24:55 -07004788 }
4789 }
4790
4791 private NetworkStats getNetworkUidBytes(NetworkTemplate template, long start, long end) {
4792 try {
4793 return mNetworkStats.getNetworkUidBytes(template, start, end);
4794 } catch (RuntimeException e) {
4795 Slog.w(TAG, "Failed to read network stats: " + e);
4796 return new NetworkStats(SystemClock.elapsedRealtime(), 0);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004797 }
4798 }
4799
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004800 private boolean isBandwidthControlEnabled() {
4801 final long token = Binder.clearCallingIdentity();
4802 try {
4803 return mNetworkManager.isBandwidthControlEnabled();
4804 } catch (RemoteException e) {
4805 // ignored; service lives in system_server
4806 return false;
4807 } finally {
4808 Binder.restoreCallingIdentity(token);
4809 }
4810 }
4811
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004812 private static Intent buildAllowBackgroundDataIntent() {
4813 return new Intent(ACTION_ALLOW_BACKGROUND);
4814 }
4815
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004816 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4817 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004818 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4819 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4820 return intent;
4821 }
4822
4823 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4824 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4825 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004826 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4827 return intent;
4828 }
4829
Wei Liu546cb772016-07-21 16:19:01 -07004830 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004831 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004832 intent.setComponent(ComponentName.unflattenFromString(
4833 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004834 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4835 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4836 return intent;
4837 }
4838
Wei Liu546cb772016-07-21 16:19:01 -07004839 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004840 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004841 intent.setComponent(ComponentName.unflattenFromString(
4842 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004843 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4844 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4845 return intent;
4846 }
4847
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004848 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004849 void addIdleHandler(IdleHandler handler) {
Jeff Sharkey163e6442011-10-31 16:37:52 -07004850 mHandler.getLooper().getQueue().addIdleHandler(handler);
4851 }
4852
Andreas Gampeaae5aa32018-07-20 12:55:38 -07004853 @GuardedBy("mUidRulesFirstLock")
jackqdyulei29c82ab2017-03-10 14:09:16 -08004854 @VisibleForTesting
Sudheer Shanka8ab22992018-11-29 00:08:58 -08004855 void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
jackqdyulei29c82ab2017-03-10 14:09:16 -08004856 mRestrictBackgroundPowerState = result;
4857
4858 boolean restrictBackground = result.batterySaverEnabled;
4859 boolean shouldInvokeRestrictBackground;
4860 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4861 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4862
4863 if (result.globalBatterySaverEnabled) {
4864 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4865 // turn it on.
4866 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4867 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4868 localRestrictBgChangedInBsm = false;
4869 } else {
4870 // Try to restore the restrictBackground if it doesn't change in bsm
4871 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4872 restrictBackground = mRestrictBackgroundBeforeBsm;
4873 }
4874
4875 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004876 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004877 }
4878
4879 // Change it at last so setRestrictBackground() won't affect this variable
4880 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4881 }
4882
Jeff Sharkey1b861272011-05-22 00:34:52 -07004883 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4884 final int size = source.size();
4885 for (int i = 0; i < size; i++) {
4886 target.put(source.keyAt(i), true);
4887 }
4888 }
4889
Stuart Scottf1fb3972015-04-02 18:00:02 -07004890 @Override
4891 public void factoryReset(String subscriber) {
4892 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4893
Stuart Scotte3e314d2015-04-20 14:07:45 -07004894 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4895 return;
4896 }
4897
Stuart Scottf1fb3972015-04-02 18:00:02 -07004898 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004899 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004900 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4901 for (NetworkPolicy policy : policies) {
4902 if (policy.template.equals(template)) {
4903 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4904 policy.inferred = false;
4905 policy.clearSnooze();
4906 }
4907 }
4908 setNetworkPolicies(policies);
4909
4910 // Turn restrict background data off
4911 setRestrictBackground(false);
4912
Stuart Scotte3e314d2015-04-20 14:07:45 -07004913 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4914 // Remove app's "restrict background data" flag
4915 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4916 setUidPolicy(uid, POLICY_NONE);
4917 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004918 }
4919 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004920
Sudheer Shankab8f23162017-08-04 13:30:10 -07004921 @Override
4922 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
Makoto Onuki49392d32018-04-11 13:51:02 -07004923 final long startTime = mStatLogger.getTime();
4924
Sudheer Shankab8f23162017-08-04 13:30:10 -07004925 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004926 final int uidRules;
4927 final boolean isBackgroundRestricted;
4928 synchronized (mUidRulesFirstLock) {
4929 uidRules = mUidRules.get(uid, RULE_NONE);
4930 isBackgroundRestricted = mRestrictBackground;
4931 }
junyulai05986c62018-08-07 19:50:45 +08004932 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
4933 isBackgroundRestricted, mLogger);
4934
4935 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
4936
4937 return ret;
4938 }
4939
4940 private static boolean isSystem(int uid) {
4941 return uid < Process.FIRST_APPLICATION_UID;
4942 }
4943
4944 static boolean isUidNetworkingBlockedInternal(int uid, int uidRules, boolean isNetworkMetered,
4945 boolean isBackgroundRestricted, @Nullable NetworkPolicyLogger logger) {
4946 final int reason;
4947 // Networks are never blocked for system components
4948 if (isSystem(uid)) {
4949 reason = NTWK_ALLOWED_SYSTEM;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004950 }
junyulai05986c62018-08-07 19:50:45 +08004951 else if (hasRule(uidRules, RULE_REJECT_ALL)) {
4952 reason = NTWK_BLOCKED_POWER;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004953 }
junyulai05986c62018-08-07 19:50:45 +08004954 else if (!isNetworkMetered) {
4955 reason = NTWK_ALLOWED_NON_METERED;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004956 }
junyulai05986c62018-08-07 19:50:45 +08004957 else if (hasRule(uidRules, RULE_REJECT_METERED)) {
4958 reason = NTWK_BLOCKED_BLACKLIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004959 }
junyulai05986c62018-08-07 19:50:45 +08004960 else if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4961 reason = NTWK_ALLOWED_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004962 }
junyulai05986c62018-08-07 19:50:45 +08004963 else if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4964 reason = NTWK_ALLOWED_TMP_WHITELIST;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004965 }
junyulai05986c62018-08-07 19:50:45 +08004966 else if (isBackgroundRestricted) {
4967 reason = NTWK_BLOCKED_BG_RESTRICT;
4968 }
4969 else {
4970 reason = NTWK_ALLOWED_DEFAULT;
4971 }
4972
4973 final boolean blocked;
4974 switch(reason) {
4975 case NTWK_ALLOWED_DEFAULT:
4976 case NTWK_ALLOWED_NON_METERED:
4977 case NTWK_ALLOWED_TMP_WHITELIST:
4978 case NTWK_ALLOWED_WHITELIST:
4979 case NTWK_ALLOWED_SYSTEM:
4980 blocked = false;
4981 break;
4982 case NTWK_BLOCKED_POWER:
4983 case NTWK_BLOCKED_BLACKLIST:
4984 case NTWK_BLOCKED_BG_RESTRICT:
4985 blocked = true;
4986 break;
4987 default:
4988 throw new IllegalArgumentException();
4989 }
4990 if (logger != null) {
4991 logger.networkBlocked(uid, reason);
4992 }
4993
4994 return blocked;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004995 }
4996
Felipe Lemed17fda42016-04-29 11:12:45 -07004997 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4998
4999 @Override
5000 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07005001 synchronized (mUidRulesFirstLock) {
5002 boolean changed = removeUserStateUL(userId, false);
5003 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07005004 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07005005 synchronized (mNetworkPoliciesSecondLock) {
5006 writePolicyAL();
5007 }
Felipe Lemed17fda42016-04-29 11:12:45 -07005008 }
5009 }
5010 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005011
5012 /**
5013 * @return true if the given uid is restricted from doing networking on metered networks.
5014 */
5015 @Override
5016 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
5017 final int uidRules;
5018 final boolean isBackgroundRestricted;
5019 synchronized (mUidRulesFirstLock) {
5020 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
5021 isBackgroundRestricted = mRestrictBackground;
5022 }
5023 return isBackgroundRestricted
5024 && !hasRule(uidRules, RULE_ALLOW_METERED)
5025 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
5026 }
5027
5028 /**
5029 * @return true if networking is blocked on the given interface for the given uid according
5030 * to current networking policies.
5031 */
5032 @Override
5033 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Makoto Onuki49392d32018-04-11 13:51:02 -07005034 final long startTime = mStatLogger.getTime();
5035
junyulai05986c62018-08-07 19:50:45 +08005036 final int uidRules;
5037 final boolean isBackgroundRestricted;
5038 synchronized (mUidRulesFirstLock) {
5039 uidRules = mUidRules.get(uid, RULE_NONE);
5040 isBackgroundRestricted = mRestrictBackground;
5041 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005042 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07005043 synchronized (mNetworkPoliciesSecondLock) {
5044 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005045 }
junyulai05986c62018-08-07 19:50:45 +08005046 final boolean ret = isUidNetworkingBlockedInternal(uid, uidRules, isNetworkMetered,
5047 isBackgroundRestricted, mLogger);
Makoto Onuki49392d32018-04-11 13:51:02 -07005048
5049 mStatLogger.logDurationStat(Stats.IS_UID_NETWORKING_BLOCKED, startTime);
5050
5051 return ret;
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005052 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005053
5054 @Override
5055 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
5056 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07005057 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07005058 if (added) {
5059 mPowerSaveTempWhitelistAppIds.put(appId, true);
5060 } else {
5061 mPowerSaveTempWhitelistAppIds.delete(appId);
5062 }
5063 updateRulesForTempWhitelistChangeUL(appId);
5064 }
5065 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005066
5067 @Override
5068 public SubscriptionPlan getSubscriptionPlan(Network network) {
5069 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09005070 final int subId = getSubIdLocked(network);
5071 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005072 }
5073 }
5074
5075 @Override
Jeff Sharkey146bb332018-04-18 15:42:57 -06005076 public SubscriptionPlan getSubscriptionPlan(NetworkTemplate template) {
5077 synchronized (mNetworkPoliciesSecondLock) {
5078 final int subId = findRelevantSubIdNL(template);
5079 return getPrimarySubscriptionPlanLocked(subId);
5080 }
5081 }
5082
5083 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09005084 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005085 final long quotaBytes;
Jeff Sharkey9252b342018-01-19 07:58:35 +09005086 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005087 quotaBytes = mSubscriptionOpportunisticQuota.get(getSubIdLocked(network),
Remi NGUYEN VAN5a89f942018-03-30 21:17:42 +09005088 OPPORTUNISTIC_QUOTA_UNKNOWN);
Jeff Sharkey9252b342018-01-19 07:58:35 +09005089 }
Jeff Sharkey36b414b2018-03-30 11:00:03 -06005090 if (quotaBytes == OPPORTUNISTIC_QUOTA_UNKNOWN) {
5091 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5092 }
5093
5094 if (quotaType == QUOTA_TYPE_JOBS) {
5095 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5096 NETPOLICY_QUOTA_FRAC_JOBS, QUOTA_FRAC_JOBS_DEFAULT));
5097 } else if (quotaType == QUOTA_TYPE_MULTIPATH) {
5098 return (long) (quotaBytes * Settings.Global.getFloat(mContext.getContentResolver(),
5099 NETPOLICY_QUOTA_FRAC_MULTIPATH, QUOTA_FRAC_MULTIPATH_DEFAULT));
5100 } else {
5101 return OPPORTUNISTIC_QUOTA_UNKNOWN;
5102 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005103 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005104
5105 @Override
5106 public void onAdminDataAvailable() {
5107 mAdminDataAvailableLatch.countDown();
5108 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005109
5110 @Override
Kweku Adamsa9e55bc2018-11-19 14:59:15 -08005111 public void setAppIdleWhitelist(int uid, boolean shouldWhitelist) {
5112 NetworkPolicyManagerService.this.setAppIdleWhitelist(uid, shouldWhitelist);
5113 }
5114
5115 @Override
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005116 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
5117 setMeteredRestrictedPackagesInternal(packageNames, userId);
5118 }
5119
5120 @Override
5121 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
5122 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
5123 userId, 0, packageNames).sendToTarget();
5124 }
5125 }
5126
5127 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
5128 synchronized (mUidRulesFirstLock) {
5129 final Set<Integer> newRestrictedUids = new ArraySet<>();
5130 for (String packageName : packageNames) {
5131 final int uid = getUidForPackage(packageName, userId);
5132 if (uid >= 0) {
5133 newRestrictedUids.add(uid);
5134 }
5135 }
5136 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
5137 mMeteredRestrictedUids.put(userId, newRestrictedUids);
5138 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
5139 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
5140 }
5141 }
5142
5143 private int getUidForPackage(String packageName, int userId) {
5144 try {
5145 return mContext.getPackageManager().getPackageUidAsUser(packageName,
5146 PackageManager.MATCH_KNOWN_PACKAGES, userId);
5147 } catch (NameNotFoundException e) {
5148 return -1;
5149 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09005150 }
5151
5152 private int parseSubId(NetworkState state) {
5153 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
5154 int subId = INVALID_SUBSCRIPTION_ID;
5155 if (state != null && state.networkCapabilities != null
5156 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
5157 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
5158 if (spec instanceof StringNetworkSpecifier) {
5159 try {
5160 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
5161 } catch (NumberFormatException e) {
5162 }
5163 }
5164 }
5165 return subId;
5166 }
5167
Andreas Gampea36dc622018-02-05 17:19:22 -08005168 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09005169 private int getSubIdLocked(Network network) {
5170 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005171 }
5172
Andreas Gampea36dc622018-02-05 17:19:22 -08005173 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09005174 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
5175 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005176 if (!ArrayUtils.isEmpty(plans)) {
5177 for (SubscriptionPlan plan : plans) {
5178 if (plan.getCycleRule().isRecurring()) {
5179 // Recurring plans will always have an active cycle
5180 return plan;
5181 } else {
5182 // Non-recurring plans need manual test for active cycle
5183 final Range<ZonedDateTime> cycle = plan.cycleIterator().next();
5184 if (cycle.contains(ZonedDateTime.now(mClock))) {
5185 return plan;
5186 }
5187 }
5188 }
5189 }
5190 return null;
Jeff Sharkey2e471452018-01-19 18:02:47 +09005191 }
5192
Sudheer Shankac53c47f2018-01-16 12:01:00 -08005193 /**
5194 * This will only ever be called once - during device boot.
5195 */
5196 private void waitForAdminData() {
5197 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
5198 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
5199 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
5200 }
5201 }
5202
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005203 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
5204 Set<Integer> newRestrictedUids) {
Sudheer Shanka1536fb62018-07-05 11:52:36 -07005205 if (!mNetworkManagerReady) {
5206 return;
5207 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005208 if (oldRestrictedUids == null) {
5209 for (int uid : newRestrictedUids) {
5210 updateRulesForDataUsageRestrictionsUL(uid);
5211 }
5212 return;
5213 }
5214 for (int uid : oldRestrictedUids) {
5215 if (!newRestrictedUids.contains(uid)) {
5216 updateRulesForDataUsageRestrictionsUL(uid);
5217 }
5218 }
5219 for (int uid : newRestrictedUids) {
5220 if (!oldRestrictedUids.contains(uid)) {
5221 updateRulesForDataUsageRestrictionsUL(uid);
5222 }
5223 }
5224 }
5225
Andreas Gampeaae5aa32018-07-20 12:55:38 -07005226 @GuardedBy("mUidRulesFirstLock")
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08005227 private boolean isRestrictedByAdminUL(int uid) {
5228 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
5229 UserHandle.getUserId(uid));
5230 return restrictedUids != null && restrictedUids.contains(uid);
5231 }
5232
Hugo Benichi938ab4f2017-02-11 17:04:43 +09005233 private static boolean hasRule(int uidRules, int rule) {
5234 return (uidRules & rule) != 0;
5235 }
5236
Jeff Sharkey2e471452018-01-19 18:02:47 +09005237 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
5238 return (val != null) ? val : new NetworkState[0];
5239 }
5240
Jeff Sharkey0a5570d2018-04-10 12:38:29 -06005241 private static boolean getBooleanDefeatingNullable(@Nullable PersistableBundle bundle,
5242 String key, boolean defaultValue) {
5243 return (bundle != null) ? bundle.getBoolean(key, defaultValue) : defaultValue;
5244 }
5245
Chris Wren193ae6b2017-03-31 15:17:11 -04005246 private class NotificationId {
5247 private final String mTag;
5248 private final int mId;
5249
5250 NotificationId(NetworkPolicy policy, int type) {
5251 mTag = buildNotificationTag(policy, type);
5252 mId = type;
5253 }
5254
5255 @Override
5256 public boolean equals(Object o) {
5257 if (this == o) return true;
5258 if (!(o instanceof NotificationId)) return false;
5259 NotificationId that = (NotificationId) o;
5260 return Objects.equals(mTag, that.mTag);
5261 }
5262
5263 @Override
5264 public int hashCode() {
5265 return Objects.hash(mTag);
5266 }
5267
5268 /**
5269 * Build unique tag that identifies an active {@link NetworkPolicy}
5270 * notification of a specific type, like {@link #TYPE_LIMIT}.
5271 */
5272 private String buildNotificationTag(NetworkPolicy policy, int type) {
5273 return TAG + ":" + policy.template.hashCode() + ":" + type;
5274 }
5275
5276 public String getTag() {
5277 return mTag;
5278 }
5279
5280 public int getId() {
5281 return mId;
5282 }
5283 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07005284}