blob: e2b2d46eb4a6b4d3990a5e6552c2b3763bca31cb [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;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey64c96ec2017-08-30 16:28:26 -060036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey9252b342018-01-19 07:58:35 +090037import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070038import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070039import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070040import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070041import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
45import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060048import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
49import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070050import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070051import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070052import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070054import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070055import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080059import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
60import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060061import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070062import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070063import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070064import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
65import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070066import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
67import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070068import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080069import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070070import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070071import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060072import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey9252b342018-01-19 07:58:35 +090073import static android.telephony.SubscriptionManager.INVALID_SUBSCRIPTION_ID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060081import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070082import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
83import static com.android.internal.util.XmlUtils.writeIntAttribute;
84import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060085import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070086import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Sudheer Shanka352dc572017-09-22 17:09:38 -070087import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_DEFAULT;
88import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_NON_METERED;
89import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_TMP_WHITELIST;
90import static com.android.server.net.NetworkPolicyLogger.NTWK_ALLOWED_WHITELIST;
91import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BG_RESTRICT;
92import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_BLACKLIST;
93import static com.android.server.net.NetworkPolicyLogger.NTWK_BLOCKED_POWER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070094import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060095
Jeff Sharkey21c9c452011-06-07 12:26:43 -070096import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080097import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070098import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070099
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700100import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -0700101import android.annotation.IntDef;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900102import android.annotation.NonNull;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700103import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700104import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800105import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700106import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700107import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700108import android.app.IActivityManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700109import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700110import android.app.Notification;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700111import android.app.NotificationManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700113import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700116import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700117import android.content.Intent;
118import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700119import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700120import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700121import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700122import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700123import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700124import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700125import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600126import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700128import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700129import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700130import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700131import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700132import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600133import android.net.Network;
134import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700135import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600137import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700138import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600139import android.net.NetworkRequest;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900140import android.net.NetworkSpecifier;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700141import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700142import android.net.NetworkTemplate;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900143import android.net.StringNetworkSpecifier;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600144import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700145import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700146import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700147import android.os.Binder;
Jeff Sharkeya7f50462018-02-14 14:26:10 -0700148import android.os.Build;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149import android.os.Environment;
150import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700151import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700152import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700153import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700154import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700155import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700156import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700157import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700158import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700159import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600160import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800161import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700163import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600164import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700165import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700166import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600167import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700168import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700169import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700170import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700171import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100172import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700173import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600174import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800175import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600176import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700177import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400178import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700179import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700180import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700181import android.util.ArrayMap;
182import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700183import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900184import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700185import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700187import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600188import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700189import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600190import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700191import android.util.SparseBooleanArray;
192import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900193import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194import android.util.TrustedTime;
195import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700196
Jeff Sharkey497e4432011-06-14 17:27:29 -0700197import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700198import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800199import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400200import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500201import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700202import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800203import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800204import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600205import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700207import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600208import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700209import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700210import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700211import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800212import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600213
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600214import libcore.io.IoUtils;
215
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217import org.xmlpull.v1.XmlSerializer;
218
219import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700220import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221import java.io.FileInputStream;
222import java.io.FileNotFoundException;
223import java.io.FileOutputStream;
224import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700225import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700226import java.lang.annotation.Retention;
227import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100228import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600229import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600230import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700232import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600233import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400234import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800235import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800236import java.util.concurrent.CountDownLatch;
237import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700239/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700240 * Service that maintains low-level network policy rules, using
241 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242 * <p>
243 * Derives active rules by combining a given policy with other system status,
244 * and delivers to listeners, such as {@link ConnectivityManager}, for
245 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700246 *
247 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000248 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700249 * <ul>
250 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
251 * rules).
252 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
253 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000254 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
255 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700256 * </ul>
257 *
258 * <p>
259 * As such, methods that require synchronization have the following prefixes:
260 * <ul>
261 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
262 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000263 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
264 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700265 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700266 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700267public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700268 static final String TAG = NetworkPolicyLogger.TAG;
269 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
270 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700271
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700272 private static final int VERSION_INIT = 1;
273 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700274 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800275 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800276 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800277 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700278 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700279 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700280 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700281 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600282 private static final int VERSION_ADDED_CYCLE = 11;
283 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700284
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800285 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400286 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800287 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400288 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800289 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400290 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900291 @VisibleForTesting
292 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700293
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294 private static final String TAG_POLICY_LIST = "policy-list";
295 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600296 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700297 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700298 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800299 private static final String TAG_WHITELIST = "whitelist";
300 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800301 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302
303 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700304 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
306 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700307 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
309 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
310 private static final String ATTR_CYCLE_START = "cycleStart";
311 private static final String ATTR_CYCLE_END = "cycleEnd";
312 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313 private static final String ATTR_WARNING_BYTES = "warningBytes";
314 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700315 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800316 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
317 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800318 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700319 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700321 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600323 private static final String ATTR_SUB_ID = "subId";
324 private static final String ATTR_TITLE = "title";
325 private static final String ATTR_SUMMARY = "summary";
326 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
327 private static final String ATTR_USAGE_BYTES = "usageBytes";
328 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600329 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800331 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800332 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800333 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800334 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700335 private static final String ACTION_SNOOZE_RAPID =
336 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700337
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700338 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
339
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800340 /**
341 * Indicates the maximum wait time for admin data to be available;
342 */
343 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
344
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700345 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700346 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800347 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800348 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700349 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700350 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
351 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700352 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700353 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900354 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800355 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700356
Makoto Onuki8e777332017-03-28 11:25:47 -0700357 private static final int UID_MSG_STATE_CHANGED = 100;
358 private static final int UID_MSG_GONE = 101;
359
Jeff Sharkey75279902011-05-24 18:39:45 -0700360 private final Context mContext;
361 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700362 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700363 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700364 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700365 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700366 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700367 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700368
369 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700370 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700371 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800372 @GuardedBy("mUidRulesFirstLock")
373 private PowerSaveState mRestrictBackgroundPowerState;
374
375 // Store the status of restrict background before turning on battery saver.
376 // Used to restore mRestrictBackground when battery saver is turned off.
377 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700378
Sudheer Shanka543339f2017-07-28 15:18:07 -0700379 // Denotes the status of restrict background read from disk.
380 private boolean mLoadedRestrictBackground;
381
Felipe Lemef0823852016-06-08 13:43:08 -0700382 // See main javadoc for instructions on how to use these locks.
383 final Object mUidRulesFirstLock = new Object();
384 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700385
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("allLocks") volatile boolean mSystemReady;
387
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
389 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
390 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800391 // Store whether user flipped restrict background in battery saver mode
392 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700393
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700394 private final boolean mSuppressDefaultPolicy;
395
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800396 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
397
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700398 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600399 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800400 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700401
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600402 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600403 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600404 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600405 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600406 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600407 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600408
Jeff Sharkey9252b342018-01-19 07:58:35 +0900409 /** Map from subId to daily opportunistic quota. */
410 @GuardedBy("mNetworkPoliciesSecondLock")
411 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
412
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700413 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700414 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700415 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700417
Felipe Lemef0823852016-06-08 13:43:08 -0700418 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700419 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700421 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700422 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800423 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700424
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700425 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700426 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700427 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
428
Jeff Sharkey32566012014-12-02 18:30:14 -0800429 /**
430 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700431 * in power save mode, except device idle (doze) still applies.
432 * TODO: An int array might be sufficient
433 */
Felipe Lemef0823852016-06-08 13:43:08 -0700434 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700435 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
436
437 /**
438 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800439 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700440 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800441 */
Felipe Lemef0823852016-06-08 13:43:08 -0700442 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700443 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700444
Felipe Lemef0823852016-06-08 13:43:08 -0700445 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700446 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
447
Felipe Lemeb85a6372016-01-14 16:16:16 -0800448 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800449 * UIDs that have been initially white-listed by system to avoid restricted background.
450 */
Felipe Lemef0823852016-06-08 13:43:08 -0700451 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800452 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
453 new SparseBooleanArray();
454
455 /**
456 * UIDs that have been initially white-listed by system to avoid restricted background,
457 * but later revoked by user.
458 */
Felipe Lemef0823852016-06-08 13:43:08 -0700459 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800460 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
461 new SparseBooleanArray();
462
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700463 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700464 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800465 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700466 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700467 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800468 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700469
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700470 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700471 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400472 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700473
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700474 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700475 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800476 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700477
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600478 /** Map from network ID to last observed meteredness state */
479 @GuardedBy("mNetworkPoliciesSecondLock")
480 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
481
Jeff Sharkey9252b342018-01-19 07:58:35 +0900482 /** Map from netId to subId as of last update */
483 @GuardedBy("mNetworkPoliciesSecondLock")
484 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
485
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800486 /**
487 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
488 * userId to restricted uids which belong to that user.
489 */
490 @GuardedBy("mUidRulesFirstLock")
491 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
492
Jeff Sharkey32566012014-12-02 18:30:14 -0800493 private final RemoteCallbackList<INetworkPolicyListener>
494 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700495
Dianne Hackborn497175b2014-07-01 12:56:08 -0700496 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700497 @VisibleForTesting
498 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700499
500 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700501
Felipe Lemef0823852016-06-08 13:43:08 -0700502 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700503 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700504
Svet Ganov16a16892015-04-16 10:32:04 -0700505 private final AppOpsManager mAppOps;
506
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800507 private final IPackageManager mIPm;
508
Sudheer Shankae7361852017-03-07 11:51:46 -0800509 private ActivityManagerInternal mActivityManagerInternal;
510
Sudheer Shanka352dc572017-09-22 17:09:38 -0700511 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800512
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700513 // TODO: keep whitelist of system-critical services that should never have
514 // rules enforced, such as system, phone, and radio UIDs.
515
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700516 // TODO: migrate notifications to SystemUI
517
Jeff Sharkey75279902011-05-24 18:39:45 -0700518 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700519 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
520 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700521 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
522 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700523 }
524
525 private static File getSystemDir() {
526 return new File(Environment.getDataDirectory(), "system");
527 }
528
529 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700530 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700531 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700532 mContext = checkNotNull(context, "missing context");
533 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700534 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700535 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700536 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700537 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700538 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700539 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700540 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700541 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700542
Amith Yamasani450a16b2013-09-18 16:28:50 -0700543 HandlerThread thread = new HandlerThread(TAG);
544 thread.start();
545 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700546
Makoto Onuki8e777332017-03-28 11:25:47 -0700547 // We create another thread for the UID events, which are more time-critical.
548 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
549 /*allowIo=*/ false);
550 mUidEventThread.start();
551 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
552
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700553 mSuppressDefaultPolicy = suppressDefaultPolicy;
554
Dianne Hackborne17b4452018-01-10 13:15:40 -0800555 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700556
557 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800558
Felipe Lemed17fda42016-04-29 11:12:45 -0700559 // Expose private service for system components to use.
560 LocalServices.addService(NetworkPolicyManagerInternal.class,
561 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700562 }
563
564 public void bindConnectivityManager(IConnectivityManager connManager) {
565 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700566 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700567
Felipe Lemef0823852016-06-08 13:43:08 -0700568 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700569 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700570 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
571 mPowerSaveWhitelistExceptIdleAppIds.clear();
572 if (whitelist != null) {
573 for (int uid : whitelist) {
574 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
575 }
576 }
577 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700578 mPowerSaveWhitelistAppIds.clear();
579 if (whitelist != null) {
580 for (int uid : whitelist) {
581 mPowerSaveWhitelistAppIds.put(uid, true);
582 }
583 }
584 } catch (RemoteException e) {
585 }
586 }
587
Felipe Lemea9505cc2016-02-26 10:28:41 -0800588 /**
589 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
590 * revoke the whitelist.
591 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700592 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800593 */
Felipe Lemef0823852016-06-08 13:43:08 -0700594 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800595 final List<UserInfo> users = mUserManager.getUsers();
596 final int numberUsers = users.size();
597
Felipe Lemea110eec2016-04-29 09:58:06 -0700598 boolean changed = false;
599 for (int i = 0; i < numberUsers; i++) {
600 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700601 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700602 }
603 return changed;
604 }
605
Felipe Lemef0823852016-06-08 13:43:08 -0700606 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700607 final SystemConfig sysConfig = SystemConfig.getInstance();
608 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800609 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
610 boolean changed = false;
611 for (int i = 0; i < allowDataUsage.size(); i++) {
612 final String pkg = allowDataUsage.valueAt(i);
613 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700614 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
615 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800616 final ApplicationInfo app;
617 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700618 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700620 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
621 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800622 continue;
623 }
624 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700625 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
626 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800627 continue;
628 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700629 final int uid = UserHandle.getUid(userId, app.uid);
630 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
631 if (LOGD)
632 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
633 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800634 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700635 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700636 if (LOGD)
637 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
638 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700639 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700640 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800641 }
642 }
643 return changed;
644 }
645
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800646 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700647 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800648 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700649 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800650 // Boost thread's priority during system server init
651 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700652 if (!isBandwidthControlEnabled()) {
653 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
654 return;
655 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700656
Felipe Leme873a83a2016-09-07 11:34:10 -0700657 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700658
Felipe Leme873a83a2016-09-07 11:34:10 -0700659 synchronized (mUidRulesFirstLock) {
660 synchronized (mNetworkPoliciesSecondLock) {
661 updatePowerSaveWhitelistUL();
662 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
663 mPowerManagerInternal.registerLowPowerModeObserver(
664 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800665 @Override
666 public int getServiceType() {
667 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700668 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800669
670 @Override
671 public void onLowPowerModeChanged(PowerSaveState result) {
672 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800673 if (LOGD) {
674 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
675 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800676 synchronized (mUidRulesFirstLock) {
677 if (mRestrictPower != enabled) {
678 mRestrictPower = enabled;
679 updateRulesForRestrictPowerUL();
680 }
681 }
682 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800683 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800684 mRestrictPower = mPowerManagerInternal.getLowPowerState(
685 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700686
687 mSystemReady = true;
688
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800689 waitForAdminData();
690
Felipe Leme873a83a2016-09-07 11:34:10 -0700691 // read policy from disk
692 readPolicyAL();
693
jackqdyulei29c82ab2017-03-10 14:09:16 -0800694 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700695 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800696 mRestrictBackgroundPowerState = mPowerManagerInternal
697 .getLowPowerState(ServiceType.DATA_SAVER);
698 final boolean localRestrictBackground =
699 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700700 if (localRestrictBackground && !mLoadedRestrictBackground) {
701 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800702 }
703 mPowerManagerInternal.registerLowPowerModeObserver(
704 new PowerManagerInternal.LowPowerModeListener() {
705 @Override
706 public int getServiceType() {
707 return ServiceType.DATA_SAVER;
708 }
709
710 @Override
711 public void onLowPowerModeChanged(PowerSaveState result) {
712 synchronized (mUidRulesFirstLock) {
713 updateRestrictBackgroundByLowPowerModeUL(result);
714 }
715 }
716 });
717
Felipe Leme873a83a2016-09-07 11:34:10 -0700718 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
719 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700720 }
Felipe Lemef0823852016-06-08 13:43:08 -0700721
Sudheer Shanka543339f2017-07-28 15:18:07 -0700722 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 updateRulesForGlobalChangeAL(false);
724 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700725 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800726 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700727
Sudheer Shankae7361852017-03-07 11:51:46 -0800728 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700729 try {
730 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000731 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800732 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700733 mNetworkManager.registerObserver(mAlertObserver);
734 } catch (RemoteException e) {
735 // ignored; both services live in system_server
736 }
737
738 // listen for changes to power save whitelist
739 final IntentFilter whitelistFilter = new IntentFilter(
740 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
741 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
742
Felipe Leme873a83a2016-09-07 11:34:10 -0700743 // watch for network interfaces to be claimed
744 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
745 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
746
747 // listen for package changes to update policy
748 final IntentFilter packageFilter = new IntentFilter();
749 packageFilter.addAction(ACTION_PACKAGE_ADDED);
750 packageFilter.addDataScheme("package");
751 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
752
753 // listen for UID changes to update policy
754 mContext.registerReceiver(
755 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
756
757 // listen for user changes to update policy
758 final IntentFilter userFilter = new IntentFilter();
759 userFilter.addAction(ACTION_USER_ADDED);
760 userFilter.addAction(ACTION_USER_REMOVED);
761 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
762
763 // listen for stats update events
764 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
765 mContext.registerReceiver(
766 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
767
768 // listen for restrict background changes from notifications
769 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
770 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
771
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700772 // Listen for snooze from notifications
773 mContext.registerReceiver(mSnoozeReceiver,
774 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
775 mContext.registerReceiver(mSnoozeReceiver,
776 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700777
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600778 // listen for configured wifi networks to be loaded
779 final IntentFilter wifiFilter =
780 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
781 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700782
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700783 // listen for carrier config changes to update data cycle information
784 final IntentFilter carrierConfigFilter = new IntentFilter(
785 ACTION_CARRIER_CONFIG_CHANGED);
786 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
787
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600788 // listen for meteredness changes
789 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
790 new NetworkRequest.Builder().build(), mNetworkCallback);
791
Felipe Leme873a83a2016-09-07 11:34:10 -0700792 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800793 // tell systemReady() that the service has been initialized
794 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700795 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800796 // Restore the default priority after init is done
797 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700798 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700799 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700800 }
801
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800802 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
803 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
804 mHandler.post(() -> initService(initCompleteSignal));
805 return initCompleteSignal;
806 }
807
808 public void systemReady(CountDownLatch initCompleteSignal) {
809 // wait for initService to complete
810 try {
811 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
812 throw new IllegalStateException("Service " + TAG +" init timeout");
813 }
814 } catch (InterruptedException e) {
815 Thread.currentThread().interrupt();
816 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
817 }
818 }
819
Sudheer Shankac9d94072017-02-22 22:13:55 +0000820 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700821 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700822 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
823 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700824 }
825
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700826 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700827 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700828 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700829
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700830 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700831 }
832
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700833 @Override public void onUidIdle(int uid, boolean disabled) {
834 }
835
836 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700837 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700838 };
839
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700840 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700841 @Override
842 public void onReceive(Context context, Intent intent) {
843 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700844 synchronized (mUidRulesFirstLock) {
845 updatePowerSaveWhitelistUL();
846 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700847 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700848 }
849 }
850 };
851
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700852 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700853 @Override
854 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700855 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700856
857 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700858 final int uid = intent.getIntExtra(EXTRA_UID, -1);
859 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700860
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700861 if (ACTION_PACKAGE_ADDED.equals(action)) {
862 // update rules for UID, since it might be subject to
863 // global background data policy
864 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700865 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700866 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700867 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700868 }
869 }
870 };
871
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700872 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700873 @Override
874 public void onReceive(Context context, Intent intent) {
875 // on background handler thread, and UID_REMOVED is protected
876
877 final int uid = intent.getIntExtra(EXTRA_UID, -1);
878 if (uid == -1) return;
879
880 // remove any policy and update rules to clean up
881 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700882 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700883 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700884 synchronized (mNetworkPoliciesSecondLock) {
885 writePolicyAL();
886 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700887 }
888 }
889 };
890
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700891 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700892 @Override
893 public void onReceive(Context context, Intent intent) {
894 // on background handler thread, and USER_ADDED and USER_REMOVED
895 // broadcasts are protected
896
897 final String action = intent.getAction();
898 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
899 if (userId == -1) return;
900
Amith Yamasani15e472352015-04-24 19:06:07 -0700901 switch (action) {
902 case ACTION_USER_REMOVED:
903 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700904 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800905 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700906 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700907 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800908 // Removing outside removeUserStateUL since that can also be called when
909 // user resets app preferences.
910 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700911 if (action == ACTION_USER_ADDED) {
912 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700913 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700914 }
915 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700916 synchronized (mNetworkPoliciesSecondLock) {
917 updateRulesForGlobalChangeAL(true);
918 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700919 }
920 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700921 }
922 }
923 };
924
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700925 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700926 * Receiver that watches for {@link INetworkStatsService} updates, which we
927 * use to check against {@link NetworkPolicy#warningBytes}.
928 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700929 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700930 @Override
931 public void onReceive(Context context, Intent intent) {
932 // on background handler thread, and verified
933 // READ_NETWORK_USAGE_HISTORY permission above.
934
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800935 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700936 synchronized (mNetworkPoliciesSecondLock) {
937 updateNetworkEnabledNL();
938 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939 }
940 }
941 };
942
943 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700944 * Receiver that watches for {@link Notification} control of
945 * {@link #mRestrictBackground}.
946 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700947 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700948 @Override
949 public void onReceive(Context context, Intent intent) {
950 // on background handler thread, and verified MANAGE_NETWORK_POLICY
951 // permission above.
952
953 setRestrictBackground(false);
954 }
955 };
956
957 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800958 * Receiver that watches for {@link Notification} control of
959 * {@link NetworkPolicy#lastWarningSnooze}.
960 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700961 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800962 @Override
963 public void onReceive(Context context, Intent intent) {
964 // on background handler thread, and verified MANAGE_NETWORK_POLICY
965 // permission above.
966
967 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700968 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
969 performSnooze(template, TYPE_WARNING);
970 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
971 performSnooze(template, TYPE_RAPID);
972 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800973 }
974 };
975
976 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600977 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600978 * we can perform upgrade logic. After initial upgrade logic, it updates
979 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700980 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600981 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700982 @Override
983 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900984 synchronized (mUidRulesFirstLock) {
985 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600986 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600987 }
988 }
989 // Only need to perform upgrade logic once
990 mContext.unregisterReceiver(this);
991 }
992 };
993
994 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
995 @Override
996 public void onCapabilitiesChanged(Network network,
997 NetworkCapabilities networkCapabilities) {
998 if (network == null || networkCapabilities == null) return;
999
1000 synchronized (mNetworkPoliciesSecondLock) {
1001 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1002 final boolean newMetered = !networkCapabilities
1003 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1004
1005 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001006 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001007 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001008 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001009 }
1010 }
1011 }
1012 };
1013
1014 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001015 * Observer that watches for {@link INetworkManagementService} alerts.
1016 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001017 final private INetworkManagementEventObserver mAlertObserver
1018 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 @Override
1020 public void limitReached(String limitName, String iface) {
1021 // only someone like NMS should be calling us
1022 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1023
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001024 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1025 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 }
1027 }
1028 };
1029
1030 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001031 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1032 * to show visible notifications as needed.
1033 */
Felipe Lemef0823852016-06-08 13:43:08 -07001034 void updateNotificationsNL() {
1035 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001037 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001038 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001039 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001040
1041 // TODO: when switching to kernel notifications, compute next future
1042 // cycle boundary to recompute notifications.
1043
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001044 // examine stats for each active policy
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001045 final long now = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001046 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1047 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001048 // ignore policies that aren't relevant to user
1049 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001050 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001051
Jeff Sharkey53313d72017-07-13 16:47:32 -06001052 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1053 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001054 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1055 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1056 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001058 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001059 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001060 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1061 if (snoozedThisCycle) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001062 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1063 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001065 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 }
1067
Jeff Sharkey497e4432011-06-14 17:27:29 -07001068 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001069 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001071 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1072 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074 }
1075 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001076
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001077 // Warn if average usage over last 4 days is on track to blow pretty
1078 // far past the plan limits.
1079 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001080 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001081 final long recentBytes = getTotalBytes(policy.template, now - recentDuration, now);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001082
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001083 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001084 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001085 final long alertBytes = (policy.limitBytes * 3) / 2;
1086
1087 if (LOGD) {
1088 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1089 + projectedBytes + " alert " + alertBytes);
1090 }
1091
1092 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1093 - DateUtils.DAY_IN_MILLIS;
1094 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001095 enqueueNotification(policy, TYPE_RAPID, 0);
1096 }
1097 }
1098 }
1099
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001101 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001102 final NotificationId notificationId = beforeNotifs.valueAt(i);
1103 if (!mActiveNotifs.contains(notificationId)) {
1104 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 }
1106 }
1107 }
1108
1109 /**
1110 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001111 * current device state, such as when
1112 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1113 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 */
1115 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001116 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001117 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1118 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001119
Jeff Sharkey32566012014-12-02 18:30:14 -08001120 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001121 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001122 for (int subId : subIds) {
1123 final String subscriberId = tele.getSubscriberId(subId);
1124 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001125 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1126 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001127 if (template.matches(probeIdent)) {
1128 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001129 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001130 }
1131 return false;
1132 } else {
1133 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 }
1136
1137 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001138 * Notify that given {@link NetworkTemplate} is over
1139 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1140 */
Felipe Lemef0823852016-06-08 13:43:08 -07001141 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001143 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001144 mOverLimitNotified.add(template);
1145 }
1146 }
1147
Felipe Lemef0823852016-06-08 13:43:08 -07001148 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 mOverLimitNotified.remove(template);
1150 }
1151
1152 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001153 * Show notification for combined {@link NetworkPolicy} and specific type,
1154 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1155 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001156 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001157 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001158 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001159 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001161 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001162 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001163 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164
1165 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001166 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001167 switch (type) {
1168 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001169 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001170 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001171
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001172 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001173 builder.setTicker(title);
1174 builder.setContentTitle(title);
1175 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001176
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001177 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1178 builder.setDeleteIntent(PendingIntent.getBroadcast(
1179 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1180
Wei Liu546cb772016-07-21 16:19:01 -07001181 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001182 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001183 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1184
Jeff Sharkey497e4432011-06-14 17:27:29 -07001185 break;
1186 }
1187 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001188 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001189
1190 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001191 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001192 switch (policy.template.getMatchRule()) {
1193 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001194 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001195 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001196 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001198 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001199 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001200 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001201 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001202 case MATCH_WIFI:
1203 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001204 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001205 break;
1206 default:
1207 title = null;
1208 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001209 }
1210
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001211 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001212 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001213 builder.setTicker(title);
1214 builder.setContentTitle(title);
1215 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001216
Wei Liu546cb772016-07-21 16:19:01 -07001217 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001218 builder.setContentIntent(PendingIntent.getActivity(
1219 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1220 break;
1221 }
1222 case TYPE_LIMIT_SNOOZED: {
1223 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001224 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001225 Formatter.formatFileSize(mContext, overBytes));
1226
1227 final CharSequence title;
1228 switch (policy.template.getMatchRule()) {
1229 case MATCH_MOBILE_3G_LOWER:
1230 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1231 break;
1232 case MATCH_MOBILE_4G:
1233 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1234 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001235 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001236 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1237 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001238 case MATCH_WIFI:
1239 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1240 break;
1241 default:
1242 title = null;
1243 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001244 }
1245
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001246 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001247 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001248 builder.setTicker(title);
1249 builder.setContentTitle(title);
1250 builder.setContentText(body);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001251 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001252
Wei Liu546cb772016-07-21 16:19:01 -07001253 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001254 builder.setContentIntent(PendingIntent.getActivity(
1255 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001256 break;
1257 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001258 case TYPE_RAPID: {
1259 final CharSequence title = res.getText(R.string.data_usage_rapid_title);
1260 body = res.getText(R.string.data_usage_rapid_body);
1261
Jeff Sharkey2e471452018-01-19 18:02:47 +09001262 builder.setSmallIcon(R.drawable.stat_notify_error);
1263 builder.setTicker(title);
1264 builder.setContentTitle(title);
1265 builder.setContentText(body);
1266
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001267 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1268 builder.setDeleteIntent(PendingIntent.getBroadcast(
1269 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1270
1271 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001272 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001273 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001274 break;
1275 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001276 }
1277
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001278 if (!TextUtils.isEmpty(body)) {
1279 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001280 }
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001281
1282 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1283 notificationId.getId(), builder.build(), UserHandle.ALL);
1284 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001285 }
1286
Chris Wren193ae6b2017-03-31 15:17:11 -04001287 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001288 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1289 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001290 }
1291
1292 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001293 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001294 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001295 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001296 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297 @Override
1298 public void onReceive(Context context, Intent intent) {
1299 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1300 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001301
1302 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001303 synchronized (mUidRulesFirstLock) {
1304 synchronized (mNetworkPoliciesSecondLock) {
1305 ensureActiveMobilePolicyAL();
1306 normalizePoliciesNL();
1307 updateNetworkEnabledNL();
1308 updateNetworkRulesNL();
1309 updateNotificationsNL();
1310 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001311 }
1312 }
1313 };
1314
Jeff Sharkey2e471452018-01-19 18:02:47 +09001315 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001316 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001317 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001318 final CountDownLatch latch = new CountDownLatch(1);
1319 mHandler.post(() -> {
1320 latch.countDown();
1321 });
1322 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001323 }
1324
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001326 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1327 * if necessary.
1328 *
1329 * @param subId that has its associated NetworkPolicy updated if necessary
1330 * @return if any policies were updated
1331 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001332 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1333 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001334
1335 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001336 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1337 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001338
1339 // find and update the mobile NetworkPolicy for this subscriber id
1340 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001341 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001342 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1343 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1344 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001345 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1346 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001347 }
1348 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001349 return policyUpdated;
1350 }
1351
1352 /**
1353 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1354 *
1355 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1356 * to do so, it returns the fallback value.
1357 *
1358 * @param config The CarrierConfig to read the value from.
1359 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1360 * @return cycleDay to use in the mobile NetworkPolicy.
1361 */
1362 @VisibleForTesting
1363 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1364 int fallbackCycleDay) {
1365 if (config == null) {
1366 return fallbackCycleDay;
1367 }
1368 int cycleDay =
1369 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1370 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1371 return fallbackCycleDay;
1372 }
1373 // validate cycleDay value
1374 final Calendar cal = Calendar.getInstance();
1375 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1376 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1377 Slog.e(TAG, "Invalid date in "
1378 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1379 return fallbackCycleDay;
1380 }
1381 return cycleDay;
1382 }
1383
1384 /**
1385 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1386 *
1387 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1388 * to do so, it returns the fallback value.
1389 *
1390 * @param config The CarrierConfig to read the value from.
1391 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1392 * @return warningBytes to use in the mobile NetworkPolicy.
1393 */
1394 @VisibleForTesting
1395 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1396 long fallbackWarningBytes) {
1397 if (config == null) {
1398 return fallbackWarningBytes;
1399 }
1400 long warningBytes =
1401 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1402
1403 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1404 return WARNING_DISABLED;
1405 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1406 return getPlatformDefaultWarningBytes();
1407 } else if (warningBytes < 0) {
1408 Slog.e(TAG, "Invalid value in "
1409 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1410 + "non-negative value but got: " + warningBytes);
1411 return fallbackWarningBytes;
1412 }
1413
1414 return warningBytes;
1415 }
1416
1417 /**
1418 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1419 *
1420 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1421 * to do so, it returns the fallback value.
1422 *
1423 * @param config The CarrierConfig to read the value from.
1424 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1425 * @return limitBytes to use in the mobile NetworkPolicy.
1426 */
1427 @VisibleForTesting
1428 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1429 long fallbackLimitBytes) {
1430 if (config == null) {
1431 return fallbackLimitBytes;
1432 }
1433 long limitBytes =
1434 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1435
1436 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1437 return LIMIT_DISABLED;
1438 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1439 return getPlatformDefaultLimitBytes();
1440 } else if (limitBytes < 0) {
1441 Slog.e(TAG, "Invalid value in "
1442 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1443 + "non-negative value but got: " + limitBytes);
1444 return fallbackLimitBytes;
1445 }
1446 return limitBytes;
1447 }
1448
1449 /**
1450 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1451 */
1452 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1453 @Override
1454 public void onReceive(Context context, Intent intent) {
1455 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1456 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1457
1458 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1459 return;
1460 }
1461 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001462 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001463 final String subscriberId = tele.getSubscriberId(subId);
1464
1465 maybeRefreshTrustedTime();
1466 synchronized (mUidRulesFirstLock) {
1467 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001468 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001469 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001470 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001471 if (!updated) return;
1472 // update network and notification rules, as the data cycle changed and it's
1473 // possible that we should be triggering warnings/limits now
1474 handleNetworkPoliciesUpdateAL(true);
1475 }
1476 }
1477 }
1478 };
1479
1480 /**
1481 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1482 * one has been updated.
1483 *
1484 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1485 * update.
1486 */
1487 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1488 if (shouldNormalizePolicies) {
1489 normalizePoliciesNL();
1490 }
1491 updateNetworkEnabledNL();
1492 updateNetworkRulesNL();
1493 updateNotificationsNL();
1494 writePolicyAL();
1495 }
1496
1497 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001498 * Proactively control network data connections when they exceed
1499 * {@link NetworkPolicy#limitBytes}.
1500 */
Felipe Lemef0823852016-06-08 13:43:08 -07001501 void updateNetworkEnabledNL() {
1502 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001503
1504 // TODO: reset any policy-disabled networks when any policy is removed
1505 // completely, which is currently rare case.
1506
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001507 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1508 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001509 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001510 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001511 setNetworkTemplateEnabled(policy.template, true);
1512 continue;
1513 }
1514
Jeff Sharkey53313d72017-07-13 16:47:32 -06001515 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1516 .cycleIterator(policy).next();
1517 final long start = cycle.first.toInstant().toEpochMilli();
1518 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001519 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001520
1521 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001522 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1523 && policy.lastLimitSnooze < start;
1524 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001525
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001526 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001527 }
1528 }
1529
1530 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001531 * Proactively disable networks that match the given
1532 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001533 */
1534 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001535 // TODO: reach into ConnectivityManager to proactively disable bringing
1536 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001537
1538 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1539 // If mobile data usage hits the limit or if the user resumes the data, we need to
1540 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001541 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1542 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001543
Jeff Sharkey2e471452018-01-19 18:02:47 +09001544 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001545 for (int subId : subIds) {
1546 final String subscriberId = tm.getSubscriberId(subId);
1547 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001548 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1549 true);
Jack Yu8781b682016-07-08 14:28:51 -07001550 // Template is matched when subscriber id matches.
1551 if (template.matches(probeIdent)) {
1552 tm.setPolicyDataEnabled(enabled, subId);
1553 }
1554 }
1555 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001556 }
1557
1558 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001559 * Collect all ifaces from a {@link NetworkState} into the given set.
1560 */
1561 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1562 final String baseIface = state.linkProperties.getInterfaceName();
1563 if (baseIface != null) {
1564 ifaces.add(baseIface);
1565 }
1566 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1567 final String stackedIface = stackedLink.getInterfaceName();
1568 if (stackedIface != null) {
1569 ifaces.add(stackedIface);
1570 }
1571 }
1572 }
1573
1574 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001575 * Examine all connected {@link NetworkState}, looking for
1576 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1577 * remaining quota based on usage cycle and historical stats.
1578 */
Felipe Lemef0823852016-06-08 13:43:08 -07001579 void updateNetworkRulesNL() {
1580 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581
1582 final NetworkState[] states;
1583 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001584 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001586 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 return;
1588 }
1589
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001590 // First, generate identities of all connected networks so we can
1591 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001592 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001593 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001594 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001595 if (state.network != null) {
1596 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1597 }
Wei Liub8eaf452016-01-25 10:32:27 -08001598 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001599 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1600 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001601 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001602 }
1603 }
1604
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001605 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001606 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001607
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001608 // For every well-defined policy, compute remaining data based on
1609 // current cycle and historical stats, and push to kernel.
1610 final ArraySet<String> matchingIfaces = new ArraySet<>();
1611 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1612 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1613
1614 // Collect all ifaces that match this policy
1615 matchingIfaces.clear();
1616 for (int j = identified.size() - 1; j >= 0; j--) {
1617 if (policy.template.matches(identified.valueAt(j))) {
1618 collectIfaces(matchingIfaces, identified.keyAt(j));
1619 }
1620 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001622 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001623 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001624 }
1625
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001626 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001627 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001628 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001629 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001630 if (hasLimit && policy.hasCycle()) {
1631 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1632 .cycleIterator(policy).next();
1633 final long start = cycle.first.toInstant().toEpochMilli();
1634 final long end = cycle.second.toInstant().toEpochMilli();
1635 final long totalBytes = getTotalBytes(policy.template, start, end);
1636
1637 if (policy.lastLimitSnooze >= start) {
1638 // snoozing past quota, but we still need to restrict apps,
1639 // so push really high quota.
1640 quotaBytes = Long.MAX_VALUE;
1641 } else {
1642 // remaining "quota" bytes are based on total usage in
1643 // current cycle. kernel doesn't like 0-byte rules, so we
1644 // set 1-byte quota and disable the radio later.
1645 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1646 }
1647 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001648 // metered network, but no policy limit; we still need to
1649 // restrict apps, so push really high quota.
1650 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001651 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001652
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001653 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001654 // TODO: switch to shared quota once NMS supports
1655 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001656 }
1657
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001658 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1659 final String iface = matchingIfaces.valueAt(j);
1660 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001661 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001662 }
1663 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001664
1665 // keep track of lowest warning or limit of active policies
1666 if (hasWarning && policy.warningBytes < lowestRule) {
1667 lowestRule = policy.warningBytes;
1668 }
1669 if (hasLimit && policy.limitBytes < lowestRule) {
1670 lowestRule = policy.limitBytes;
1671 }
1672 }
1673
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001674 // One final pass to catch any metered ifaces that don't have explicitly
1675 // defined policies; typically Wi-Fi networks.
1676 for (NetworkState state : states) {
1677 if (state.networkInfo != null && state.networkInfo.isConnected()
1678 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1679 matchingIfaces.clear();
1680 collectIfaces(matchingIfaces, state);
1681 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1682 final String iface = matchingIfaces.valueAt(j);
1683 if (!newMeteredIfaces.contains(iface)) {
1684 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1685 newMeteredIfaces.add(iface);
1686 }
1687 }
1688 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001689 }
1690
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001691 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001692 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1693 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001694 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001695 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001696 }
1697 }
1698 mMeteredIfaces = newMeteredIfaces;
1699
Jeff Sharkey9252b342018-01-19 07:58:35 +09001700 // Finally, calculate our opportunistic quotas
1701 // TODO: add experiments support to disable or tweak ratios
1702 mSubscriptionOpportunisticQuota.clear();
1703 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001704 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001705 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001706 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001707 if (plan == null) continue;
1708
1709 // By default assume we have no quota
Jeff Sharkey9252b342018-01-19 07:58:35 +09001710 long quotaBytes = 0;
1711
Jeff Sharkey2e471452018-01-19 18:02:47 +09001712 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001713 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1714 // Ignore missing limits
Jeff Sharkey2e471452018-01-19 18:02:47 +09001715 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001716 // Unlimited data; let's use 20MiB/day (600MiB/month)
1717 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1718 } else {
1719 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001720 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001721 final long start = cycle.first.toInstant().toEpochMilli();
1722 final long end = cycle.second.toInstant().toEpochMilli();
1723 final long totalBytes = getTotalBytes(
1724 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1725 final long remainingBytes = limitBytes - totalBytes;
Jeff Sharkeyf46dc152018-02-07 12:28:24 -07001726 final long remainingDays = Math.max(1, (end - currentTimeMillis())
Jeff Sharkey9252b342018-01-19 07:58:35 +09001727 / TimeUnit.DAYS.toMillis(1));
1728 if (remainingBytes > 0) {
1729 quotaBytes = (remainingBytes / remainingDays) / 10;
1730 }
1731 }
1732
1733 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1734 }
1735
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001736 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001737 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001738
1739 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001740 }
1741
1742 /**
1743 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1744 * have at least a default mobile policy defined.
1745 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001746 private void ensureActiveMobilePolicyAL() {
1747 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001748 if (mSuppressDefaultPolicy) return;
1749
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001750 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1751 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001752
Jeff Sharkey2e471452018-01-19 18:02:47 +09001753 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001754 for (int subId : subIds) {
1755 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001756 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001757 }
1758 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001759
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001760 /**
1761 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1762 * have at least a default mobile policy defined.
1763 *
1764 * @param subId to build a default policy for
1765 * @param subscriberId that we check for an existing policy
1766 * @return true if a mobile network policy was added, or false one already existed.
1767 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001768 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001769 // Poke around to see if we already have a policy
1770 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001771 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001772 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1773 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1774 if (template.matches(probeIdent)) {
1775 if (LOGD) {
1776 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1777 + NetworkIdentity.scrubSubscriberId(subscriberId));
1778 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001779 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001780 }
1781 }
1782
Jeff Sharkey32566012014-12-02 18:30:14 -08001783 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1784 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001785 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001786 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001787 return true;
1788 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001789
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001790 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001791 final int dataWarningConfig = mContext.getResources().getInteger(
1792 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001793 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001794 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001795 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001796 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001797 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001798 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001799
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001800 private long getPlatformDefaultLimitBytes() {
1801 return LIMIT_DISABLED;
1802 }
1803
1804 @VisibleForTesting
1805 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001806 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001807 final RecurrenceRule cycleRule = NetworkPolicy
1808 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001809 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001810 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1811 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1812 synchronized (mUidRulesFirstLock) {
1813 synchronized (mNetworkPoliciesSecondLock) {
1814 updateDefaultMobilePolicyAL(subId, policy);
1815 }
1816 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001817 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001818 }
1819
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001820 /**
1821 * Update the given {@link NetworkPolicy} based on any carrier-provided
1822 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1823 * Leaves policy untouched if the user has modified it.
1824 *
1825 * @return if the policy was modified
1826 */
1827 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1828 if (!policy.inferred) {
1829 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1830 return false;
1831 }
1832
1833 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1834 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1835 policy.lastLimitSnooze, policy.metered, policy.inferred);
1836
1837 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1838 if (!ArrayUtils.isEmpty(plans)) {
1839 final SubscriptionPlan plan = plans[0];
1840 policy.cycleRule = plan.getCycleRule();
1841 final long planLimitBytes = plan.getDataLimitBytes();
1842 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1843 policy.warningBytes = getPlatformDefaultWarningBytes();
1844 policy.limitBytes = getPlatformDefaultLimitBytes();
1845 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1846 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1847 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1848 } else {
1849 policy.warningBytes = (planLimitBytes * 9) / 10;
1850 switch (plan.getDataLimitBehavior()) {
1851 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1852 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1853 policy.limitBytes = planLimitBytes;
1854 break;
1855 default:
1856 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1857 break;
1858 }
1859 }
1860 } else {
1861 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1862 final int currentCycleDay;
1863 if (policy.cycleRule.isMonthly()) {
1864 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1865 } else {
1866 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1867 }
1868 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1869 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1870 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1871 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1872 }
1873
1874 if (policy.equals(original)) {
1875 return false;
1876 } else {
1877 Slog.d(TAG, "Updated " + original + " to " + policy);
1878 return true;
1879 }
1880 }
1881
Felipe Lemef0823852016-06-08 13:43:08 -07001882 private void readPolicyAL() {
1883 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001884
1885 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001886 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001887 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001888 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001889 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001890
1891 FileInputStream fis = null;
1892 try {
1893 fis = mPolicyFile.openRead();
1894 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001895 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001896
Felipe Leme46b451f2016-08-19 08:46:17 -07001897 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1898 // to skip UIDs that were explicitly blacklisted.
1899 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1900
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001901 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001902 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001903 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001904 while ((type = in.next()) != END_DOCUMENT) {
1905 final String tag = in.getName();
1906 if (type == START_TAG) {
1907 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001908 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001909 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001910 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1911 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001912 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1913 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1914 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001915 final String networkId;
1916 if (version >= VERSION_ADDED_NETWORK_ID) {
1917 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1918 } else {
1919 networkId = null;
1920 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001921 final RecurrenceRule cycleRule;
1922 if (version >= VERSION_ADDED_CYCLE) {
1923 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1924 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1925 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1926 cycleRule = new RecurrenceRule(
1927 RecurrenceRule.convertZonedDateTime(start),
1928 RecurrenceRule.convertZonedDateTime(end),
1929 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001930 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001931 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1932 final String cycleTimezone;
1933 if (version >= VERSION_ADDED_TIMEZONE) {
1934 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1935 } else {
1936 cycleTimezone = "UTC";
1937 }
1938 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001939 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001940 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1941 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001942 final long lastLimitSnooze;
1943 if (version >= VERSION_SPLIT_SNOOZE) {
1944 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1945 } else if (version >= VERSION_ADDED_SNOOZE) {
1946 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001947 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001948 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001949 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001950 final boolean metered;
1951 if (version >= VERSION_ADDED_METERED) {
1952 metered = readBooleanAttribute(in, ATTR_METERED);
1953 } else {
1954 switch (networkTemplate) {
1955 case MATCH_MOBILE_3G_LOWER:
1956 case MATCH_MOBILE_4G:
1957 case MATCH_MOBILE_ALL:
1958 metered = true;
1959 break;
1960 default:
1961 metered = false;
1962 }
1963 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001964 final long lastWarningSnooze;
1965 if (version >= VERSION_SPLIT_SNOOZE) {
1966 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1967 } else {
1968 lastWarningSnooze = SNOOZE_NEVER;
1969 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001970 final boolean inferred;
1971 if (version >= VERSION_ADDED_INFERRED) {
1972 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1973 } else {
1974 inferred = false;
1975 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001976
Jeff Sharkey32566012014-12-02 18:30:14 -08001977 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1978 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001979 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001980 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1981 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001982 lastLimitSnooze, metered, inferred));
1983 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001984
1985 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1986 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1987 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1988 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1989 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1990 RecurrenceRule.convertZonedDateTime(start),
1991 RecurrenceRule.convertZonedDateTime(end),
1992 RecurrenceRule.convertPeriod(period));
1993 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1994 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1995
1996 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1997 SubscriptionPlan.BYTES_UNKNOWN);
1998 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1999 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2000 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2001 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2002 builder.setDataLimit(limitBytes, limitBehavior);
2003 }
2004
2005 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2006 SubscriptionPlan.BYTES_UNKNOWN);
2007 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2008 SubscriptionPlan.TIME_UNKNOWN);
2009 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2010 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2011 builder.setDataUsage(usageBytes, usageTime);
2012 }
2013
2014 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2015 final SubscriptionPlan plan = builder.build();
2016 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2017 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2018
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002019 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2020 mSubscriptionPlansOwner.put(subId, ownerPackage);
2021
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002022 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002023 final int uid = readIntAttribute(in, ATTR_UID);
2024 final int policy = readIntAttribute(in, ATTR_POLICY);
2025
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002026 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002027 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002028 } else {
2029 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2030 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002031 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002032 final int appId = readIntAttribute(in, ATTR_APP_ID);
2033 final int policy = readIntAttribute(in, ATTR_POLICY);
2034
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002035 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002036 // app policy is deprecated so this is only used in pre system user split.
2037 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002038 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002039 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002040 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002041 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002042 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002043 } else if (TAG_WHITELIST.equals(tag)) {
2044 insideWhitelist = true;
2045 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2046 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002047 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002048 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2049 final int uid = readIntAttribute(in, ATTR_UID);
2050 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002051 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002052 } else if (type == END_TAG) {
2053 if (TAG_WHITELIST.equals(tag)) {
2054 insideWhitelist = false;
2055 }
2056
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002057 }
2058 }
2059
Felipe Leme46b451f2016-08-19 08:46:17 -07002060 final int size = whitelistedRestrictBackground.size();
2061 for (int i = 0; i < size; i++) {
2062 final int uid = whitelistedRestrictBackground.keyAt(i);
2063 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2064 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2065 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2066 + " because its policy is " + uidPoliciesToString(policy));
2067 continue;
2068 }
2069 if (UserHandle.isApp(uid)) {
2070 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2071 if (LOGV)
2072 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2073 setUidPolicyUncheckedUL(uid, newPolicy, false);
2074 } else {
2075 Slog.w(TAG, "unable to update policy on UID " + uid);
2076 }
2077 }
2078
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002079 } catch (FileNotFoundException e) {
2080 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002081 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002082 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002083 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002084 } finally {
2085 IoUtils.closeQuietly(fis);
2086 }
2087 }
2088
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002089 /**
2090 * Upgrade legacy background data flags, notifying listeners of one last
2091 * change to always-true.
2092 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002093 private void upgradeDefaultBackgroundDataUL() {
2094 // This method is only called when we're unable to find the network policy flag, which
2095 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002096
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002097 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002098 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002099 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2100
2101 // NOTE: We used to read the legacy setting here :
2102 //
2103 // final int legacyFlagValue = Settings.Secure.getInt(
2104 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2105 //
2106 // This is no longer necessary because we will never upgrade directly from Gingerbread
2107 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2108 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002109 }
2110
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002111 /**
2112 * Perform upgrade step of moving any user-defined meterness overrides over
2113 * into {@link WifiConfiguration}.
2114 */
2115 private void upgradeWifiMeteredOverrideAL() {
2116 boolean modified = false;
2117 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2118 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2119 for (int i = 0; i < mNetworkPolicy.size(); ) {
2120 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2121 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2122 && !policy.inferred) {
2123 mNetworkPolicy.removeAt(i);
2124 modified = true;
2125
2126 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2127 for (WifiConfiguration config : configs) {
2128 if (Objects.equals(resolveNetworkId(config), networkId)) {
2129 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2130 config.meteredOverride = policy.metered
2131 ? WifiConfiguration.METERED_OVERRIDE_METERED
2132 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2133 wm.updateNetwork(config);
2134 }
2135 }
2136 } else {
2137 i++;
2138 }
2139 }
2140 if (modified) {
2141 writePolicyAL();
2142 }
2143 }
2144
Felipe Lemef0823852016-06-08 13:43:08 -07002145 void writePolicyAL() {
2146 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002147
2148 FileOutputStream fos = null;
2149 try {
2150 fos = mPolicyFile.startWrite();
2151
2152 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002153 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002154 out.startDocument(null, true);
2155
2156 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002157 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002158 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159
2160 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002161 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2162 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002163 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002164 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002165
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002166 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002167 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2168 final String subscriberId = template.getSubscriberId();
2169 if (subscriberId != null) {
2170 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002172 final String networkId = template.getNetworkId();
2173 if (networkId != null) {
2174 out.attribute(null, ATTR_NETWORK_ID, networkId);
2175 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002176 writeStringAttribute(out, ATTR_CYCLE_START,
2177 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2178 writeStringAttribute(out, ATTR_CYCLE_END,
2179 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2180 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2181 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002182 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2183 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002184 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2185 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002186 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002187 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002188 out.endTag(null, TAG_NETWORK_POLICY);
2189 }
2190
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002191 // write all known subscription plans
2192 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2193 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002194 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002195 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2196 if (ArrayUtils.isEmpty(plans)) continue;
2197
2198 for (SubscriptionPlan plan : plans) {
2199 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2200 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002201 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002202 final RecurrenceRule cycleRule = plan.getCycleRule();
2203 writeStringAttribute(out, ATTR_CYCLE_START,
2204 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2205 writeStringAttribute(out, ATTR_CYCLE_END,
2206 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2207 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2208 RecurrenceRule.convertPeriod(cycleRule.period));
2209 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2210 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2211 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2212 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2213 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2214 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2215 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2216 }
2217 }
2218
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002219 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002220 for (int i = 0; i < mUidPolicy.size(); i++) {
2221 final int uid = mUidPolicy.keyAt(i);
2222 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002223
Jeff Sharkey497e4432011-06-14 17:27:29 -07002224 // skip writing empty policies
2225 if (policy == POLICY_NONE) continue;
2226
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002227 out.startTag(null, TAG_UID_POLICY);
2228 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002229 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002230 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002231 }
2232
2233 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002234
2235 // write all whitelists
2236 out.startTag(null, TAG_WHITELIST);
2237
Felipe Lemea9505cc2016-02-26 10:28:41 -08002238 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002239 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002240 for (int i = 0; i < size; i++) {
2241 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2242 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2243 writeIntAttribute(out, ATTR_UID, uid);
2244 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2245 }
2246
Felipe Lemeb85a6372016-01-14 16:16:16 -08002247 out.endTag(null, TAG_WHITELIST);
2248
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002249 out.endDocument();
2250
2251 mPolicyFile.finishWrite(fos);
2252 } catch (IOException e) {
2253 if (fos != null) {
2254 mPolicyFile.failWrite(fos);
2255 }
2256 }
2257 }
2258
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002259 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002260 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002261 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002262
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002263 if (!UserHandle.isApp(uid)) {
2264 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002265 }
Felipe Lemef0823852016-06-08 13:43:08 -07002266 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002267 final long token = Binder.clearCallingIdentity();
2268 try {
2269 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2270 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002271 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002272 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002273 }
2274 } finally {
2275 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002276 }
2277 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002278 }
2279
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002280 @Override
2281 public void addUidPolicy(int uid, int policy) {
2282 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002283
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002284 if (!UserHandle.isApp(uid)) {
2285 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2286 }
2287
Felipe Lemef0823852016-06-08 13:43:08 -07002288 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002289 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2290 policy |= oldPolicy;
2291 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002292 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002293 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002294 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002295 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002296 }
2297
2298 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002299 public void removeUidPolicy(int uid, int policy) {
2300 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2301
2302 if (!UserHandle.isApp(uid)) {
2303 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2304 }
2305
Felipe Lemef0823852016-06-08 13:43:08 -07002306 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002307 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2308 policy = oldPolicy & ~policy;
2309 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002310 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002311 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002312 }
2313 }
2314 }
2315
Felipe Lemef0823852016-06-08 13:43:08 -07002316 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2317 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002318
Felipe Leme57e3d312016-08-23 14:42:52 -07002319 final boolean notifyApp;
2320 if (!isUidValidForWhitelistRules(uid)) {
2321 notifyApp = false;
2322 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002323 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2324 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2325 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2326 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002327 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2328 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002329 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2330 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2331 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2332 if (LOGD)
2333 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2334 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2335 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002336 notifyApp = wasBlocked != isBlocked;
2337 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002338 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2339 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002340 }
2341
Felipe Lemef0823852016-06-08 13:43:08 -07002342 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002343 if (policy == POLICY_NONE) {
2344 mUidPolicy.delete(uid);
2345 } else {
2346 mUidPolicy.put(uid, policy);
2347 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002348
2349 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002350 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002351 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002352 synchronized (mNetworkPoliciesSecondLock) {
2353 writePolicyAL();
2354 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002355 }
2356 }
2357
2358 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002359 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002360 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2361
Felipe Lemef0823852016-06-08 13:43:08 -07002362 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002363 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002364 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002365 }
2366
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002367 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002368 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002369 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2370
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002371 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002372 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002373 for (int i = 0; i < mUidPolicy.size(); i++) {
2374 final int uid = mUidPolicy.keyAt(i);
2375 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002376 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2377 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002378 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002379 }
2380 }
2381 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002382 return uids;
2383 }
2384
2385 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002386 * Removes any persistable state associated with given {@link UserHandle}, persisting
2387 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002388 */
Felipe Lemef0823852016-06-08 13:43:08 -07002389 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002390
Sudheer Shanka352dc572017-09-22 17:09:38 -07002391 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002392 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002393
Felipe Lemea110eec2016-04-29 09:58:06 -07002394 // Remove entries from revoked default restricted background UID whitelist
2395 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2396 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2397 if (UserHandle.getUserId(uid) == userId) {
2398 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002399 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002400 }
2401 }
2402
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002403 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002404 int[] uids = new int[0];
2405 for (int i = 0; i < mUidPolicy.size(); i++) {
2406 final int uid = mUidPolicy.keyAt(i);
2407 if (UserHandle.getUserId(uid) == userId) {
2408 uids = appendInt(uids, uid);
2409 }
2410 }
2411
2412 if (uids.length > 0) {
2413 for (int uid : uids) {
2414 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002415 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002416 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002417 }
Felipe Lemef0823852016-06-08 13:43:08 -07002418 synchronized (mNetworkPoliciesSecondLock) {
2419 updateRulesForGlobalChangeAL(true);
2420 if (writePolicy && changed) {
2421 writePolicyAL();
2422 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002423 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002424 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002425 }
2426
2427 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002428 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002429 // TODO: create permission for observing network policy
2430 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002431 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002432 }
2433
2434 @Override
2435 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002436 // TODO: create permission for observing network policy
2437 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002438 mListeners.unregister(listener);
2439 }
2440
Jeff Sharkey1b861272011-05-22 00:34:52 -07002441 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002442 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002443 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2444
Felipe Leme6a05eee2016-02-19 14:43:51 -08002445 final long token = Binder.clearCallingIdentity();
2446 try {
2447 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002448 synchronized (mUidRulesFirstLock) {
2449 synchronized (mNetworkPoliciesSecondLock) {
2450 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002451 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002452 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002453 }
2454 } finally {
2455 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002456 }
2457 }
2458
Hugo Benichi446c9c92017-04-10 09:41:10 +09002459 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002460 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002461 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2462 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002463 }
2464
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002465 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002466 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002467 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002468 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002469 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2470 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2471 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002472 } catch (SecurityException e) {
2473 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002474
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002475 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2476 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2477 return new NetworkPolicy[0];
2478 }
Svet Ganov16a16892015-04-16 10:32:04 -07002479 }
2480
Felipe Lemef0823852016-06-08 13:43:08 -07002481 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002482 final int size = mNetworkPolicy.size();
2483 final NetworkPolicy[] policies = new NetworkPolicy[size];
2484 for (int i = 0; i < size; i++) {
2485 policies[i] = mNetworkPolicy.valueAt(i);
2486 }
2487 return policies;
2488 }
2489 }
2490
Felipe Lemef0823852016-06-08 13:43:08 -07002491 private void normalizePoliciesNL() {
2492 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002493 }
2494
Felipe Lemef0823852016-06-08 13:43:08 -07002495 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002496 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002497 final String[] merged = tele.getMergedSubscriberIds();
2498
2499 mNetworkPolicy.clear();
2500 for (NetworkPolicy policy : policies) {
2501 // When two normalized templates conflict, prefer the most
2502 // restrictive policy
2503 policy.template = NetworkTemplate.normalize(policy.template, merged);
2504 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2505 if (existing == null || existing.compareTo(policy) > 0) {
2506 if (existing != null) {
2507 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2508 }
2509 mNetworkPolicy.put(policy.template, policy);
2510 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002511 }
2512 }
2513
2514 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002515 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002516 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002517
2518 final long token = Binder.clearCallingIdentity();
2519 try {
2520 performSnooze(template, TYPE_LIMIT);
2521 } finally {
2522 Binder.restoreCallingIdentity(token);
2523 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002524 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002525
Dianne Hackborn497175b2014-07-01 12:56:08 -07002526 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002527 maybeRefreshTrustedTime();
2528 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002529 synchronized (mUidRulesFirstLock) {
2530 synchronized (mNetworkPoliciesSecondLock) {
2531 // find and snooze local policy that matches
2532 final NetworkPolicy policy = mNetworkPolicy.get(template);
2533 if (policy == null) {
2534 throw new IllegalArgumentException("unable to find policy for " + template);
2535 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002536
Felipe Lemef0823852016-06-08 13:43:08 -07002537 switch (type) {
2538 case TYPE_WARNING:
2539 policy.lastWarningSnooze = currentTime;
2540 break;
2541 case TYPE_LIMIT:
2542 policy.lastLimitSnooze = currentTime;
2543 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002544 case TYPE_RAPID:
2545 policy.lastRapidSnooze = currentTime;
2546 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002547 default:
2548 throw new IllegalArgumentException("unexpected type");
2549 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002550
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002551 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002552 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002553 }
2554 }
2555
2556 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002557 public void onTetheringChanged(String iface, boolean tethering) {
2558 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002559 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002560 if (mRestrictBackground && tethering) {
2561 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2562 setRestrictBackground(false);
2563 }
2564 }
2565 }
2566
2567 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002568 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002569 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002570 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002571 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2572 final long token = Binder.clearCallingIdentity();
2573 try {
2574 maybeRefreshTrustedTime();
2575 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002576 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002577 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002578 } finally {
2579 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002580 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002581 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002582 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002583 }
2584 }
2585
Felipe Lemef0823852016-06-08 13:43:08 -07002586 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002587 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002588 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002589 if (restrictBackground == mRestrictBackground) {
2590 // Ideally, UI should never allow this scenario...
2591 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002592 return;
2593 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002594 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2595 final boolean oldRestrictBackground = mRestrictBackground;
2596 mRestrictBackground = restrictBackground;
2597 // Must whitelist foreground apps before turning data saver mode on.
2598 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2599 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2600 updateRulesForRestrictBackgroundUL();
2601 try {
2602 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2603 Slog.e(TAG,
2604 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2605 mRestrictBackground = oldRestrictBackground;
2606 // TODO: if it knew the foreground apps (see TODO above), it could call
2607 // updateRulesForRestrictBackgroundUL() again to restore state.
2608 return;
2609 }
2610 } catch (RemoteException e) {
2611 // ignored; service lives in system_server
2612 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002613
Sudheer Shanka543339f2017-07-28 15:18:07 -07002614 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002615 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002616
2617 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2618 mRestrictBackgroundChangedInBsm = true;
2619 }
2620 synchronized (mNetworkPoliciesSecondLock) {
2621 updateNotificationsNL();
2622 writePolicyAL();
2623 }
2624 } finally {
2625 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002626 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002627 }
2628
2629 private void sendRestrictBackgroundChangedMsg() {
2630 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2631 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2632 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002633 }
2634
Felipe Lemeb85a6372016-01-14 16:16:16 -08002635 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002636 public int getRestrictBackgroundByCaller() {
2637 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2638 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002639
Felipe Lemef0823852016-06-08 13:43:08 -07002640 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002641 // Must clear identity because getUidPolicy() is restricted to system.
2642 final long token = Binder.clearCallingIdentity();
2643 final int policy;
2644 try {
2645 policy = getUidPolicy(uid);
2646 } finally {
2647 Binder.restoreCallingIdentity(token);
2648 }
2649 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2650 // App is blacklisted.
2651 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2652 }
Felipe Leme1b103232016-01-22 09:44:57 -08002653 if (!mRestrictBackground) {
2654 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2655 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002656 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002657 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2658 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2659 }
2660 }
2661
2662 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002663 public boolean getRestrictBackground() {
2664 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2665
Felipe Lemef0823852016-06-08 13:43:08 -07002666 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002667 return mRestrictBackground;
2668 }
2669 }
2670
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002671 @Override
2672 public void setDeviceIdleMode(boolean enabled) {
2673 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002674 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2675 try {
2676 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002677 if (mDeviceIdleMode == enabled) {
2678 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002679 }
Felipe Lemeea014392016-09-06 13:59:54 -07002680 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002681 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002682 if (mSystemReady) {
2683 // Device idle change means we need to rebuild rules for all
2684 // known apps, so do a global refresh.
2685 updateRulesForRestrictPowerUL();
2686 }
2687 }
2688 if (enabled) {
2689 EventLogTags.writeDeviceIdleOnPhase("net");
2690 } else {
2691 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002692 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002693 } finally {
2694 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002695 }
2696 }
2697
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002698 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002699 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2700 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002701 final long token = Binder.clearCallingIdentity();
2702 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002703 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2704 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2705 for (WifiConfiguration config : configs) {
2706 if (Objects.equals(resolveNetworkId(config), networkId)) {
2707 config.meteredOverride = meteredOverride;
2708 wm.updateNetwork(config);
2709 }
2710 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002711 } finally {
2712 Binder.restoreCallingIdentity(token);
2713 }
2714 }
2715
Jeff Sharkey46645002011-07-27 21:11:21 -07002716 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002717 @Deprecated
2718 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2719 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2720 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2721 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002722 }
2723
Jeff Sharkey53313d72017-07-13 16:47:32 -06002724 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2725 // Verify they're not lying about package name
2726 mAppOps.checkPackage(callingUid, callingPackage);
2727
Jeff Sharkey53313d72017-07-13 16:47:32 -06002728 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002729 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002730 final long token = Binder.clearCallingIdentity();
2731 try {
2732 si = mContext.getSystemService(SubscriptionManager.class)
2733 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002734 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002735 } finally {
2736 Binder.restoreCallingIdentity(token);
2737 }
2738
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002739 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002740 if (si != null) {
2741 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2742 return;
2743 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002744 }
2745
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002746 // Second check: has the CarrierService delegated access?
2747 if (config != null) {
2748 final String overridePackage = config
2749 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2750 if (!TextUtils.isEmpty(overridePackage)
2751 && Objects.equals(overridePackage, callingPackage)) {
2752 return;
2753 }
2754 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002755
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002756 // Third check: is caller the fallback/default CarrierService?
2757 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2758 if (!TextUtils.isEmpty(defaultPackage)
2759 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002760 return;
2761 }
2762
Jeff Sharkeya7f50462018-02-14 14:26:10 -07002763 // Fourth check: is caller a testing app on a debug build?
2764 final boolean enableDebug = Build.IS_USERDEBUG || Build.IS_ENG;
2765 if (enableDebug && callingPackage
2766 .equals(SystemProperties.get("fw.sub_plan_owner." + subId, null))) {
2767 return;
2768 }
2769
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002770 // Final check: does the caller hold a permission?
2771 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002772 }
2773
2774 @Override
2775 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2776 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2777
Jeff Sharkey53313d72017-07-13 16:47:32 -06002778 final String fake = SystemProperties.get("fw.fake_plan");
2779 if (!TextUtils.isEmpty(fake)) {
2780 final List<SubscriptionPlan> plans = new ArrayList<>();
2781 if ("month_hard".equals(fake)) {
2782 plans.add(SubscriptionPlan.Builder
2783 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2784 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002785 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2786 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2787 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2788 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2789 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002790 plans.add(SubscriptionPlan.Builder
2791 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2792 .setTitle("G-Mobile Happy")
2793 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2794 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2795 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2796 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2797 .build());
2798 plans.add(SubscriptionPlan.Builder
2799 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2800 .setTitle("G-Mobile, Charged after limit")
2801 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2802 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2803 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2804 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2805 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002806 } else if ("month_soft".equals(fake)) {
2807 plans.add(SubscriptionPlan.Builder
2808 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2809 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2810 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2811 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002812 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2813 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2814 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2815 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2816 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002817 plans.add(SubscriptionPlan.Builder
2818 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2819 .setTitle("G-Mobile, Throttled after limit")
2820 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2821 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2822 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2823 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2824 .build());
2825 plans.add(SubscriptionPlan.Builder
2826 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2827 .setTitle("G-Mobile, No data connection after limit")
2828 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2829 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2830 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2831 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2832 .build());
2833
Jeff Sharkey53313d72017-07-13 16:47:32 -06002834 } else if ("month_none".equals(fake)) {
2835 plans.add(SubscriptionPlan.Builder
2836 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2837 .setTitle("G-Mobile")
2838 .build());
2839 } else if ("prepaid".equals(fake)) {
2840 plans.add(SubscriptionPlan.Builder
2841 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2842 ZonedDateTime.now().plusDays(10))
2843 .setTitle("G-Mobile")
2844 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2845 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2846 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2847 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2848 .build());
2849 } else if ("prepaid_crazy".equals(fake)) {
2850 plans.add(SubscriptionPlan.Builder
2851 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2852 ZonedDateTime.now().plusDays(10))
2853 .setTitle("G-Mobile Anytime")
2854 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2855 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2856 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2857 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2858 .build());
2859 plans.add(SubscriptionPlan.Builder
2860 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2861 ZonedDateTime.now().plusDays(20))
2862 .setTitle("G-Mobile Nickel Nights")
2863 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002864 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2865 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002866 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2867 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2868 .build());
2869 plans.add(SubscriptionPlan.Builder
2870 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2871 ZonedDateTime.now().plusDays(20))
2872 .setTitle("G-Mobile Bonus 3G")
2873 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002874 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002875 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2876 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2877 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2878 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002879 } else if ("unlimited".equals(fake)) {
2880 plans.add(SubscriptionPlan.Builder
2881 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2882 ZonedDateTime.now().plusDays(10))
2883 .setTitle("G-Mobile Awesome")
2884 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2885 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2886 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2887 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2888 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002889 }
2890 return plans.toArray(new SubscriptionPlan[plans.size()]);
2891 }
2892
Jeff Sharkey4635f102017-09-01 11:27:13 -06002893 synchronized (mNetworkPoliciesSecondLock) {
2894 // Only give out plan details to the package that defined them,
2895 // so that we don't risk leaking plans between apps. We always
2896 // let in core system components (like the Settings app).
2897 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2898 if (Objects.equals(ownerPackage, callingPackage)
2899 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2900 return mSubscriptionPlans.get(subId);
2901 } else {
2902 Log.w(TAG, "Not returning plans because caller " + callingPackage
2903 + " doesn't match owner " + ownerPackage);
2904 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002905 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002906 }
2907 }
2908
2909 @Override
2910 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2911 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2912
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002913 for (SubscriptionPlan plan : plans) {
2914 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002915 }
2916
2917 final long token = Binder.clearCallingIdentity();
2918 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002919 maybeRefreshTrustedTime();
2920 synchronized (mUidRulesFirstLock) {
2921 synchronized (mNetworkPoliciesSecondLock) {
2922 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002923 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002924
2925 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2926 .getSubscriberId(subId);
2927 ensureActiveMobilePolicyAL(subId, subscriberId);
2928 maybeUpdateMobilePolicyCycleAL(subId);
2929 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002930 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002931 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002932
2933 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2934 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2935 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2936 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002937 } finally {
2938 Binder.restoreCallingIdentity(token);
2939 }
2940 }
2941
2942 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002943 public String getSubscriptionPlansOwner(int subId) {
2944 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2945 throw new SecurityException();
2946 }
2947
2948 synchronized (mNetworkPoliciesSecondLock) {
2949 return mSubscriptionPlansOwner.get(subId);
2950 }
2951 }
2952
2953 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09002954 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
2955 long timeoutMillis, String callingPackage) {
2956 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2957
2958 // We can only override when carrier told us about plans
2959 synchronized (mNetworkPoliciesSecondLock) {
2960 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
2961 throw new IllegalStateException(
2962 "Must provide SubscriptionPlan information before overriding");
2963 }
2964 }
2965
2966 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2967 overrideMask, overrideValue, subId));
2968 if (timeoutMillis > 0) {
2969 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2970 overrideMask, 0, subId), timeoutMillis);
2971 }
2972 }
2973
2974 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002975 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002976 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002977
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002978 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2979
Dianne Hackborn497175b2014-07-01 12:56:08 -07002980 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002981 for (String arg : args) {
2982 argSet.add(arg);
2983 }
2984
Felipe Lemef0823852016-06-08 13:43:08 -07002985 synchronized (mUidRulesFirstLock) {
2986 synchronized (mNetworkPoliciesSecondLock) {
2987 if (argSet.contains("--unsnooze")) {
2988 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2989 mNetworkPolicy.valueAt(i).clearSnooze();
2990 }
2991
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002992 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002993
2994 fout.println("Cleared snooze timestamps");
2995 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002996 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002997
Felipe Lemef0823852016-06-08 13:43:08 -07002998 fout.print("System ready: "); fout.println(mSystemReady);
2999 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3000 fout.print("Restrict power: "); fout.println(mRestrictPower);
3001 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003002 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3003
3004 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003005 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003006 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003007 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3008 fout.println(mNetworkPolicy.valueAt(i).toString());
3009 }
3010 fout.decreaseIndent();
3011
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003012 fout.println();
3013 fout.println("Subscription plans:");
3014 fout.increaseIndent();
3015 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3016 final int subId = mSubscriptionPlans.keyAt(i);
3017 fout.println("Subscriber ID " + subId + ":");
3018 fout.increaseIndent();
3019 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3020 if (!ArrayUtils.isEmpty(plans)) {
3021 for (SubscriptionPlan plan : plans) {
3022 fout.println(plan);
3023 }
3024 }
3025 fout.decreaseIndent();
3026 }
3027 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003028
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003029 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003030 fout.println("Policy for UIDs:");
3031 fout.increaseIndent();
3032 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003033 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003034 final int uid = mUidPolicy.keyAt(i);
3035 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003036 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003037 fout.print(uid);
3038 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003039 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003040 fout.println();
3041 }
3042 fout.decreaseIndent();
3043
3044 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3045 if (size > 0) {
3046 fout.println("Power save whitelist (except idle) app ids:");
3047 fout.increaseIndent();
3048 for (int i = 0; i < size; i++) {
3049 fout.print("UID=");
3050 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3051 fout.print(": ");
3052 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3053 fout.println();
3054 }
3055 fout.decreaseIndent();
3056 }
3057
3058 size = mPowerSaveWhitelistAppIds.size();
3059 if (size > 0) {
3060 fout.println("Power save whitelist app ids:");
3061 fout.increaseIndent();
3062 for (int i = 0; i < size; i++) {
3063 fout.print("UID=");
3064 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3065 fout.print(": ");
3066 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3067 fout.println();
3068 }
3069 fout.decreaseIndent();
3070 }
3071
Felipe Lemef0823852016-06-08 13:43:08 -07003072 size = mDefaultRestrictBackgroundWhitelistUids.size();
3073 if (size > 0) {
3074 fout.println("Default restrict background whitelist uids:");
3075 fout.increaseIndent();
3076 for (int i = 0; i < size; i++) {
3077 fout.print("UID=");
3078 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3079 fout.println();
3080 }
3081 fout.decreaseIndent();
3082 }
3083
3084 size = mRestrictBackgroundWhitelistRevokedUids.size();
3085 if (size > 0) {
3086 fout.println("Default restrict background whitelist uids revoked by users:");
3087 fout.increaseIndent();
3088 for (int i = 0; i < size; i++) {
3089 fout.print("UID=");
3090 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3091 fout.println();
3092 }
3093 fout.decreaseIndent();
3094 }
3095
3096 final SparseBooleanArray knownUids = new SparseBooleanArray();
3097 collectKeys(mUidState, knownUids);
3098 collectKeys(mUidRules, knownUids);
3099
3100 fout.println("Status for all known UIDs:");
3101 fout.increaseIndent();
3102 size = knownUids.size();
3103 for (int i = 0; i < size; i++) {
3104 final int uid = knownUids.keyAt(i);
3105 fout.print("UID=");
3106 fout.print(uid);
3107
3108 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3109 fout.print(" state=");
3110 fout.print(state);
3111 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3112 fout.print(" (fg)");
3113 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003114 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003115 ? " (fg svc)" : " (bg)");
3116 }
3117
3118 final int uidRules = mUidRules.get(uid, RULE_NONE);
3119 fout.print(" rules=");
3120 fout.print(uidRulesToString(uidRules));
3121 fout.println();
3122 }
3123 fout.decreaseIndent();
3124
3125 fout.println("Status for just UIDs with rules:");
3126 fout.increaseIndent();
3127 size = mUidRules.size();
3128 for (int i = 0; i < size; i++) {
3129 final int uid = mUidRules.keyAt(i);
3130 fout.print("UID=");
3131 fout.print(uid);
3132 final int uidRules = mUidRules.get(uid, RULE_NONE);
3133 fout.print(" rules=");
3134 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003135 fout.println();
3136 }
3137 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003138
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003139 fout.println("Admin restricted uids for metered data:");
3140 fout.increaseIndent();
3141 size = mMeteredRestrictedUids.size();
3142 for (int i = 0; i < size; ++i) {
3143 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3144 fout.println(mMeteredRestrictedUids.valueAt(i));
3145 }
3146 fout.decreaseIndent();
3147
Sudheer Shanka352dc572017-09-22 17:09:38 -07003148 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003149 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003150 }
3151 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003152
3153 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003154 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003155 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003156 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003157 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003158 }
3159
3160 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003161 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003162 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3163
Felipe Lemef0823852016-06-08 13:43:08 -07003164 synchronized (mUidRulesFirstLock) {
3165 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003166 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003167 }
3168
Felipe Lemef0823852016-06-08 13:43:08 -07003169 private boolean isUidForegroundUL(int uid) {
3170 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003171 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3172 }
3173
Felipe Lemef0823852016-06-08 13:43:08 -07003174 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003175 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003176 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003177 }
3178
Felipe Lemef0823852016-06-08 13:43:08 -07003179 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003180 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3181 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3182 }
3183
Felipe Lemef0823852016-06-08 13:43:08 -07003184 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003185 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003186 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003187 }
3188
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003189 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003190 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003191 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3192 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003193 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003194 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003195 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3196 try {
3197 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3198 if (oldUidState != uidState) {
3199 // state changed, push updated rules
3200 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003201 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3202 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3203 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003204 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003205 if (mDeviceIdleMode) {
3206 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003207 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003208 if (mRestrictPower) {
3209 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003210 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003211 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003212 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003213 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003214 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003215 } finally {
3216 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003217 }
3218 }
3219
Felipe Lemef0823852016-06-08 13:43:08 -07003220 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003221 final int index = mUidState.indexOfKey(uid);
3222 if (index >= 0) {
3223 final int oldUidState = mUidState.valueAt(index);
3224 mUidState.removeAt(index);
3225 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003226 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003227 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003228 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003229 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003230 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003231 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003232 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003233 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003234 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003235 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003236 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003237 }
3238 }
3239
Felipe Lemef28983d2016-03-25 12:18:23 -07003240 // adjust stats accounting based on foreground status
3241 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003242 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3243 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3244 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3245 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003246 try {
3247 mNetworkStats.setUidForeground(uid, uidForeground);
3248 } catch (RemoteException e) {
3249 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003250 } finally {
3251 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003252 }
3253 }
3254
Sudheer Shankac9d94072017-02-22 22:13:55 +00003255 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3256 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003257 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003258 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003259 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003260 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003261 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003262 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003263 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003264 }
3265
Felipe Lemef0823852016-06-08 13:43:08 -07003266 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003267 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3268 try {
3269 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3270 mUidFirewallPowerSaveRules);
3271 } finally {
3272 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3273 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003274 }
3275
Felipe Lemef0823852016-06-08 13:43:08 -07003276 void updateRuleForRestrictPowerUL(int uid) {
3277 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003278 }
3279
Felipe Lemef0823852016-06-08 13:43:08 -07003280 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003281 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3282 try {
3283 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3284 mUidFirewallDozableRules);
3285 } finally {
3286 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3287 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003288 }
3289
Felipe Lemef0823852016-06-08 13:43:08 -07003290 void updateRuleForDeviceIdleUL(int uid) {
3291 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003292 }
3293
Felipe Lemef28983d2016-03-25 12:18:23 -07003294 // NOTE: since both fw_dozable and fw_powersave uses the same map
3295 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003296 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003297 SparseIntArray rules) {
3298 if (enabled) {
3299 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003300 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003301 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003302 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003303 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003304 for (int ui = users.size() - 1; ui >= 0; ui--) {
3305 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003306 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3307 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3308 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3309 updateRulesForWhitelistedAppIds(uidRules,
3310 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003311 }
3312 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003313 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003314 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003315 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3316 }
3317 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003318 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003319 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003320 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003321 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003322 }
3323
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003324 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3325 final SparseBooleanArray whitelistedAppIds, int userId) {
3326 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3327 if (whitelistedAppIds.valueAt(i)) {
3328 final int appId = whitelistedAppIds.keyAt(i);
3329 final int uid = UserHandle.getUid(userId, appId);
3330 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3331 }
3332 }
3333 }
3334
3335 /**
3336 * @param deviceIdleMode if true then we don't consider
3337 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3338 * whitelisted.
3339 */
3340 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003341 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003342 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3343 || mPowerSaveWhitelistAppIds.get(appId);
3344 if (!deviceIdleMode) {
3345 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3346 }
3347 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003348 }
3349
Felipe Lemef28983d2016-03-25 12:18:23 -07003350 // NOTE: since both fw_dozable and fw_powersave uses the same map
3351 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003352 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003353 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003354 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3355 chain == FIREWALL_CHAIN_DOZABLE);
3356 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003357 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003358 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003359 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003360 }
3361 }
3362 }
3363
Felipe Lemef0823852016-06-08 13:43:08 -07003364 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003365 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3366 try {
3367 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3368 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003369
Felipe Leme873a83a2016-09-07 11:34:10 -07003370 // Fully update the app idle firewall chain.
3371 final List<UserInfo> users = mUserManager.getUsers();
3372 for (int ui = users.size() - 1; ui >= 0; ui--) {
3373 UserInfo user = users.get(ui);
3374 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3375 for (int uid : idleUids) {
3376 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3377 // quick check: if this uid doesn't have INTERNET permission, it
3378 // doesn't have network access anyway, so it is a waste to mess
3379 // with it here.
3380 if (hasInternetPermissions(uid)) {
3381 uidRules.put(uid, FIREWALL_RULE_DENY);
3382 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003383 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003384 }
3385 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003386
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003387 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003388 } finally {
3389 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3390 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003391 }
3392
Felipe Lemef0823852016-06-08 13:43:08 -07003393 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003394 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003395
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003396 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3397 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3398 }
3399 try {
3400 int appId = UserHandle.getAppId(uid);
3401 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3402 && !isUidForegroundOnRestrictPowerUL(uid)) {
3403 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3404 } else {
3405 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3406 }
3407 } finally {
3408 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003409 }
3410 }
3411
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003412 /**
3413 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3414 * changed.
3415 */
Felipe Lemef0823852016-06-08 13:43:08 -07003416 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003417 boolean paroled = mUsageStats.isAppIdleParoleOn();
3418 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003419 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003420
3421 int ruleCount = mUidFirewallStandbyRules.size();
3422 for (int i = 0; i < ruleCount; i++) {
3423 int uid = mUidFirewallStandbyRules.keyAt(i);
3424 int oldRules = mUidRules.get(uid);
3425 if (enableChain) {
3426 // Chain wasn't enabled before and the other power-related
3427 // chains are whitelists, so we can clear the
3428 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3429 // the effective rules result in blocking network access.
3430 oldRules &= MASK_METERED_NETWORKS;
3431 } else {
3432 // Skip if it had no restrictions to begin with
3433 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3434 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003435 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3436 if (newUidRules == RULE_NONE) {
3437 mUidRules.delete(uid);
3438 } else {
3439 mUidRules.put(uid, newUidRules);
3440 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003441 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003442 }
3443
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003444 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003445 * Update rules that might be changed by {@link #mRestrictBackground},
3446 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003447 */
Felipe Lemef0823852016-06-08 13:43:08 -07003448 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003449 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3450 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3451 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3452 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003453 try {
Felipe Leme09700462016-09-08 09:33:48 -07003454 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003455 updateRulesForRestrictPowerUL();
3456 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003457
Felipe Leme873a83a2016-09-07 11:34:10 -07003458 // If the set of restricted networks may have changed, re-evaluate those.
3459 if (restrictedNetworksChanged) {
3460 normalizePoliciesNL();
3461 updateNetworkRulesNL();
3462 }
3463 } finally {
3464 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003465 }
3466 }
3467
Felipe Leme09700462016-09-08 09:33:48 -07003468 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003469 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003470 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3471 try {
3472 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003473 updateRulesForPowerSaveUL();
3474 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3475 } finally {
3476 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3477 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003478 }
3479
Felipe Lemef0823852016-06-08 13:43:08 -07003480 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003481 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3482 try {
3483 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3484 } finally {
3485 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3486 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003487 }
3488
3489 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3490 private static final int TYPE_RESTRICT_POWER = 2;
3491 @Retention(RetentionPolicy.SOURCE)
3492 @IntDef(flag = false, value = {
3493 TYPE_RESTRICT_BACKGROUND,
3494 TYPE_RESTRICT_POWER,
3495 })
3496 public @interface RestrictType {
3497 }
3498
3499 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003500 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003501 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3502 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3503 }
3504 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003505 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003506
3507 final PackageManager pm = mContext.getPackageManager();
3508 final List<UserInfo> users;
3509 final List<ApplicationInfo> apps;
3510
3511 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3512 try {
3513 users = mUserManager.getUsers();
3514 } finally {
3515 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3516 }
3517 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3518 try {
3519 apps = pm.getInstalledApplications(
3520 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3521 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3522 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3523 } finally {
3524 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3525 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003526
Felipe Leme873a83a2016-09-07 11:34:10 -07003527 final int usersSize = users.size();
3528 final int appsSize = apps.size();
3529 for (int i = 0; i < usersSize; i++) {
3530 final UserInfo user = users.get(i);
3531 for (int j = 0; j < appsSize; j++) {
3532 final ApplicationInfo app = apps.get(j);
3533 final int uid = UserHandle.getUid(user.id, app.uid);
3534 switch (type) {
3535 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003536 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003537 break;
3538 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003539 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003540 break;
3541 default:
3542 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3543 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003544 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003545 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003546 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003547 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003548 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003549 }
3550
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003551 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003552 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003553 final int numUsers = users.size();
3554 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003555 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003556 int uid = UserHandle.getUid(user.id, appId);
3557 // Update external firewall rules.
3558 updateRuleForAppIdleUL(uid);
3559 updateRuleForDeviceIdleUL(uid);
3560 updateRuleForRestrictPowerUL(uid);
3561 // Update internal rules.
3562 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003563 }
3564 }
3565
Felipe Leme70c57c22016-03-29 10:45:13 -07003566 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3567 // methods below could be merged into a isUidValidForRules() method.
3568 private boolean isUidValidForBlacklistRules(int uid) {
3569 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003570 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003571 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003572 return true;
3573 }
3574
3575 return false;
3576 }
3577
Felipe Leme70c57c22016-03-29 10:45:13 -07003578 private boolean isUidValidForWhitelistRules(int uid) {
3579 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3580 }
3581
Amith Yamasani15e472352015-04-24 19:06:07 -07003582 private boolean isUidIdle(int uid) {
3583 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3584 final int userId = UserHandle.getUserId(uid);
3585
songjinshi0655edd2016-05-18 19:55:32 +08003586 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003587 for (String packageName : packages) {
3588 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3589 return false;
3590 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003591 }
3592 }
3593 return true;
3594 }
3595
3596 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003597 * Checks if an uid has INTERNET permissions.
3598 * <p>
3599 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003600 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003601 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003602 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003603 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003604 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003605 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003606 }
3607 } catch (RemoteException e) {
3608 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003609 return true;
3610 }
3611
3612 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003613 * Clears all state - internal and external - associated with an UID.
3614 */
3615 private void onUidDeletedUL(int uid) {
3616 // First cleanup in-memory state synchronously...
3617 mUidRules.delete(uid);
3618 mUidPolicy.delete(uid);
3619 mUidFirewallStandbyRules.delete(uid);
3620 mUidFirewallDozableRules.delete(uid);
3621 mUidFirewallPowerSaveRules.delete(uid);
3622 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3623 mPowerSaveWhitelistAppIds.delete(uid);
3624 mPowerSaveTempWhitelistAppIds.delete(uid);
3625
3626 // ...then update iptables asynchronously.
3627 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3628 }
3629
3630 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003631 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003632 *
Felipe Leme781ba142016-05-09 16:24:48 -07003633 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003634 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003635 * <li>Doze mode
3636 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003637 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003638 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003639 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003640 *
3641 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003642 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003643 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003644 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003645 updateRuleForDeviceIdleUL(uid);
3646 updateRuleForAppIdleUL(uid);
3647 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003648
3649 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003650 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003651
3652 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003653 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003654 }
3655
Felipe Leme70c57c22016-03-29 10:45:13 -07003656 /**
3657 * Applies network rules to bandwidth controllers based on process state and user-defined
3658 * restrictions (blacklist / whitelist).
3659 *
3660 * <p>
3661 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3662 * networks:
3663 * <ul>
3664 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3665 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3666 * also blacklisted.
3667 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3668 * no UIDs other those whitelisted will have access.
3669 * <ul>
3670 *
3671 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3672 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3673 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3674 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003675 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003676 * {@link INetworkManagementService}, but this method should also be called in events (like
3677 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3678 * following rules should also be applied:
3679 *
3680 * <ul>
3681 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3682 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3683 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3684 * {@code bw_penalty_box}.
3685 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3686 * </ul>
3687 *
3688 * <p>For optimization, the rules are only applied on user apps that have internet access
3689 * permission, since there is no need to change the {@code iptables} rule if the app does not
3690 * have permission to use the internet.
3691 *
3692 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003693 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003694 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003695 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003696 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3697 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3698 "updateRulesForDataUsageRestrictionsUL: " + uid);
3699 }
3700 try {
3701 updateRulesForDataUsageRestrictionsULInner(uid);
3702 } finally {
3703 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3704 }
3705 }
3706
3707 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003708 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003709 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003710 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003711 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003712
Dianne Hackborn497175b2014-07-01 12:56:08 -07003713 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003714 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003715 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003716 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003717
Felipe Leme781ba142016-05-09 16:24:48 -07003718 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003719 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003720 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3721 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003722
Felipe Leme70c57c22016-03-29 10:45:13 -07003723 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003724 if (isRestrictedByAdmin) {
3725 newRule = RULE_REJECT_METERED;
3726 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003727 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3728 newRule = RULE_TEMPORARY_ALLOW_METERED;
3729 } else if (isWhitelisted) {
3730 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003731 }
3732 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003733 if (isBlacklisted) {
3734 newRule = RULE_REJECT_METERED;
3735 } else if (mRestrictBackground && isWhitelisted) {
3736 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003737 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003738 }
Felipe Leme781ba142016-05-09 16:24:48 -07003739 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003740
Felipe Lemef28983d2016-03-25 12:18:23 -07003741 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003742 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003743 + ": isForeground=" +isForeground
3744 + ", isBlacklisted=" + isBlacklisted
3745 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003746 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003747 + ", oldRule=" + uidRulesToString(oldRule)
3748 + ", newRule=" + uidRulesToString(newRule)
3749 + ", newUidRules=" + uidRulesToString(newUidRules)
3750 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003751 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003752
Felipe Leme46c4fc32016-05-04 09:21:43 -07003753 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003754 mUidRules.delete(uid);
3755 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003756 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003757 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003758
Felipe Leme70c57c22016-03-29 10:45:13 -07003759 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003760 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003761 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003762 // Temporarily whitelist foreground app, removing from blacklist if necessary
3763 // (since bw_penalty_box prevails over bw_happy_box).
3764
3765 setMeteredNetworkWhitelist(uid, true);
3766 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3767 // but ideally it should be just:
3768 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003769 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003770 setMeteredNetworkBlacklist(uid, false);
3771 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003772 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003773 // Remove temporary whitelist from app that is not on foreground anymore.
3774
3775 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3776 // but ideally they should be just:
3777 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3778 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003779 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003780 setMeteredNetworkWhitelist(uid, false);
3781 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003782 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003783 setMeteredNetworkBlacklist(uid, true);
3784 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003785 } else if (hasRule(newRule, RULE_REJECT_METERED)
3786 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003787 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003788 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003789 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003790 // Since blacklist prevails over whitelist, we need to handle the special case
3791 // where app is whitelisted and blacklisted at the same time (although such
3792 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003793 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003794 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003795 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3796 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003797 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003798 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003799 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003800 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003801 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3802 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003803 + ", whitelisted=" + isWhitelisted
3804 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003805 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003806 + ", newRule=" + uidRulesToString(newUidRules)
3807 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003808 }
Felipe Leme781ba142016-05-09 16:24:48 -07003809
Sudheer Shankac9d94072017-02-22 22:13:55 +00003810 // Dispatch changed rule to existing listeners.
3811 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003812 }
3813 }
3814
3815 /**
3816 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3817 * listeners in case of change.
3818 * <p>
3819 * There are 3 power-related rules that affects whether an app has background access on
3820 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3821 * restriction, it's added to the equivalent firewall chain:
3822 * <ul>
3823 * <li>App is idle: {@code fw_standby} firewall chain.
3824 * <li>Device is idle: {@code fw_dozable} firewall chain.
3825 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3826 * </ul>
3827 * <p>
3828 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3829 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3830 * <p>
3831 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3832 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003833 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003834 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3835
Sudheer Shankac9d94072017-02-22 22:13:55 +00003836 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003837
Sudheer Shankac9d94072017-02-22 22:13:55 +00003838 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003839 mUidRules.delete(uid);
3840 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003841 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003842 }
3843 }
3844
3845 /**
3846 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3847 *
3848 * @param uid the uid of the app to update rules for
3849 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3850 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3851 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003852 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003853 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003854 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003855 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3856 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3857 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3858 + (paroled ? "P" : "-"));
3859 }
3860 try {
3861 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3862 } finally {
3863 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3864 }
3865 }
3866
3867 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003868 if (!isUidValidForBlacklistRules(uid)) {
3869 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003870 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003871 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003872
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003873 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003874 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003875 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003876
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003877 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003878 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3879 int newRule = RULE_NONE;
3880
3881 // First step: define the new rule based on user restrictions and foreground state.
3882
3883 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3884 // by considering the foreground and non-foreground states.
3885 if (isForeground) {
3886 if (restrictMode) {
3887 newRule = RULE_ALLOW_ALL;
3888 }
3889 } else if (restrictMode) {
3890 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3891 }
3892
3893 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3894
3895 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003896 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003897 + ", isIdle: " + isIdle
3898 + ", mRestrictPower: " + mRestrictPower
3899 + ", mDeviceIdleMode: " + mDeviceIdleMode
3900 + ", isForeground=" + isForeground
3901 + ", isWhitelisted=" + isWhitelisted
3902 + ", oldRule=" + uidRulesToString(oldRule)
3903 + ", newRule=" + uidRulesToString(newRule)
3904 + ", newUidRules=" + uidRulesToString(newUidRules)
3905 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3906 }
3907
Felipe Leme781ba142016-05-09 16:24:48 -07003908 // Second step: notify listeners if state changed.
3909 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003910 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003911 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003912 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003913 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3914 } else {
3915 // All scenarios should have been covered above
3916 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3917 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003918 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003919 + ", newRule=" + uidRulesToString(newUidRules)
3920 + ", oldRule=" + uidRulesToString(oldUidRules));
3921 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003922 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003923 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003924
Sudheer Shankac9d94072017-02-22 22:13:55 +00003925 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003926 }
3927
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003928 private class AppIdleStateChangeListener
3929 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3930
3931 @Override
Amith Yamasani84cd7b72017-11-07 13:59:37 -08003932 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003933 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003934 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3935 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003936 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003937 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003938 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003939 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003940 }
3941 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003942 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003943 }
3944
3945 @Override
3946 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003947 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003948 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003949 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003950 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003951 }
3952 }
3953
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003954 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3955 if (listener != null) {
3956 try {
3957 listener.onUidRulesChanged(uid, uidRules);
3958 } catch (RemoteException ignored) {
3959 }
3960 }
3961 }
3962
3963 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3964 String[] meteredIfaces) {
3965 if (listener != null) {
3966 try {
3967 listener.onMeteredIfacesChanged(meteredIfaces);
3968 } catch (RemoteException ignored) {
3969 }
3970 }
3971 }
3972
3973 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3974 boolean restrictBackground) {
3975 if (listener != null) {
3976 try {
3977 listener.onRestrictBackgroundChanged(restrictBackground);
3978 } catch (RemoteException ignored) {
3979 }
3980 }
3981 }
3982
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003983 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3984 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003985 if (listener != null) {
3986 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003987 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003988 } catch (RemoteException ignored) {
3989 }
3990 }
3991 }
3992
Jeff Sharkey9252b342018-01-19 07:58:35 +09003993 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
3994 int overrideMask, int overrideValue) {
3995 if (listener != null) {
3996 try {
3997 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
3998 } catch (RemoteException ignored) {
3999 }
4000 }
4001 }
4002
Makoto Onuki8e777332017-03-28 11:25:47 -07004003 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004004 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004005 public boolean handleMessage(Message msg) {
4006 switch (msg.what) {
4007 case MSG_RULES_CHANGED: {
4008 final int uid = msg.arg1;
4009 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004010 final int length = mListeners.beginBroadcast();
4011 for (int i = 0; i < length; i++) {
4012 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4013 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004014 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004015 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004016 return true;
4017 }
4018 case MSG_METERED_IFACES_CHANGED: {
4019 final String[] meteredIfaces = (String[]) msg.obj;
4020 final int length = mListeners.beginBroadcast();
4021 for (int i = 0; i < length; i++) {
4022 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004023 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004024 }
4025 mListeners.finishBroadcast();
4026 return true;
4027 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004028 case MSG_LIMIT_REACHED: {
4029 final String iface = (String) msg.obj;
4030
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004031 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07004032 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004033 if (mMeteredIfaces.contains(iface)) {
4034 try {
4035 // force stats update to make sure we have
4036 // numbers that caused alert to trigger.
4037 mNetworkStats.forceUpdate();
4038 } catch (RemoteException e) {
4039 // ignored; service lives in system_server
4040 }
4041
Felipe Lemef0823852016-06-08 13:43:08 -07004042 updateNetworkEnabledNL();
4043 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004044 }
4045 }
4046 return true;
4047 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004048 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4049 final boolean restrictBackground = msg.arg1 != 0;
4050 final int length = mListeners.beginBroadcast();
4051 for (int i = 0; i < length; i++) {
4052 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004053 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004054 }
4055 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004056 final Intent intent =
4057 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4058 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4059 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4060 return true;
4061 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004062 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004063 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004064 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004065 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004066 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004067 final int length = mListeners.beginBroadcast();
4068 for (int i = 0; i < length; i++) {
4069 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004070 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004071 }
4072 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004073 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4074 if (notifyApp.booleanValue()) {
4075 broadcastRestrictBackgroundChanged(uid, notifyApp);
4076 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004077 return true;
4078 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004079 case MSG_ADVISE_PERSIST_THRESHOLD: {
4080 final long lowestRule = (Long) msg.obj;
4081 try {
4082 // make sure stats are recorded frequently enough; we aim
4083 // for 2MB threshold for 2GB/month rules.
4084 final long persistThreshold = lowestRule / 1000;
4085 mNetworkStats.advisePersistThreshold(persistThreshold);
4086 } catch (RemoteException e) {
4087 // ignored; service lives in system_server
4088 }
4089 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004090 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004091 case MSG_UPDATE_INTERFACE_QUOTA: {
4092 removeInterfaceQuota((String) msg.obj);
4093 // int params need to be stitched back into a long
4094 setInterfaceQuota((String) msg.obj,
4095 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4096 return true;
4097 }
4098 case MSG_REMOVE_INTERFACE_QUOTA: {
4099 removeInterfaceQuota((String) msg.obj);
4100 return true;
4101 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004102 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4103 resetUidFirewallRules(msg.arg1);
4104 return true;
4105 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004106 case MSG_SUBSCRIPTION_OVERRIDE: {
4107 final int overrideMask = msg.arg1;
4108 final int overrideValue = msg.arg2;
4109 final int subId = (int) msg.obj;
4110 final int length = mListeners.beginBroadcast();
4111 for (int i = 0; i < length; i++) {
4112 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4113 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4114 }
4115 mListeners.finishBroadcast();
4116 return true;
4117 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004118 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4119 final int userId = msg.arg1;
4120 final Set<String> packageNames = (Set<String>) msg.obj;
4121 setMeteredRestrictedPackagesInternal(packageNames, userId);
4122 return true;
4123 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004124 default: {
4125 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004126 }
4127 }
4128 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004129 };
4130
4131 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4132 @Override
4133 public boolean handleMessage(Message msg) {
4134 switch (msg.what) {
4135 case UID_MSG_STATE_CHANGED: {
4136 final int uid = msg.arg1;
4137 final int procState = msg.arg2;
4138 final long procStateSeq = (Long) msg.obj;
4139
4140 handleUidChanged(uid, procState, procStateSeq);
4141 return true;
4142 }
4143 case UID_MSG_GONE: {
4144 final int uid = msg.arg1;
4145 handleUidGone(uid);
4146 return true;
4147 }
4148 default: {
4149 return false;
4150 }
4151 }
4152 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004153
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004154 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004155
Makoto Onuki8e777332017-03-28 11:25:47 -07004156 void handleUidChanged(int uid, int procState, long procStateSeq) {
4157 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4158 try {
4159 synchronized (mUidRulesFirstLock) {
4160 // We received a uid state change callback, add it to the history so that it
4161 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004162 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004163 // Now update the network policy rules as per the updated uid state.
4164 updateUidStateUL(uid, procState);
4165 // Updating the network rules is done, so notify AMS about this.
4166 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4167 }
4168 } finally {
4169 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4170 }
4171 }
4172
4173 void handleUidGone(int uid) {
4174 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4175 try {
4176 synchronized (mUidRulesFirstLock) {
4177 removeUidStateUL(uid);
4178 }
4179 } finally {
4180 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4181 }
4182 }
4183
Felipe Leme57e3d312016-08-23 14:42:52 -07004184 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4185 final PackageManager pm = mContext.getPackageManager();
4186 final String[] packages = pm.getPackagesForUid(uid);
4187 if (packages != null) {
4188 final int userId = UserHandle.getUserId(uid);
4189 for (String packageName : packages) {
4190 final Intent intent =
4191 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4192 intent.setPackage(packageName);
4193 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4194 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4195 }
4196 }
4197 }
4198
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004199 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4200 // long quotaBytes split up into two ints to fit in message
4201 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4202 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4203 }
4204
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004205 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004206 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004207 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004208 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004209 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004210 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004211 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004212 }
4213 }
4214
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004215 private void removeInterfaceQuotaAsync(String iface) {
4216 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4217 }
4218
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004219 private void removeInterfaceQuota(String iface) {
4220 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004221 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004222 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004223 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004224 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004225 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004226 }
4227 }
4228
Felipe Leme70c57c22016-03-29 10:45:13 -07004229 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4230 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004231 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004232 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004233 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004234 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4235 } catch (RemoteException e) {
4236 // ignored; service lives in system_server
4237 }
4238 }
4239
4240 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4241 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4242 try {
4243 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4244 } catch (IllegalStateException e) {
4245 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004246 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004247 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004248 }
4249 }
4250
Felipe Lemebc853dd2016-09-08 13:26:55 -07004251 private static final int CHAIN_TOGGLE_NONE = 0;
4252 private static final int CHAIN_TOGGLE_ENABLE = 1;
4253 private static final int CHAIN_TOGGLE_DISABLE = 2;
4254 @Retention(RetentionPolicy.SOURCE)
4255 @IntDef(flag = false, value = {
4256 CHAIN_TOGGLE_NONE,
4257 CHAIN_TOGGLE_ENABLE,
4258 CHAIN_TOGGLE_DISABLE
4259 })
4260 public @interface ChainToggleType {
4261 }
4262
4263 /**
4264 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004265 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004266 *
4267 * @param chain firewall chain.
4268 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4269 * @param toggle whether the chain should be enabled, disabled, or not changed.
4270 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004271 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004272 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004273 if (uidRules != null) {
4274 setUidFirewallRulesUL(chain, uidRules);
4275 }
4276 if (toggle != CHAIN_TOGGLE_NONE) {
4277 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4278 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004279 }
4280
Amith Yamasani15e472352015-04-24 19:06:07 -07004281 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004282 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4283 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4284 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004285 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004286 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004287 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004288 int size = uidRules.size();
4289 int[] uids = new int[size];
4290 int[] rules = new int[size];
4291 for(int index = size - 1; index >= 0; --index) {
4292 uids[index] = uidRules.keyAt(index);
4293 rules[index] = uidRules.valueAt(index);
4294 }
4295 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004296 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004297 } catch (IllegalStateException e) {
4298 Log.wtf(TAG, "problem setting firewall uid rules", e);
4299 } catch (RemoteException e) {
4300 // ignored; service lives in system_server
4301 }
4302 }
4303
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004304 /**
4305 * Add or remove a uid to the firewall blacklist for all network ifaces.
4306 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004307 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004308 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4309 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4310 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004311 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004312 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004313 if (chain == FIREWALL_CHAIN_DOZABLE) {
4314 mUidFirewallDozableRules.put(uid, rule);
4315 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4316 mUidFirewallStandbyRules.put(uid, rule);
4317 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4318 mUidFirewallPowerSaveRules.put(uid, rule);
4319 }
4320
4321 try {
4322 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004323 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004324 } catch (IllegalStateException e) {
4325 Log.wtf(TAG, "problem setting firewall uid rules", e);
4326 } catch (RemoteException e) {
4327 // ignored; service lives in system_server
4328 }
4329 } finally {
4330 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004331 }
4332 }
4333
4334 /**
4335 * Add or remove a uid to the firewall blacklist for all network ifaces.
4336 */
Felipe Lemef0823852016-06-08 13:43:08 -07004337 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004338 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4339 mFirewallChainStates.get(chain) == enable) {
4340 // All is the same, nothing to do.
4341 return;
4342 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004343 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004344 try {
4345 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004346 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004347 } catch (IllegalStateException e) {
4348 Log.wtf(TAG, "problem enable firewall chain", e);
4349 } catch (RemoteException e) {
4350 // ignored; service lives in system_server
4351 }
4352 }
4353
Felipe Leme03e95e22016-09-09 09:25:31 -07004354 /**
4355 * Resets all firewall rules associated with an UID.
4356 */
4357 private void resetUidFirewallRules(int uid) {
4358 try {
4359 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4360 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4361 mNetworkManager
4362 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4363 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4364 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4365 } catch (IllegalStateException e) {
4366 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4367 } catch (RemoteException e) {
4368 // ignored; service lives in system_server
4369 }
4370 }
4371
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004372 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4373 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004374 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004375 } catch (RuntimeException e) {
4376 Slog.w(TAG, "problem reading network stats: " + e);
4377 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004378 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004379 // ignored; service lives in system_server
4380 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004381 }
4382 }
4383
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004384 private boolean isBandwidthControlEnabled() {
4385 final long token = Binder.clearCallingIdentity();
4386 try {
4387 return mNetworkManager.isBandwidthControlEnabled();
4388 } catch (RemoteException e) {
4389 // ignored; service lives in system_server
4390 return false;
4391 } finally {
4392 Binder.restoreCallingIdentity(token);
4393 }
4394 }
4395
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004396 /**
4397 * Try refreshing {@link #mTime} when stale.
4398 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004399 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004400 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004401 mTime.forceRefresh();
4402 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004403 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004404
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004405 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004406 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4407 }
4408
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004409 private static Intent buildAllowBackgroundDataIntent() {
4410 return new Intent(ACTION_ALLOW_BACKGROUND);
4411 }
4412
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004413 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4414 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004415 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4416 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4417 return intent;
4418 }
4419
4420 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4421 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4422 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004423 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4424 return intent;
4425 }
4426
Wei Liu546cb772016-07-21 16:19:01 -07004427 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004428 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004429 intent.setComponent(ComponentName.unflattenFromString(
4430 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004431 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4432 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4433 return intent;
4434 }
4435
Wei Liu546cb772016-07-21 16:19:01 -07004436 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004437 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004438 intent.setComponent(ComponentName.unflattenFromString(
4439 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004440 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4441 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4442 return intent;
4443 }
4444
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004445 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004446 public void addIdleHandler(IdleHandler handler) {
4447 mHandler.getLooper().getQueue().addIdleHandler(handler);
4448 }
4449
jackqdyulei29c82ab2017-03-10 14:09:16 -08004450 @VisibleForTesting
4451 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4452 mRestrictBackgroundPowerState = result;
4453
4454 boolean restrictBackground = result.batterySaverEnabled;
4455 boolean shouldInvokeRestrictBackground;
4456 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4457 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4458
4459 if (result.globalBatterySaverEnabled) {
4460 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4461 // turn it on.
4462 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4463 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4464 localRestrictBgChangedInBsm = false;
4465 } else {
4466 // Try to restore the restrictBackground if it doesn't change in bsm
4467 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4468 restrictBackground = mRestrictBackgroundBeforeBsm;
4469 }
4470
4471 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004472 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004473 }
4474
4475 // Change it at last so setRestrictBackground() won't affect this variable
4476 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4477 }
4478
Jeff Sharkey1b861272011-05-22 00:34:52 -07004479 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4480 final int size = source.size();
4481 for (int i = 0; i < size; i++) {
4482 target.put(source.keyAt(i), true);
4483 }
4484 }
4485
Stuart Scottf1fb3972015-04-02 18:00:02 -07004486 @Override
4487 public void factoryReset(String subscriber) {
4488 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4489
Stuart Scotte3e314d2015-04-20 14:07:45 -07004490 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4491 return;
4492 }
4493
Stuart Scottf1fb3972015-04-02 18:00:02 -07004494 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004495 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004496 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4497 for (NetworkPolicy policy : policies) {
4498 if (policy.template.equals(template)) {
4499 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4500 policy.inferred = false;
4501 policy.clearSnooze();
4502 }
4503 }
4504 setNetworkPolicies(policies);
4505
4506 // Turn restrict background data off
4507 setRestrictBackground(false);
4508
Stuart Scotte3e314d2015-04-20 14:07:45 -07004509 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4510 // Remove app's "restrict background data" flag
4511 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4512 setUidPolicy(uid, POLICY_NONE);
4513 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004514 }
4515 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004516
Sudheer Shankab8f23162017-08-04 13:30:10 -07004517 @Override
4518 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4519 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4520 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4521 }
4522
4523 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4524 final int uidRules;
4525 final boolean isBackgroundRestricted;
4526 synchronized (mUidRulesFirstLock) {
4527 uidRules = mUidRules.get(uid, RULE_NONE);
4528 isBackgroundRestricted = mRestrictBackground;
4529 }
4530 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004531 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004532 return true;
4533 }
4534 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004535 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004536 return false;
4537 }
4538 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004539 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004540 return true;
4541 }
4542 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004543 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004544 return false;
4545 }
4546 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004547 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004548 return false;
4549 }
4550 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004551 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004552 return true;
4553 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004554 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004555 return false;
4556 }
4557
Felipe Lemed17fda42016-04-29 11:12:45 -07004558 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4559
4560 @Override
4561 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004562 synchronized (mUidRulesFirstLock) {
4563 boolean changed = removeUserStateUL(userId, false);
4564 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004565 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004566 synchronized (mNetworkPoliciesSecondLock) {
4567 writePolicyAL();
4568 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004569 }
4570 }
4571 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004572
4573 /**
4574 * @return true if the given uid is restricted from doing networking on metered networks.
4575 */
4576 @Override
4577 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4578 final int uidRules;
4579 final boolean isBackgroundRestricted;
4580 synchronized (mUidRulesFirstLock) {
4581 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4582 isBackgroundRestricted = mRestrictBackground;
4583 }
4584 return isBackgroundRestricted
4585 && !hasRule(uidRules, RULE_ALLOW_METERED)
4586 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4587 }
4588
4589 /**
4590 * @return true if networking is blocked on the given interface for the given uid according
4591 * to current networking policies.
4592 */
4593 @Override
4594 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004595 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004596 synchronized (mNetworkPoliciesSecondLock) {
4597 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004598 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004599 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004600 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004601
4602 @Override
4603 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4604 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004605 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004606 if (added) {
4607 mPowerSaveTempWhitelistAppIds.put(appId, true);
4608 } else {
4609 mPowerSaveTempWhitelistAppIds.delete(appId);
4610 }
4611 updateRulesForTempWhitelistChangeUL(appId);
4612 }
4613 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004614
4615 @Override
4616 public SubscriptionPlan getSubscriptionPlan(Network network) {
4617 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004618 final int subId = getSubIdLocked(network);
4619 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004620 }
4621 }
4622
4623 @Override
4624 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4625 synchronized (mNetworkPoliciesSecondLock) {
4626 // TODO: handle splitting quota between use-cases
4627 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network));
4628 }
4629 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004630
4631 @Override
4632 public void onAdminDataAvailable() {
4633 mAdminDataAvailableLatch.countDown();
4634 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004635
4636 @Override
4637 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4638 setMeteredRestrictedPackagesInternal(packageNames, userId);
4639 }
4640
4641 @Override
4642 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4643 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4644 userId, 0, packageNames).sendToTarget();
4645 }
4646 }
4647
4648 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4649 synchronized (mUidRulesFirstLock) {
4650 final Set<Integer> newRestrictedUids = new ArraySet<>();
4651 for (String packageName : packageNames) {
4652 final int uid = getUidForPackage(packageName, userId);
4653 if (uid >= 0) {
4654 newRestrictedUids.add(uid);
4655 }
4656 }
4657 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4658 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4659 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4660 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4661 }
4662 }
4663
4664 private int getUidForPackage(String packageName, int userId) {
4665 try {
4666 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4667 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4668 } catch (NameNotFoundException e) {
4669 return -1;
4670 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004671 }
4672
4673 private int parseSubId(NetworkState state) {
4674 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4675 int subId = INVALID_SUBSCRIPTION_ID;
4676 if (state != null && state.networkCapabilities != null
4677 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4678 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4679 if (spec instanceof StringNetworkSpecifier) {
4680 try {
4681 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4682 } catch (NumberFormatException e) {
4683 }
4684 }
4685 }
4686 return subId;
4687 }
4688
Andreas Gampea36dc622018-02-05 17:19:22 -08004689 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey9252b342018-01-19 07:58:35 +09004690 private int getSubIdLocked(Network network) {
4691 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004692 }
4693
Andreas Gampea36dc622018-02-05 17:19:22 -08004694 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey2e471452018-01-19 18:02:47 +09004695 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4696 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4697 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4698 }
4699
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004700 /**
4701 * This will only ever be called once - during device boot.
4702 */
4703 private void waitForAdminData() {
4704 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4705 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4706 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4707 }
4708 }
4709
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004710 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4711 Set<Integer> newRestrictedUids) {
4712 if (oldRestrictedUids == null) {
4713 for (int uid : newRestrictedUids) {
4714 updateRulesForDataUsageRestrictionsUL(uid);
4715 }
4716 return;
4717 }
4718 for (int uid : oldRestrictedUids) {
4719 if (!newRestrictedUids.contains(uid)) {
4720 updateRulesForDataUsageRestrictionsUL(uid);
4721 }
4722 }
4723 for (int uid : newRestrictedUids) {
4724 if (!oldRestrictedUids.contains(uid)) {
4725 updateRulesForDataUsageRestrictionsUL(uid);
4726 }
4727 }
4728 }
4729
4730 private boolean isRestrictedByAdminUL(int uid) {
4731 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4732 UserHandle.getUserId(uid));
4733 return restrictedUids != null && restrictedUids.contains(uid);
4734 }
4735
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004736 private static boolean hasRule(int uidRules, int rule) {
4737 return (uidRules & rule) != 0;
4738 }
4739
Jeff Sharkey2e471452018-01-19 18:02:47 +09004740 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4741 return (val != null) ? val : new NetworkState[0];
4742 }
4743
Chris Wren193ae6b2017-03-31 15:17:11 -04004744 private class NotificationId {
4745 private final String mTag;
4746 private final int mId;
4747
4748 NotificationId(NetworkPolicy policy, int type) {
4749 mTag = buildNotificationTag(policy, type);
4750 mId = type;
4751 }
4752
4753 @Override
4754 public boolean equals(Object o) {
4755 if (this == o) return true;
4756 if (!(o instanceof NotificationId)) return false;
4757 NotificationId that = (NotificationId) o;
4758 return Objects.equals(mTag, that.mTag);
4759 }
4760
4761 @Override
4762 public int hashCode() {
4763 return Objects.hash(mTag);
4764 }
4765
4766 /**
4767 * Build unique tag that identifies an active {@link NetworkPolicy}
4768 * notification of a specific type, like {@link #TYPE_LIMIT}.
4769 */
4770 private String buildNotificationTag(NetworkPolicy policy, int type) {
4771 return TAG + ":" + policy.template.hashCode() + ":" + type;
4772 }
4773
4774 public String getTag() {
4775 return mTag;
4776 }
4777
4778 public int getId() {
4779 return mId;
4780 }
4781 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004782}