blob: a6f049e1d8d0f23bddca8e747ee61e28f4d08a07 [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 Sharkey21c9c452011-06-07 12:26:43 -0700148import android.os.Environment;
149import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700150import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700152import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700153import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700154import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700155import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700156import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -0700157import android.os.PowerManager.ServiceType;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700158import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600159import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800160import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700162import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600163import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700164import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700165import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600166import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700167import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700168import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700169import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700170import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100171import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700172import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600173import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800174import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600175import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700176import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400177import android.text.TextUtils;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700178import android.text.format.DateUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700179import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700180import android.util.ArrayMap;
181import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700182import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900183import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700184import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700186import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600187import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700188import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600189import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190import android.util.SparseBooleanArray;
191import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900192import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193import android.util.TrustedTime;
194import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195
Jeff Sharkey497e4432011-06-14 17:27:29 -0700196import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700197import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800198import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400199import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500200import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700201import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800202import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800203import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600204import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700206import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600207import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700208import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700209import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700210import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800211import com.android.server.SystemConfig;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600212
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600213import libcore.io.IoUtils;
214
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216import org.xmlpull.v1.XmlSerializer;
217
218import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700219import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220import java.io.FileInputStream;
221import java.io.FileNotFoundException;
222import java.io.FileOutputStream;
223import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700224import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700225import java.lang.annotation.Retention;
226import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100227import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600228import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600229import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700231import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600232import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400233import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800234import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800235import java.util.concurrent.CountDownLatch;
236import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700238/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700239 * Service that maintains low-level network policy rules, using
240 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700241 * <p>
242 * Derives active rules by combining a given policy with other system status,
243 * and delivers to listeners, such as {@link ConnectivityManager}, for
244 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700245 *
246 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000247 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700248 * <ul>
249 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
250 * rules).
251 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
252 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000253 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
254 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700255 * </ul>
256 *
257 * <p>
258 * As such, methods that require synchronization have the following prefixes:
259 * <ul>
260 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
261 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000262 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
263 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700264 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700265 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700266public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700267 static final String TAG = NetworkPolicyLogger.TAG;
268 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
269 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700270
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700271 private static final int VERSION_INIT = 1;
272 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700273 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800274 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800275 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800276 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700277 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700278 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700279 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700280 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600281 private static final int VERSION_ADDED_CYCLE = 11;
282 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800284 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400285 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800286 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400287 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800288 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400289 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900290 @VisibleForTesting
291 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700292
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 private static final String TAG_POLICY_LIST = "policy-list";
294 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600295 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700296 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700297 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800298 private static final String TAG_WHITELIST = "whitelist";
299 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800300 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301
302 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700303 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
305 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700306 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600307 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
308 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
309 private static final String ATTR_CYCLE_START = "cycleStart";
310 private static final String ATTR_CYCLE_END = "cycleEnd";
311 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312 private static final String ATTR_WARNING_BYTES = "warningBytes";
313 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700314 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800315 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
316 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800317 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700318 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700320 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700321 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600322 private static final String ATTR_SUB_ID = "subId";
323 private static final String ATTR_TITLE = "title";
324 private static final String ATTR_SUMMARY = "summary";
325 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
326 private static final String ATTR_USAGE_BYTES = "usageBytes";
327 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600328 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700329
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800330 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800331 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800332 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800333 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700334 private static final String ACTION_SNOOZE_RAPID =
335 "com.android.server.net.action.SNOOZE_RAPID";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700336
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700337 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
338
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800339 /**
340 * Indicates the maximum wait time for admin data to be available;
341 */
342 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
343
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700344 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700345 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800346 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800347 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700348 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700349 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
350 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700351 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700352 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900353 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800354 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700355
Makoto Onuki8e777332017-03-28 11:25:47 -0700356 private static final int UID_MSG_STATE_CHANGED = 100;
357 private static final int UID_MSG_GONE = 101;
358
Jeff Sharkey75279902011-05-24 18:39:45 -0700359 private final Context mContext;
360 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700361 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700362 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700363 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700364 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700365 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700366 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700367
368 private IConnectivityManager mConnManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700369 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700370 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800371 @GuardedBy("mUidRulesFirstLock")
372 private PowerSaveState mRestrictBackgroundPowerState;
373
374 // Store the status of restrict background before turning on battery saver.
375 // Used to restore mRestrictBackground when battery saver is turned off.
376 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700377
Sudheer Shanka543339f2017-07-28 15:18:07 -0700378 // Denotes the status of restrict background read from disk.
379 private boolean mLoadedRestrictBackground;
380
Felipe Lemef0823852016-06-08 13:43:08 -0700381 // See main javadoc for instructions on how to use these locks.
382 final Object mUidRulesFirstLock = new Object();
383 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700384
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("allLocks") volatile boolean mSystemReady;
386
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
388 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
389 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800390 // Store whether user flipped restrict background in battery saver mode
391 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700392
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700393 private final boolean mSuppressDefaultPolicy;
394
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800395 private final CountDownLatch mAdminDataAvailableLatch = new CountDownLatch(1);
396
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700397 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600398 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800399 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700400
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600401 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600402 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600403 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600404 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600405 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600406 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600407
Jeff Sharkey9252b342018-01-19 07:58:35 +0900408 /** Map from subId to daily opportunistic quota. */
409 @GuardedBy("mNetworkPoliciesSecondLock")
410 final SparseLongArray mSubscriptionOpportunisticQuota = new SparseLongArray();
411
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700412 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700413 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700414 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700415 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700418 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700419 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700420 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700421 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800422 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700423
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700424 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700425 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700426 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
427
Jeff Sharkey32566012014-12-02 18:30:14 -0800428 /**
429 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700430 * in power save mode, except device idle (doze) still applies.
431 * TODO: An int array might be sufficient
432 */
Felipe Lemef0823852016-06-08 13:43:08 -0700433 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700434 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
435
436 /**
437 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800438 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700439 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800440 */
Felipe Lemef0823852016-06-08 13:43:08 -0700441 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700442 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700443
Felipe Lemef0823852016-06-08 13:43:08 -0700444 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700445 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
446
Felipe Lemeb85a6372016-01-14 16:16:16 -0800447 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800448 * UIDs that have been initially white-listed by system to avoid restricted background.
449 */
Felipe Lemef0823852016-06-08 13:43:08 -0700450 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800451 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
452 new SparseBooleanArray();
453
454 /**
455 * UIDs that have been initially white-listed by system to avoid restricted background,
456 * but later revoked by user.
457 */
Felipe Lemef0823852016-06-08 13:43:08 -0700458 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800459 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
460 new SparseBooleanArray();
461
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700462 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800464 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700465 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700466 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800467 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700468
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700469 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700470 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400471 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700472
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700473 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700474 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800475 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700476
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600477 /** Map from network ID to last observed meteredness state */
478 @GuardedBy("mNetworkPoliciesSecondLock")
479 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
480
Jeff Sharkey9252b342018-01-19 07:58:35 +0900481 /** Map from netId to subId as of last update */
482 @GuardedBy("mNetworkPoliciesSecondLock")
483 private final SparseIntArray mNetIdToSubId = new SparseIntArray();
484
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800485 /**
486 * Indicates the uids restricted by admin from accessing metered data. It's a mapping from
487 * userId to restricted uids which belong to that user.
488 */
489 @GuardedBy("mUidRulesFirstLock")
490 private final SparseArray<Set<Integer>> mMeteredRestrictedUids = new SparseArray<>();
491
Jeff Sharkey32566012014-12-02 18:30:14 -0800492 private final RemoteCallbackList<INetworkPolicyListener>
493 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700494
Dianne Hackborn497175b2014-07-01 12:56:08 -0700495 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700496 @VisibleForTesting
497 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700498
499 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700500
Felipe Lemef0823852016-06-08 13:43:08 -0700501 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700502 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700503
Svet Ganov16a16892015-04-16 10:32:04 -0700504 private final AppOpsManager mAppOps;
505
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800506 private final IPackageManager mIPm;
507
Sudheer Shankae7361852017-03-07 11:51:46 -0800508 private ActivityManagerInternal mActivityManagerInternal;
509
Sudheer Shanka352dc572017-09-22 17:09:38 -0700510 private final NetworkPolicyLogger mLogger = new NetworkPolicyLogger();
Felipe Lemeb85a6372016-01-14 16:16:16 -0800511
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700512 // TODO: keep whitelist of system-critical services that should never have
513 // rules enforced, such as system, phone, and radio UIDs.
514
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700515 // TODO: migrate notifications to SystemUI
516
Jeff Sharkey75279902011-05-24 18:39:45 -0700517 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700518 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
519 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700520 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
521 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700522 }
523
524 private static File getSystemDir() {
525 return new File(Environment.getDataDirectory(), "system");
526 }
527
528 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700529 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700530 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700531 mContext = checkNotNull(context, "missing context");
532 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700533 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700534 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700535 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700536 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700537 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700538 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700539 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700540 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700541
Amith Yamasani450a16b2013-09-18 16:28:50 -0700542 HandlerThread thread = new HandlerThread(TAG);
543 thread.start();
544 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700545
Makoto Onuki8e777332017-03-28 11:25:47 -0700546 // We create another thread for the UID events, which are more time-critical.
547 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
548 /*allowIo=*/ false);
549 mUidEventThread.start();
550 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
551
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700552 mSuppressDefaultPolicy = suppressDefaultPolicy;
553
Dianne Hackborne17b4452018-01-10 13:15:40 -0800554 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"), "net-policy");
Svet Ganov16a16892015-04-16 10:32:04 -0700555
556 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800557
Felipe Lemed17fda42016-04-29 11:12:45 -0700558 // Expose private service for system components to use.
559 LocalServices.addService(NetworkPolicyManagerInternal.class,
560 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700561 }
562
563 public void bindConnectivityManager(IConnectivityManager connManager) {
564 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700565 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700566
Felipe Lemef0823852016-06-08 13:43:08 -0700567 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700568 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700569 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
570 mPowerSaveWhitelistExceptIdleAppIds.clear();
571 if (whitelist != null) {
572 for (int uid : whitelist) {
573 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
574 }
575 }
576 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700577 mPowerSaveWhitelistAppIds.clear();
578 if (whitelist != null) {
579 for (int uid : whitelist) {
580 mPowerSaveWhitelistAppIds.put(uid, true);
581 }
582 }
583 } catch (RemoteException e) {
584 }
585 }
586
Felipe Lemea9505cc2016-02-26 10:28:41 -0800587 /**
588 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
589 * revoke the whitelist.
590 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700591 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800592 */
Felipe Lemef0823852016-06-08 13:43:08 -0700593 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800594 final List<UserInfo> users = mUserManager.getUsers();
595 final int numberUsers = users.size();
596
Felipe Lemea110eec2016-04-29 09:58:06 -0700597 boolean changed = false;
598 for (int i = 0; i < numberUsers; i++) {
599 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700600 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700601 }
602 return changed;
603 }
604
Felipe Lemef0823852016-06-08 13:43:08 -0700605 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700606 final SystemConfig sysConfig = SystemConfig.getInstance();
607 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800608 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
609 boolean changed = false;
610 for (int i = 0; i < allowDataUsage.size(); i++) {
611 final String pkg = allowDataUsage.valueAt(i);
612 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700613 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
614 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800615 final ApplicationInfo app;
616 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700617 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800618 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700619 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
620 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800621 continue;
622 }
623 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700624 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
625 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800626 continue;
627 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700628 final int uid = UserHandle.getUid(userId, app.uid);
629 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
630 if (LOGD)
631 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
632 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800633 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700634 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700635 if (LOGD)
636 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
637 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700638 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700639 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800640 }
641 }
642 return changed;
643 }
644
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800645 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700646 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800647 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700648 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800649 // Boost thread's priority during system server init
650 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700651 if (!isBandwidthControlEnabled()) {
652 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
653 return;
654 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700655
Felipe Leme873a83a2016-09-07 11:34:10 -0700656 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700657
Felipe Leme873a83a2016-09-07 11:34:10 -0700658 synchronized (mUidRulesFirstLock) {
659 synchronized (mNetworkPoliciesSecondLock) {
660 updatePowerSaveWhitelistUL();
661 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
662 mPowerManagerInternal.registerLowPowerModeObserver(
663 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800664 @Override
665 public int getServiceType() {
666 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700667 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800668
669 @Override
670 public void onLowPowerModeChanged(PowerSaveState result) {
671 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800672 if (LOGD) {
673 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
674 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800675 synchronized (mUidRulesFirstLock) {
676 if (mRestrictPower != enabled) {
677 mRestrictPower = enabled;
678 updateRulesForRestrictPowerUL();
679 }
680 }
681 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800682 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800683 mRestrictPower = mPowerManagerInternal.getLowPowerState(
684 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700685
686 mSystemReady = true;
687
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800688 waitForAdminData();
689
Felipe Leme873a83a2016-09-07 11:34:10 -0700690 // read policy from disk
691 readPolicyAL();
692
jackqdyulei29c82ab2017-03-10 14:09:16 -0800693 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700694 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800695 mRestrictBackgroundPowerState = mPowerManagerInternal
696 .getLowPowerState(ServiceType.DATA_SAVER);
697 final boolean localRestrictBackground =
698 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700699 if (localRestrictBackground && !mLoadedRestrictBackground) {
700 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800701 }
702 mPowerManagerInternal.registerLowPowerModeObserver(
703 new PowerManagerInternal.LowPowerModeListener() {
704 @Override
705 public int getServiceType() {
706 return ServiceType.DATA_SAVER;
707 }
708
709 @Override
710 public void onLowPowerModeChanged(PowerSaveState result) {
711 synchronized (mUidRulesFirstLock) {
712 updateRestrictBackgroundByLowPowerModeUL(result);
713 }
714 }
715 });
716
Felipe Leme873a83a2016-09-07 11:34:10 -0700717 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
718 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700719 }
Felipe Lemef0823852016-06-08 13:43:08 -0700720
Sudheer Shanka543339f2017-07-28 15:18:07 -0700721 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700722 updateRulesForGlobalChangeAL(false);
723 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700724 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800725 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700726
Sudheer Shankae7361852017-03-07 11:51:46 -0800727 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700728 try {
729 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000730 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800731 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700732 mNetworkManager.registerObserver(mAlertObserver);
733 } catch (RemoteException e) {
734 // ignored; both services live in system_server
735 }
736
737 // listen for changes to power save whitelist
738 final IntentFilter whitelistFilter = new IntentFilter(
739 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
740 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
741
Felipe Leme873a83a2016-09-07 11:34:10 -0700742 // watch for network interfaces to be claimed
743 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
744 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
745
746 // listen for package changes to update policy
747 final IntentFilter packageFilter = new IntentFilter();
748 packageFilter.addAction(ACTION_PACKAGE_ADDED);
749 packageFilter.addDataScheme("package");
750 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
751
752 // listen for UID changes to update policy
753 mContext.registerReceiver(
754 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
755
756 // listen for user changes to update policy
757 final IntentFilter userFilter = new IntentFilter();
758 userFilter.addAction(ACTION_USER_ADDED);
759 userFilter.addAction(ACTION_USER_REMOVED);
760 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
761
762 // listen for stats update events
763 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
764 mContext.registerReceiver(
765 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
766
767 // listen for restrict background changes from notifications
768 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
769 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
770
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700771 // Listen for snooze from notifications
772 mContext.registerReceiver(mSnoozeReceiver,
773 new IntentFilter(ACTION_SNOOZE_WARNING), MANAGE_NETWORK_POLICY, mHandler);
774 mContext.registerReceiver(mSnoozeReceiver,
775 new IntentFilter(ACTION_SNOOZE_RAPID), MANAGE_NETWORK_POLICY, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700776
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600777 // listen for configured wifi networks to be loaded
778 final IntentFilter wifiFilter =
779 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
780 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700781
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700782 // listen for carrier config changes to update data cycle information
783 final IntentFilter carrierConfigFilter = new IntentFilter(
784 ACTION_CARRIER_CONFIG_CHANGED);
785 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
786
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600787 // listen for meteredness changes
788 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
789 new NetworkRequest.Builder().build(), mNetworkCallback);
790
Felipe Leme873a83a2016-09-07 11:34:10 -0700791 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800792 // tell systemReady() that the service has been initialized
793 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700794 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800795 // Restore the default priority after init is done
796 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700798 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700799 }
800
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800801 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
802 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
803 mHandler.post(() -> initService(initCompleteSignal));
804 return initCompleteSignal;
805 }
806
807 public void systemReady(CountDownLatch initCompleteSignal) {
808 // wait for initService to complete
809 try {
810 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
811 throw new IllegalStateException("Service " + TAG +" init timeout");
812 }
813 } catch (InterruptedException e) {
814 Thread.currentThread().interrupt();
815 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
816 }
817 }
818
Sudheer Shankac9d94072017-02-22 22:13:55 +0000819 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700820 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700821 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
822 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700823 }
824
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700825 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700826 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700827 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700828
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700829 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700830 }
831
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700832 @Override public void onUidIdle(int uid, boolean disabled) {
833 }
834
835 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700836 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700837 };
838
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700839 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700840 @Override
841 public void onReceive(Context context, Intent intent) {
842 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700843 synchronized (mUidRulesFirstLock) {
844 updatePowerSaveWhitelistUL();
845 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700846 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700847 }
848 }
849 };
850
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700851 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700852 @Override
853 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700854 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700855
856 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700857 final int uid = intent.getIntExtra(EXTRA_UID, -1);
858 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700859
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700860 if (ACTION_PACKAGE_ADDED.equals(action)) {
861 // update rules for UID, since it might be subject to
862 // global background data policy
863 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700864 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700865 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700866 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700867 }
868 }
869 };
870
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700871 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700872 @Override
873 public void onReceive(Context context, Intent intent) {
874 // on background handler thread, and UID_REMOVED is protected
875
876 final int uid = intent.getIntExtra(EXTRA_UID, -1);
877 if (uid == -1) return;
878
879 // remove any policy and update rules to clean up
880 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700881 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700882 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700883 synchronized (mNetworkPoliciesSecondLock) {
884 writePolicyAL();
885 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700886 }
887 }
888 };
889
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700890 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700891 @Override
892 public void onReceive(Context context, Intent intent) {
893 // on background handler thread, and USER_ADDED and USER_REMOVED
894 // broadcasts are protected
895
896 final String action = intent.getAction();
897 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
898 if (userId == -1) return;
899
Amith Yamasani15e472352015-04-24 19:06:07 -0700900 switch (action) {
901 case ACTION_USER_REMOVED:
902 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700903 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800904 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700905 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700906 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800907 // Removing outside removeUserStateUL since that can also be called when
908 // user resets app preferences.
909 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700910 if (action == ACTION_USER_ADDED) {
911 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700912 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700913 }
914 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700915 synchronized (mNetworkPoliciesSecondLock) {
916 updateRulesForGlobalChangeAL(true);
917 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700918 }
919 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700920 }
921 }
922 };
923
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700924 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700925 * Receiver that watches for {@link INetworkStatsService} updates, which we
926 * use to check against {@link NetworkPolicy#warningBytes}.
927 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700928 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700929 @Override
930 public void onReceive(Context context, Intent intent) {
931 // on background handler thread, and verified
932 // READ_NETWORK_USAGE_HISTORY permission above.
933
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800934 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700935 synchronized (mNetworkPoliciesSecondLock) {
936 updateNetworkEnabledNL();
937 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 }
939 }
940 };
941
942 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700943 * Receiver that watches for {@link Notification} control of
944 * {@link #mRestrictBackground}.
945 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700946 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700947 @Override
948 public void onReceive(Context context, Intent intent) {
949 // on background handler thread, and verified MANAGE_NETWORK_POLICY
950 // permission above.
951
952 setRestrictBackground(false);
953 }
954 };
955
956 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800957 * Receiver that watches for {@link Notification} control of
958 * {@link NetworkPolicy#lastWarningSnooze}.
959 */
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700960 final private BroadcastReceiver mSnoozeReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800961 @Override
962 public void onReceive(Context context, Intent intent) {
963 // on background handler thread, and verified MANAGE_NETWORK_POLICY
964 // permission above.
965
966 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -0700967 if (ACTION_SNOOZE_WARNING.equals(intent.getAction())) {
968 performSnooze(template, TYPE_WARNING);
969 } else if (ACTION_SNOOZE_RAPID.equals(intent.getAction())) {
970 performSnooze(template, TYPE_RAPID);
971 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800972 }
973 };
974
975 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600976 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600977 * we can perform upgrade logic. After initial upgrade logic, it updates
978 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700979 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600980 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700981 @Override
982 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900983 synchronized (mUidRulesFirstLock) {
984 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600985 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600986 }
987 }
988 // Only need to perform upgrade logic once
989 mContext.unregisterReceiver(this);
990 }
991 };
992
993 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
994 @Override
995 public void onCapabilitiesChanged(Network network,
996 NetworkCapabilities networkCapabilities) {
997 if (network == null || networkCapabilities == null) return;
998
999 synchronized (mNetworkPoliciesSecondLock) {
1000 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1001 final boolean newMetered = !networkCapabilities
1002 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1003
1004 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001005 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001006 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001007 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001008 }
1009 }
1010 }
1011 };
1012
1013 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001014 * Observer that watches for {@link INetworkManagementService} alerts.
1015 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001016 final private INetworkManagementEventObserver mAlertObserver
1017 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001018 @Override
1019 public void limitReached(String limitName, String iface) {
1020 // only someone like NMS should be calling us
1021 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1022
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001023 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1024 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 }
1026 }
1027 };
1028
1029 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1031 * to show visible notifications as needed.
1032 */
Felipe Lemef0823852016-06-08 13:43:08 -07001033 void updateNotificationsNL() {
1034 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001036 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001037 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001038 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039
1040 // TODO: when switching to kernel notifications, compute next future
1041 // cycle boundary to recompute notifications.
1042
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001043 // examine stats for each active policy
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001044 final long now = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001045 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1046 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 // ignore policies that aren't relevant to user
1048 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001049 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050
Jeff Sharkey53313d72017-07-13 16:47:32 -06001051 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1052 .cycleIterator(policy).next();
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001053 final long cycleStart = cycle.first.toInstant().toEpochMilli();
1054 final long cycleEnd = cycle.second.toInstant().toEpochMilli();
1055 final long totalBytes = getTotalBytes(policy.template, cycleStart, cycleEnd);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001056
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001057 // Notify when data usage is over warning/limit
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001058 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001059 final boolean snoozedThisCycle = policy.lastLimitSnooze >= cycleStart;
1060 if (snoozedThisCycle) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001061 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1062 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001063 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001064 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001065 }
1066
Jeff Sharkey497e4432011-06-14 17:27:29 -07001067 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001068 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001069
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001070 final boolean snoozedThisCycle = policy.lastWarningSnooze >= cycleStart;
1071 if (policy.isOverWarning(totalBytes) && !snoozedThisCycle) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001072 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 }
1074 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001075
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001076 // Warn if average usage over last 4 days is on track to blow pretty
1077 // far past the plan limits.
1078 if (policy.limitBytes != LIMIT_DISABLED) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001079 final long recentDuration = TimeUnit.DAYS.toMillis(4);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001080 final long recentBytes = getTotalBytes(policy.template, now - recentDuration, now);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001081
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001082 final long cycleDuration = cycleEnd - cycleStart;
Jeff Sharkey2e471452018-01-19 18:02:47 +09001083 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001084 final long alertBytes = (policy.limitBytes * 3) / 2;
1085
1086 if (LOGD) {
1087 Slog.d(TAG, "Rapid usage considering recent " + recentBytes + " projected "
1088 + projectedBytes + " alert " + alertBytes);
1089 }
1090
1091 final boolean snoozedRecently = policy.lastRapidSnooze >= now
1092 - DateUtils.DAY_IN_MILLIS;
1093 if (projectedBytes > alertBytes && !snoozedRecently) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001094 enqueueNotification(policy, TYPE_RAPID, 0);
1095 }
1096 }
1097 }
1098
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001100 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001101 final NotificationId notificationId = beforeNotifs.valueAt(i);
1102 if (!mActiveNotifs.contains(notificationId)) {
1103 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001104 }
1105 }
1106 }
1107
1108 /**
1109 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001110 * current device state, such as when
1111 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1112 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001113 */
1114 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001115 if (template.isMatchRuleMobile()) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001116 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1117 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001118
Jeff Sharkey32566012014-12-02 18:30:14 -08001119 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001120 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001121 for (int subId : subIds) {
1122 final String subscriberId = tele.getSubscriberId(subId);
1123 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001124 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1125 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001126 if (template.matches(probeIdent)) {
1127 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001128 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001129 }
1130 return false;
1131 } else {
1132 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 }
1135
1136 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 * Notify that given {@link NetworkTemplate} is over
1138 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1139 */
Felipe Lemef0823852016-06-08 13:43:08 -07001140 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001141 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001142 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001143 mOverLimitNotified.add(template);
1144 }
1145 }
1146
Felipe Lemef0823852016-06-08 13:43:08 -07001147 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001148 mOverLimitNotified.remove(template);
1149 }
1150
1151 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152 * Show notification for combined {@link NetworkPolicy} and specific type,
1153 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1154 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001155 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001156 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001157 final Notification.Builder builder =
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001158 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001159 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001160 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001161 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001162 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001163
1164 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001165 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001166 switch (type) {
1167 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001168 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001169 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001170
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001171 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001172 builder.setTicker(title);
1173 builder.setContentTitle(title);
1174 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001175
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001176 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1177 builder.setDeleteIntent(PendingIntent.getBroadcast(
1178 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1179
Wei Liu546cb772016-07-21 16:19:01 -07001180 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001181 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001182 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1183
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 break;
1185 }
1186 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001187 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001188
1189 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001190 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001191 switch (policy.template.getMatchRule()) {
1192 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001194 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001195 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001196 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001197 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001199 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001200 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001201 case MATCH_WIFI:
1202 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001203 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001204 break;
1205 default:
1206 title = null;
1207 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001208 }
1209
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001210 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001211 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001212 builder.setTicker(title);
1213 builder.setContentTitle(title);
1214 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001215
Wei Liu546cb772016-07-21 16:19:01 -07001216 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001217 builder.setContentIntent(PendingIntent.getActivity(
1218 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1219 break;
1220 }
1221 case TYPE_LIMIT_SNOOZED: {
1222 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001223 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001224 Formatter.formatFileSize(mContext, overBytes));
1225
1226 final CharSequence title;
1227 switch (policy.template.getMatchRule()) {
1228 case MATCH_MOBILE_3G_LOWER:
1229 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1230 break;
1231 case MATCH_MOBILE_4G:
1232 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1233 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001235 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1236 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001237 case MATCH_WIFI:
1238 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1239 break;
1240 default:
1241 title = null;
1242 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001243 }
1244
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001245 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001246 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001247 builder.setTicker(title);
1248 builder.setContentTitle(title);
1249 builder.setContentText(body);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001250 builder.setChannelId(SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001251
Wei Liu546cb772016-07-21 16:19:01 -07001252 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001253 builder.setContentIntent(PendingIntent.getActivity(
1254 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001255 break;
1256 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001257 case TYPE_RAPID: {
1258 final CharSequence title = res.getText(R.string.data_usage_rapid_title);
1259 body = res.getText(R.string.data_usage_rapid_body);
1260
Jeff Sharkey2e471452018-01-19 18:02:47 +09001261 builder.setSmallIcon(R.drawable.stat_notify_error);
1262 builder.setTicker(title);
1263 builder.setContentTitle(title);
1264 builder.setContentText(body);
1265
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001266 final Intent snoozeIntent = buildSnoozeRapidIntent(policy.template);
1267 builder.setDeleteIntent(PendingIntent.getBroadcast(
1268 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1269
1270 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001271 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001272 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey2e471452018-01-19 18:02:47 +09001273 break;
1274 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001275 }
1276
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001277 if (!TextUtils.isEmpty(body)) {
1278 builder.setStyle(new Notification.BigTextStyle().bigText(body));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001279 }
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001280
1281 mContext.getSystemService(NotificationManager.class).notifyAsUser(notificationId.getTag(),
1282 notificationId.getId(), builder.build(), UserHandle.ALL);
1283 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001284 }
1285
Chris Wren193ae6b2017-03-31 15:17:11 -04001286 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001287 mContext.getSystemService(NotificationManager.class).cancel(notificationId.getTag(),
1288 notificationId.getId());
Jeff Sharkey497e4432011-06-14 17:27:29 -07001289 }
1290
1291 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001292 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001293 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001295 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001296 @Override
1297 public void onReceive(Context context, Intent intent) {
1298 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1299 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001300
1301 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001302 synchronized (mUidRulesFirstLock) {
1303 synchronized (mNetworkPoliciesSecondLock) {
1304 ensureActiveMobilePolicyAL();
1305 normalizePoliciesNL();
1306 updateNetworkEnabledNL();
1307 updateNetworkRulesNL();
1308 updateNotificationsNL();
1309 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001310 }
1311 }
1312 };
1313
Jeff Sharkey2e471452018-01-19 18:02:47 +09001314 @VisibleForTesting
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001315 public void updateNetworks() throws InterruptedException {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001316 mConnReceiver.onReceive(null, null);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001317 final CountDownLatch latch = new CountDownLatch(1);
1318 mHandler.post(() -> {
1319 latch.countDown();
1320 });
1321 latch.await(5, TimeUnit.SECONDS);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001322 }
1323
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001325 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1326 * if necessary.
1327 *
1328 * @param subId that has its associated NetworkPolicy updated if necessary
1329 * @return if any policies were updated
1330 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001331 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1332 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001333
1334 boolean policyUpdated = false;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001335 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
1336 .getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001337
1338 // find and update the mobile NetworkPolicy for this subscriber id
1339 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001340 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001341 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1342 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1343 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001344 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1345 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001346 }
1347 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001348 return policyUpdated;
1349 }
1350
1351 /**
1352 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1353 *
1354 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1355 * to do so, it returns the fallback value.
1356 *
1357 * @param config The CarrierConfig to read the value from.
1358 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1359 * @return cycleDay to use in the mobile NetworkPolicy.
1360 */
1361 @VisibleForTesting
1362 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1363 int fallbackCycleDay) {
1364 if (config == null) {
1365 return fallbackCycleDay;
1366 }
1367 int cycleDay =
1368 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1369 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1370 return fallbackCycleDay;
1371 }
1372 // validate cycleDay value
1373 final Calendar cal = Calendar.getInstance();
1374 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1375 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1376 Slog.e(TAG, "Invalid date in "
1377 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1378 return fallbackCycleDay;
1379 }
1380 return cycleDay;
1381 }
1382
1383 /**
1384 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1385 *
1386 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1387 * to do so, it returns the fallback value.
1388 *
1389 * @param config The CarrierConfig to read the value from.
1390 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1391 * @return warningBytes to use in the mobile NetworkPolicy.
1392 */
1393 @VisibleForTesting
1394 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1395 long fallbackWarningBytes) {
1396 if (config == null) {
1397 return fallbackWarningBytes;
1398 }
1399 long warningBytes =
1400 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1401
1402 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1403 return WARNING_DISABLED;
1404 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1405 return getPlatformDefaultWarningBytes();
1406 } else if (warningBytes < 0) {
1407 Slog.e(TAG, "Invalid value in "
1408 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1409 + "non-negative value but got: " + warningBytes);
1410 return fallbackWarningBytes;
1411 }
1412
1413 return warningBytes;
1414 }
1415
1416 /**
1417 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1418 *
1419 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1420 * to do so, it returns the fallback value.
1421 *
1422 * @param config The CarrierConfig to read the value from.
1423 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1424 * @return limitBytes to use in the mobile NetworkPolicy.
1425 */
1426 @VisibleForTesting
1427 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1428 long fallbackLimitBytes) {
1429 if (config == null) {
1430 return fallbackLimitBytes;
1431 }
1432 long limitBytes =
1433 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1434
1435 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1436 return LIMIT_DISABLED;
1437 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1438 return getPlatformDefaultLimitBytes();
1439 } else if (limitBytes < 0) {
1440 Slog.e(TAG, "Invalid value in "
1441 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1442 + "non-negative value but got: " + limitBytes);
1443 return fallbackLimitBytes;
1444 }
1445 return limitBytes;
1446 }
1447
1448 /**
1449 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1450 */
1451 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1452 @Override
1453 public void onReceive(Context context, Intent intent) {
1454 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1455 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1456
1457 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1458 return;
1459 }
1460 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001461 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001462 final String subscriberId = tele.getSubscriberId(subId);
1463
1464 maybeRefreshTrustedTime();
1465 synchronized (mUidRulesFirstLock) {
1466 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001467 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001468 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001469 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001470 if (!updated) return;
1471 // update network and notification rules, as the data cycle changed and it's
1472 // possible that we should be triggering warnings/limits now
1473 handleNetworkPoliciesUpdateAL(true);
1474 }
1475 }
1476 }
1477 };
1478
1479 /**
1480 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1481 * one has been updated.
1482 *
1483 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1484 * update.
1485 */
1486 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1487 if (shouldNormalizePolicies) {
1488 normalizePoliciesNL();
1489 }
1490 updateNetworkEnabledNL();
1491 updateNetworkRulesNL();
1492 updateNotificationsNL();
1493 writePolicyAL();
1494 }
1495
1496 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001497 * Proactively control network data connections when they exceed
1498 * {@link NetworkPolicy#limitBytes}.
1499 */
Felipe Lemef0823852016-06-08 13:43:08 -07001500 void updateNetworkEnabledNL() {
1501 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001502
1503 // TODO: reset any policy-disabled networks when any policy is removed
1504 // completely, which is currently rare case.
1505
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001506 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1507 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001508 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001509 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001510 setNetworkTemplateEnabled(policy.template, true);
1511 continue;
1512 }
1513
Jeff Sharkey53313d72017-07-13 16:47:32 -06001514 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1515 .cycleIterator(policy).next();
1516 final long start = cycle.first.toInstant().toEpochMilli();
1517 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001518 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001519
1520 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001521 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1522 && policy.lastLimitSnooze < start;
1523 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001524
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001525 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001526 }
1527 }
1528
1529 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001530 * Proactively disable networks that match the given
1531 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001532 */
1533 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001534 // TODO: reach into ConnectivityManager to proactively disable bringing
1535 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001536
1537 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1538 // If mobile data usage hits the limit or if the user resumes the data, we need to
1539 // notify telephony.
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001540 final SubscriptionManager sm = mContext.getSystemService(SubscriptionManager.class);
1541 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
Jack Yu8781b682016-07-08 14:28:51 -07001542
Jeff Sharkey2e471452018-01-19 18:02:47 +09001543 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001544 for (int subId : subIds) {
1545 final String subscriberId = tm.getSubscriberId(subId);
1546 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001547 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1548 true);
Jack Yu8781b682016-07-08 14:28:51 -07001549 // Template is matched when subscriber id matches.
1550 if (template.matches(probeIdent)) {
1551 tm.setPolicyDataEnabled(enabled, subId);
1552 }
1553 }
1554 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001555 }
1556
1557 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001558 * Collect all ifaces from a {@link NetworkState} into the given set.
1559 */
1560 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1561 final String baseIface = state.linkProperties.getInterfaceName();
1562 if (baseIface != null) {
1563 ifaces.add(baseIface);
1564 }
1565 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1566 final String stackedIface = stackedLink.getInterfaceName();
1567 if (stackedIface != null) {
1568 ifaces.add(stackedIface);
1569 }
1570 }
1571 }
1572
1573 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 * Examine all connected {@link NetworkState}, looking for
1575 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1576 * remaining quota based on usage cycle and historical stats.
1577 */
Felipe Lemef0823852016-06-08 13:43:08 -07001578 void updateNetworkRulesNL() {
1579 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580
1581 final NetworkState[] states;
1582 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001583 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001585 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 return;
1587 }
1588
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001589 // First, generate identities of all connected networks so we can
1590 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001591 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001592 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001594 if (state.network != null) {
1595 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1596 }
Wei Liub8eaf452016-01-25 10:32:27 -08001597 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001598 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1599 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001600 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601 }
1602 }
1603
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001604 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001605 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001606
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001607 // For every well-defined policy, compute remaining data based on
1608 // current cycle and historical stats, and push to kernel.
1609 final ArraySet<String> matchingIfaces = new ArraySet<>();
1610 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1611 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1612
1613 // Collect all ifaces that match this policy
1614 matchingIfaces.clear();
1615 for (int j = identified.size() - 1; j >= 0; j--) {
1616 if (policy.template.matches(identified.valueAt(j))) {
1617 collectIfaces(matchingIfaces, identified.keyAt(j));
1618 }
1619 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001622 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001623 }
1624
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001625 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001627 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001628 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001629 if (hasLimit && policy.hasCycle()) {
1630 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1631 .cycleIterator(policy).next();
1632 final long start = cycle.first.toInstant().toEpochMilli();
1633 final long end = cycle.second.toInstant().toEpochMilli();
1634 final long totalBytes = getTotalBytes(policy.template, start, end);
1635
1636 if (policy.lastLimitSnooze >= start) {
1637 // snoozing past quota, but we still need to restrict apps,
1638 // so push really high quota.
1639 quotaBytes = Long.MAX_VALUE;
1640 } else {
1641 // remaining "quota" bytes are based on total usage in
1642 // current cycle. kernel doesn't like 0-byte rules, so we
1643 // set 1-byte quota and disable the radio later.
1644 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1645 }
1646 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001647 // metered network, but no policy limit; we still need to
1648 // restrict apps, so push really high quota.
1649 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001650 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001651
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001652 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001653 // TODO: switch to shared quota once NMS supports
1654 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001655 }
1656
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001657 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1658 final String iface = matchingIfaces.valueAt(j);
1659 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001660 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001661 }
1662 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001663
1664 // keep track of lowest warning or limit of active policies
1665 if (hasWarning && policy.warningBytes < lowestRule) {
1666 lowestRule = policy.warningBytes;
1667 }
1668 if (hasLimit && policy.limitBytes < lowestRule) {
1669 lowestRule = policy.limitBytes;
1670 }
1671 }
1672
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001673 // One final pass to catch any metered ifaces that don't have explicitly
1674 // defined policies; typically Wi-Fi networks.
1675 for (NetworkState state : states) {
1676 if (state.networkInfo != null && state.networkInfo.isConnected()
1677 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1678 matchingIfaces.clear();
1679 collectIfaces(matchingIfaces, state);
1680 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1681 final String iface = matchingIfaces.valueAt(j);
1682 if (!newMeteredIfaces.contains(iface)) {
1683 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1684 newMeteredIfaces.add(iface);
1685 }
1686 }
1687 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001688 }
1689
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001690 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001691 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1692 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001693 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001694 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001695 }
1696 }
1697 mMeteredIfaces = newMeteredIfaces;
1698
Jeff Sharkey9252b342018-01-19 07:58:35 +09001699 // Finally, calculate our opportunistic quotas
1700 // TODO: add experiments support to disable or tweak ratios
1701 mSubscriptionOpportunisticQuota.clear();
1702 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001703 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001704 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001705 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001706 if (plan == null) continue;
1707
1708 // By default assume we have no quota
Jeff Sharkey9252b342018-01-19 07:58:35 +09001709 long quotaBytes = 0;
1710
Jeff Sharkey2e471452018-01-19 18:02:47 +09001711 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001712 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1713 // Ignore missing limits
Jeff Sharkey2e471452018-01-19 18:02:47 +09001714 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001715 // Unlimited data; let's use 20MiB/day (600MiB/month)
1716 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1717 } else {
1718 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001719 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001720 final long start = cycle.first.toInstant().toEpochMilli();
1721 final long end = cycle.second.toInstant().toEpochMilli();
1722 final long totalBytes = getTotalBytes(
1723 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1724 final long remainingBytes = limitBytes - totalBytes;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001725 final long remainingDays = Math.min(1, (end - currentTimeMillis())
Jeff Sharkey9252b342018-01-19 07:58:35 +09001726 / TimeUnit.DAYS.toMillis(1));
1727 if (remainingBytes > 0) {
1728 quotaBytes = (remainingBytes / remainingDays) / 10;
1729 }
1730 }
1731
1732 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1733 }
1734
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001735 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001736 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001737
1738 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001739 }
1740
1741 /**
1742 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1743 * have at least a default mobile policy defined.
1744 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001745 private void ensureActiveMobilePolicyAL() {
1746 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001747 if (mSuppressDefaultPolicy) return;
1748
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07001749 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
1750 final SubscriptionManager sub = mContext.getSystemService(SubscriptionManager.class);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001751
Jeff Sharkey2e471452018-01-19 18:02:47 +09001752 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001753 for (int subId : subIds) {
1754 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001755 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001756 }
1757 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001758
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001759 /**
1760 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1761 * have at least a default mobile policy defined.
1762 *
1763 * @param subId to build a default policy for
1764 * @param subscriberId that we check for an existing policy
1765 * @return true if a mobile network policy was added, or false one already existed.
1766 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001767 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001768 // Poke around to see if we already have a policy
1769 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001770 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001771 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1772 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1773 if (template.matches(probeIdent)) {
1774 if (LOGD) {
1775 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1776 + NetworkIdentity.scrubSubscriberId(subscriberId));
1777 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001778 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001779 }
1780 }
1781
Jeff Sharkey32566012014-12-02 18:30:14 -08001782 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1783 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001784 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001785 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001786 return true;
1787 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001788
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001789 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001790 final int dataWarningConfig = mContext.getResources().getInteger(
1791 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001792 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001793 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001794 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001795 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001796 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001797 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001798
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001799 private long getPlatformDefaultLimitBytes() {
1800 return LIMIT_DISABLED;
1801 }
1802
1803 @VisibleForTesting
1804 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001805 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001806 final RecurrenceRule cycleRule = NetworkPolicy
1807 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001808 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001809 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1810 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1811 synchronized (mUidRulesFirstLock) {
1812 synchronized (mNetworkPoliciesSecondLock) {
1813 updateDefaultMobilePolicyAL(subId, policy);
1814 }
1815 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001816 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001817 }
1818
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001819 /**
1820 * Update the given {@link NetworkPolicy} based on any carrier-provided
1821 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1822 * Leaves policy untouched if the user has modified it.
1823 *
1824 * @return if the policy was modified
1825 */
1826 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1827 if (!policy.inferred) {
1828 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1829 return false;
1830 }
1831
1832 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1833 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1834 policy.lastLimitSnooze, policy.metered, policy.inferred);
1835
1836 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1837 if (!ArrayUtils.isEmpty(plans)) {
1838 final SubscriptionPlan plan = plans[0];
1839 policy.cycleRule = plan.getCycleRule();
1840 final long planLimitBytes = plan.getDataLimitBytes();
1841 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1842 policy.warningBytes = getPlatformDefaultWarningBytes();
1843 policy.limitBytes = getPlatformDefaultLimitBytes();
1844 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1845 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1846 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1847 } else {
1848 policy.warningBytes = (planLimitBytes * 9) / 10;
1849 switch (plan.getDataLimitBehavior()) {
1850 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1851 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1852 policy.limitBytes = planLimitBytes;
1853 break;
1854 default:
1855 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1856 break;
1857 }
1858 }
1859 } else {
1860 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1861 final int currentCycleDay;
1862 if (policy.cycleRule.isMonthly()) {
1863 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1864 } else {
1865 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1866 }
1867 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1868 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1869 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1870 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1871 }
1872
1873 if (policy.equals(original)) {
1874 return false;
1875 } else {
1876 Slog.d(TAG, "Updated " + original + " to " + policy);
1877 return true;
1878 }
1879 }
1880
Felipe Lemef0823852016-06-08 13:43:08 -07001881 private void readPolicyAL() {
1882 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001883
1884 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001885 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001886 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001887 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001888 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001889
1890 FileInputStream fis = null;
1891 try {
1892 fis = mPolicyFile.openRead();
1893 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001894 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001895
Felipe Leme46b451f2016-08-19 08:46:17 -07001896 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1897 // to skip UIDs that were explicitly blacklisted.
1898 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1899
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001900 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001901 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001902 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001903 while ((type = in.next()) != END_DOCUMENT) {
1904 final String tag = in.getName();
1905 if (type == START_TAG) {
1906 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001907 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001908 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001909 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1910 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001911 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1912 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1913 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001914 final String networkId;
1915 if (version >= VERSION_ADDED_NETWORK_ID) {
1916 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1917 } else {
1918 networkId = null;
1919 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001920 final RecurrenceRule cycleRule;
1921 if (version >= VERSION_ADDED_CYCLE) {
1922 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1923 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1924 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1925 cycleRule = new RecurrenceRule(
1926 RecurrenceRule.convertZonedDateTime(start),
1927 RecurrenceRule.convertZonedDateTime(end),
1928 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001929 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001930 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1931 final String cycleTimezone;
1932 if (version >= VERSION_ADDED_TIMEZONE) {
1933 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1934 } else {
1935 cycleTimezone = "UTC";
1936 }
1937 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001938 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1940 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001941 final long lastLimitSnooze;
1942 if (version >= VERSION_SPLIT_SNOOZE) {
1943 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1944 } else if (version >= VERSION_ADDED_SNOOZE) {
1945 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001946 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001947 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001948 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001949 final boolean metered;
1950 if (version >= VERSION_ADDED_METERED) {
1951 metered = readBooleanAttribute(in, ATTR_METERED);
1952 } else {
1953 switch (networkTemplate) {
1954 case MATCH_MOBILE_3G_LOWER:
1955 case MATCH_MOBILE_4G:
1956 case MATCH_MOBILE_ALL:
1957 metered = true;
1958 break;
1959 default:
1960 metered = false;
1961 }
1962 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001963 final long lastWarningSnooze;
1964 if (version >= VERSION_SPLIT_SNOOZE) {
1965 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1966 } else {
1967 lastWarningSnooze = SNOOZE_NEVER;
1968 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001969 final boolean inferred;
1970 if (version >= VERSION_ADDED_INFERRED) {
1971 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1972 } else {
1973 inferred = false;
1974 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001975
Jeff Sharkey32566012014-12-02 18:30:14 -08001976 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1977 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001978 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001979 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1980 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001981 lastLimitSnooze, metered, inferred));
1982 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001983
1984 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1985 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1986 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1987 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1988 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1989 RecurrenceRule.convertZonedDateTime(start),
1990 RecurrenceRule.convertZonedDateTime(end),
1991 RecurrenceRule.convertPeriod(period));
1992 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1993 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1994
1995 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1996 SubscriptionPlan.BYTES_UNKNOWN);
1997 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1998 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1999 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2000 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2001 builder.setDataLimit(limitBytes, limitBehavior);
2002 }
2003
2004 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2005 SubscriptionPlan.BYTES_UNKNOWN);
2006 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2007 SubscriptionPlan.TIME_UNKNOWN);
2008 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2009 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2010 builder.setDataUsage(usageBytes, usageTime);
2011 }
2012
2013 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2014 final SubscriptionPlan plan = builder.build();
2015 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2016 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2017
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002018 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2019 mSubscriptionPlansOwner.put(subId, ownerPackage);
2020
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002021 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002022 final int uid = readIntAttribute(in, ATTR_UID);
2023 final int policy = readIntAttribute(in, ATTR_POLICY);
2024
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002025 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002026 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002027 } else {
2028 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2029 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002030 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002031 final int appId = readIntAttribute(in, ATTR_APP_ID);
2032 final int policy = readIntAttribute(in, ATTR_POLICY);
2033
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002034 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002035 // app policy is deprecated so this is only used in pre system user split.
2036 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002037 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002038 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002039 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002040 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002041 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002042 } else if (TAG_WHITELIST.equals(tag)) {
2043 insideWhitelist = true;
2044 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2045 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002046 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002047 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2048 final int uid = readIntAttribute(in, ATTR_UID);
2049 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002050 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002051 } else if (type == END_TAG) {
2052 if (TAG_WHITELIST.equals(tag)) {
2053 insideWhitelist = false;
2054 }
2055
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002056 }
2057 }
2058
Felipe Leme46b451f2016-08-19 08:46:17 -07002059 final int size = whitelistedRestrictBackground.size();
2060 for (int i = 0; i < size; i++) {
2061 final int uid = whitelistedRestrictBackground.keyAt(i);
2062 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2063 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2064 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2065 + " because its policy is " + uidPoliciesToString(policy));
2066 continue;
2067 }
2068 if (UserHandle.isApp(uid)) {
2069 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2070 if (LOGV)
2071 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2072 setUidPolicyUncheckedUL(uid, newPolicy, false);
2073 } else {
2074 Slog.w(TAG, "unable to update policy on UID " + uid);
2075 }
2076 }
2077
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002078 } catch (FileNotFoundException e) {
2079 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002080 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002081 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002082 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002083 } finally {
2084 IoUtils.closeQuietly(fis);
2085 }
2086 }
2087
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002088 /**
2089 * Upgrade legacy background data flags, notifying listeners of one last
2090 * change to always-true.
2091 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002092 private void upgradeDefaultBackgroundDataUL() {
2093 // This method is only called when we're unable to find the network policy flag, which
2094 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002095
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002096 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002097 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002098 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2099
2100 // NOTE: We used to read the legacy setting here :
2101 //
2102 // final int legacyFlagValue = Settings.Secure.getInt(
2103 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2104 //
2105 // This is no longer necessary because we will never upgrade directly from Gingerbread
2106 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2107 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002108 }
2109
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002110 /**
2111 * Perform upgrade step of moving any user-defined meterness overrides over
2112 * into {@link WifiConfiguration}.
2113 */
2114 private void upgradeWifiMeteredOverrideAL() {
2115 boolean modified = false;
2116 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2117 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2118 for (int i = 0; i < mNetworkPolicy.size(); ) {
2119 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2120 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2121 && !policy.inferred) {
2122 mNetworkPolicy.removeAt(i);
2123 modified = true;
2124
2125 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2126 for (WifiConfiguration config : configs) {
2127 if (Objects.equals(resolveNetworkId(config), networkId)) {
2128 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2129 config.meteredOverride = policy.metered
2130 ? WifiConfiguration.METERED_OVERRIDE_METERED
2131 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2132 wm.updateNetwork(config);
2133 }
2134 }
2135 } else {
2136 i++;
2137 }
2138 }
2139 if (modified) {
2140 writePolicyAL();
2141 }
2142 }
2143
Felipe Lemef0823852016-06-08 13:43:08 -07002144 void writePolicyAL() {
2145 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002146
2147 FileOutputStream fos = null;
2148 try {
2149 fos = mPolicyFile.startWrite();
2150
2151 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002152 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002153 out.startDocument(null, true);
2154
2155 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002156 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002157 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002158
2159 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002160 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2161 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002162 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002163 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002164
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002165 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002166 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2167 final String subscriberId = template.getSubscriberId();
2168 if (subscriberId != null) {
2169 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002170 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002171 final String networkId = template.getNetworkId();
2172 if (networkId != null) {
2173 out.attribute(null, ATTR_NETWORK_ID, networkId);
2174 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002175 writeStringAttribute(out, ATTR_CYCLE_START,
2176 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2177 writeStringAttribute(out, ATTR_CYCLE_END,
2178 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2179 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2180 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002181 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2182 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002183 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2184 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002185 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002186 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 out.endTag(null, TAG_NETWORK_POLICY);
2188 }
2189
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002190 // write all known subscription plans
2191 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2192 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002193 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002194 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2195 if (ArrayUtils.isEmpty(plans)) continue;
2196
2197 for (SubscriptionPlan plan : plans) {
2198 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2199 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002200 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002201 final RecurrenceRule cycleRule = plan.getCycleRule();
2202 writeStringAttribute(out, ATTR_CYCLE_START,
2203 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2204 writeStringAttribute(out, ATTR_CYCLE_END,
2205 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2206 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2207 RecurrenceRule.convertPeriod(cycleRule.period));
2208 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2209 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2210 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2211 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2212 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2213 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2214 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2215 }
2216 }
2217
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002218 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002219 for (int i = 0; i < mUidPolicy.size(); i++) {
2220 final int uid = mUidPolicy.keyAt(i);
2221 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002222
Jeff Sharkey497e4432011-06-14 17:27:29 -07002223 // skip writing empty policies
2224 if (policy == POLICY_NONE) continue;
2225
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002226 out.startTag(null, TAG_UID_POLICY);
2227 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002228 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002229 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002230 }
2231
2232 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002233
2234 // write all whitelists
2235 out.startTag(null, TAG_WHITELIST);
2236
Felipe Lemea9505cc2016-02-26 10:28:41 -08002237 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002238 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002239 for (int i = 0; i < size; i++) {
2240 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2241 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2242 writeIntAttribute(out, ATTR_UID, uid);
2243 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2244 }
2245
Felipe Lemeb85a6372016-01-14 16:16:16 -08002246 out.endTag(null, TAG_WHITELIST);
2247
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002248 out.endDocument();
2249
2250 mPolicyFile.finishWrite(fos);
2251 } catch (IOException e) {
2252 if (fos != null) {
2253 mPolicyFile.failWrite(fos);
2254 }
2255 }
2256 }
2257
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002258 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002259 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002260 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002261
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002262 if (!UserHandle.isApp(uid)) {
2263 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002264 }
Felipe Lemef0823852016-06-08 13:43:08 -07002265 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002266 final long token = Binder.clearCallingIdentity();
2267 try {
2268 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2269 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002270 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002271 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002272 }
2273 } finally {
2274 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002275 }
2276 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002277 }
2278
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002279 @Override
2280 public void addUidPolicy(int uid, int policy) {
2281 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002282
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002283 if (!UserHandle.isApp(uid)) {
2284 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2285 }
2286
Felipe Lemef0823852016-06-08 13:43:08 -07002287 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002288 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2289 policy |= oldPolicy;
2290 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002291 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002292 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002293 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002294 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002295 }
2296
2297 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002298 public void removeUidPolicy(int uid, int policy) {
2299 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2300
2301 if (!UserHandle.isApp(uid)) {
2302 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2303 }
2304
Felipe Lemef0823852016-06-08 13:43:08 -07002305 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002306 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2307 policy = oldPolicy & ~policy;
2308 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002309 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002310 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002311 }
2312 }
2313 }
2314
Felipe Lemef0823852016-06-08 13:43:08 -07002315 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2316 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002317
Felipe Leme57e3d312016-08-23 14:42:52 -07002318 final boolean notifyApp;
2319 if (!isUidValidForWhitelistRules(uid)) {
2320 notifyApp = false;
2321 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002322 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2323 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2324 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2325 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002326 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2327 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002328 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2329 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2330 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2331 if (LOGD)
2332 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2333 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2334 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002335 notifyApp = wasBlocked != isBlocked;
2336 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002337 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2338 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002339 }
2340
Felipe Lemef0823852016-06-08 13:43:08 -07002341 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002342 if (policy == POLICY_NONE) {
2343 mUidPolicy.delete(uid);
2344 } else {
2345 mUidPolicy.put(uid, policy);
2346 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002347
2348 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002349 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002350 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002351 synchronized (mNetworkPoliciesSecondLock) {
2352 writePolicyAL();
2353 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002354 }
2355 }
2356
2357 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002358 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002359 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2360
Felipe Lemef0823852016-06-08 13:43:08 -07002361 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002362 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002363 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002364 }
2365
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002366 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002367 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002368 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2369
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002370 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002371 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002372 for (int i = 0; i < mUidPolicy.size(); i++) {
2373 final int uid = mUidPolicy.keyAt(i);
2374 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002375 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2376 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002377 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002378 }
2379 }
2380 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002381 return uids;
2382 }
2383
2384 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002385 * Removes any persistable state associated with given {@link UserHandle}, persisting
2386 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002387 */
Felipe Lemef0823852016-06-08 13:43:08 -07002388 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002389
Sudheer Shanka352dc572017-09-22 17:09:38 -07002390 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002391 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002392
Felipe Lemea110eec2016-04-29 09:58:06 -07002393 // Remove entries from revoked default restricted background UID whitelist
2394 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2395 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2396 if (UserHandle.getUserId(uid) == userId) {
2397 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002398 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002399 }
2400 }
2401
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002402 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002403 int[] uids = new int[0];
2404 for (int i = 0; i < mUidPolicy.size(); i++) {
2405 final int uid = mUidPolicy.keyAt(i);
2406 if (UserHandle.getUserId(uid) == userId) {
2407 uids = appendInt(uids, uid);
2408 }
2409 }
2410
2411 if (uids.length > 0) {
2412 for (int uid : uids) {
2413 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002414 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002415 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002416 }
Felipe Lemef0823852016-06-08 13:43:08 -07002417 synchronized (mNetworkPoliciesSecondLock) {
2418 updateRulesForGlobalChangeAL(true);
2419 if (writePolicy && changed) {
2420 writePolicyAL();
2421 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002422 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002423 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002424 }
2425
2426 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002427 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002428 // TODO: create permission for observing network policy
2429 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002430 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002431 }
2432
2433 @Override
2434 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002435 // TODO: create permission for observing network policy
2436 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002437 mListeners.unregister(listener);
2438 }
2439
Jeff Sharkey1b861272011-05-22 00:34:52 -07002440 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002441 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002442 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2443
Felipe Leme6a05eee2016-02-19 14:43:51 -08002444 final long token = Binder.clearCallingIdentity();
2445 try {
2446 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002447 synchronized (mUidRulesFirstLock) {
2448 synchronized (mNetworkPoliciesSecondLock) {
2449 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002450 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002451 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002452 }
2453 } finally {
2454 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002455 }
2456 }
2457
Hugo Benichi446c9c92017-04-10 09:41:10 +09002458 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002459 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002460 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2461 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002462 }
2463
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002464 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002465 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002466 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002467 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002468 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2469 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2470 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002471 } catch (SecurityException e) {
2472 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002473
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002474 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2475 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2476 return new NetworkPolicy[0];
2477 }
Svet Ganov16a16892015-04-16 10:32:04 -07002478 }
2479
Felipe Lemef0823852016-06-08 13:43:08 -07002480 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002481 final int size = mNetworkPolicy.size();
2482 final NetworkPolicy[] policies = new NetworkPolicy[size];
2483 for (int i = 0; i < size; i++) {
2484 policies[i] = mNetworkPolicy.valueAt(i);
2485 }
2486 return policies;
2487 }
2488 }
2489
Felipe Lemef0823852016-06-08 13:43:08 -07002490 private void normalizePoliciesNL() {
2491 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002492 }
2493
Felipe Lemef0823852016-06-08 13:43:08 -07002494 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002495 final TelephonyManager tele = mContext.getSystemService(TelephonyManager.class);
Jeff Sharkey32566012014-12-02 18:30:14 -08002496 final String[] merged = tele.getMergedSubscriberIds();
2497
2498 mNetworkPolicy.clear();
2499 for (NetworkPolicy policy : policies) {
2500 // When two normalized templates conflict, prefer the most
2501 // restrictive policy
2502 policy.template = NetworkTemplate.normalize(policy.template, merged);
2503 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2504 if (existing == null || existing.compareTo(policy) > 0) {
2505 if (existing != null) {
2506 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2507 }
2508 mNetworkPolicy.put(policy.template, policy);
2509 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002510 }
2511 }
2512
2513 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002514 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002515 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002516
2517 final long token = Binder.clearCallingIdentity();
2518 try {
2519 performSnooze(template, TYPE_LIMIT);
2520 } finally {
2521 Binder.restoreCallingIdentity(token);
2522 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002523 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002524
Dianne Hackborn497175b2014-07-01 12:56:08 -07002525 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002526 maybeRefreshTrustedTime();
2527 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002528 synchronized (mUidRulesFirstLock) {
2529 synchronized (mNetworkPoliciesSecondLock) {
2530 // find and snooze local policy that matches
2531 final NetworkPolicy policy = mNetworkPolicy.get(template);
2532 if (policy == null) {
2533 throw new IllegalArgumentException("unable to find policy for " + template);
2534 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002535
Felipe Lemef0823852016-06-08 13:43:08 -07002536 switch (type) {
2537 case TYPE_WARNING:
2538 policy.lastWarningSnooze = currentTime;
2539 break;
2540 case TYPE_LIMIT:
2541 policy.lastLimitSnooze = currentTime;
2542 break;
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07002543 case TYPE_RAPID:
2544 policy.lastRapidSnooze = currentTime;
2545 break;
Felipe Lemef0823852016-06-08 13:43:08 -07002546 default:
2547 throw new IllegalArgumentException("unexpected type");
2548 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002549
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002550 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002551 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002552 }
2553 }
2554
2555 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002556 public void onTetheringChanged(String iface, boolean tethering) {
2557 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002558 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002559 if (mRestrictBackground && tethering) {
2560 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2561 setRestrictBackground(false);
2562 }
2563 }
2564 }
2565
2566 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002567 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002568 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002569 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002570 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2571 final long token = Binder.clearCallingIdentity();
2572 try {
2573 maybeRefreshTrustedTime();
2574 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002575 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002576 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002577 } finally {
2578 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002579 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002580 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002581 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002582 }
2583 }
2584
Felipe Lemef0823852016-06-08 13:43:08 -07002585 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002586 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002587 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002588 if (restrictBackground == mRestrictBackground) {
2589 // Ideally, UI should never allow this scenario...
2590 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002591 return;
2592 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002593 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2594 final boolean oldRestrictBackground = mRestrictBackground;
2595 mRestrictBackground = restrictBackground;
2596 // Must whitelist foreground apps before turning data saver mode on.
2597 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2598 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2599 updateRulesForRestrictBackgroundUL();
2600 try {
2601 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2602 Slog.e(TAG,
2603 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2604 mRestrictBackground = oldRestrictBackground;
2605 // TODO: if it knew the foreground apps (see TODO above), it could call
2606 // updateRulesForRestrictBackgroundUL() again to restore state.
2607 return;
2608 }
2609 } catch (RemoteException e) {
2610 // ignored; service lives in system_server
2611 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002612
Sudheer Shanka543339f2017-07-28 15:18:07 -07002613 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002614 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002615
2616 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2617 mRestrictBackgroundChangedInBsm = true;
2618 }
2619 synchronized (mNetworkPoliciesSecondLock) {
2620 updateNotificationsNL();
2621 writePolicyAL();
2622 }
2623 } finally {
2624 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002625 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002626 }
2627
2628 private void sendRestrictBackgroundChangedMsg() {
2629 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2630 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2631 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002632 }
2633
Felipe Lemeb85a6372016-01-14 16:16:16 -08002634 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002635 public int getRestrictBackgroundByCaller() {
2636 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2637 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002638
Felipe Lemef0823852016-06-08 13:43:08 -07002639 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002640 // Must clear identity because getUidPolicy() is restricted to system.
2641 final long token = Binder.clearCallingIdentity();
2642 final int policy;
2643 try {
2644 policy = getUidPolicy(uid);
2645 } finally {
2646 Binder.restoreCallingIdentity(token);
2647 }
2648 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2649 // App is blacklisted.
2650 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2651 }
Felipe Leme1b103232016-01-22 09:44:57 -08002652 if (!mRestrictBackground) {
2653 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2654 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002655 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002656 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2657 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2658 }
2659 }
2660
2661 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002662 public boolean getRestrictBackground() {
2663 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2664
Felipe Lemef0823852016-06-08 13:43:08 -07002665 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002666 return mRestrictBackground;
2667 }
2668 }
2669
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002670 @Override
2671 public void setDeviceIdleMode(boolean enabled) {
2672 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002673 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2674 try {
2675 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002676 if (mDeviceIdleMode == enabled) {
2677 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002678 }
Felipe Lemeea014392016-09-06 13:59:54 -07002679 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002680 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002681 if (mSystemReady) {
2682 // Device idle change means we need to rebuild rules for all
2683 // known apps, so do a global refresh.
2684 updateRulesForRestrictPowerUL();
2685 }
2686 }
2687 if (enabled) {
2688 EventLogTags.writeDeviceIdleOnPhase("net");
2689 } else {
2690 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002691 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002692 } finally {
2693 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002694 }
2695 }
2696
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002697 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002698 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2699 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002700 final long token = Binder.clearCallingIdentity();
2701 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002702 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2703 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2704 for (WifiConfiguration config : configs) {
2705 if (Objects.equals(resolveNetworkId(config), networkId)) {
2706 config.meteredOverride = meteredOverride;
2707 wm.updateNetwork(config);
2708 }
2709 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002710 } finally {
2711 Binder.restoreCallingIdentity(token);
2712 }
2713 }
2714
Jeff Sharkey46645002011-07-27 21:11:21 -07002715 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002716 @Deprecated
2717 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2718 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2719 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2720 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002721 }
2722
Jeff Sharkey53313d72017-07-13 16:47:32 -06002723 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2724 // Verify they're not lying about package name
2725 mAppOps.checkPackage(callingUid, callingPackage);
2726
Jeff Sharkey53313d72017-07-13 16:47:32 -06002727 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002728 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002729 final long token = Binder.clearCallingIdentity();
2730 try {
2731 si = mContext.getSystemService(SubscriptionManager.class)
2732 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002733 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002734 } finally {
2735 Binder.restoreCallingIdentity(token);
2736 }
2737
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002738 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002739 if (si != null) {
2740 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2741 return;
2742 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002743 }
2744
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002745 // Second check: has the CarrierService delegated access?
2746 if (config != null) {
2747 final String overridePackage = config
2748 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2749 if (!TextUtils.isEmpty(overridePackage)
2750 && Objects.equals(overridePackage, callingPackage)) {
2751 return;
2752 }
2753 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002754
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002755 // Third check: is caller the fallback/default CarrierService?
2756 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2757 if (!TextUtils.isEmpty(defaultPackage)
2758 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002759 return;
2760 }
2761
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002762 // Final check: does the caller hold a permission?
2763 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002764 }
2765
2766 @Override
2767 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2768 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2769
Jeff Sharkey53313d72017-07-13 16:47:32 -06002770 final String fake = SystemProperties.get("fw.fake_plan");
2771 if (!TextUtils.isEmpty(fake)) {
2772 final List<SubscriptionPlan> plans = new ArrayList<>();
2773 if ("month_hard".equals(fake)) {
2774 plans.add(SubscriptionPlan.Builder
2775 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2776 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002777 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2778 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2779 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2780 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2781 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002782 plans.add(SubscriptionPlan.Builder
2783 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2784 .setTitle("G-Mobile Happy")
2785 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2786 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2787 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2788 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2789 .build());
2790 plans.add(SubscriptionPlan.Builder
2791 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2792 .setTitle("G-Mobile, Charged after limit")
2793 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2794 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2795 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2796 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2797 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002798 } else if ("month_soft".equals(fake)) {
2799 plans.add(SubscriptionPlan.Builder
2800 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2801 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2802 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2803 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002804 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2805 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2806 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2807 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2808 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002809 plans.add(SubscriptionPlan.Builder
2810 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2811 .setTitle("G-Mobile, Throttled after limit")
2812 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2813 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2814 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2815 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2816 .build());
2817 plans.add(SubscriptionPlan.Builder
2818 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2819 .setTitle("G-Mobile, No data connection after limit")
2820 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2821 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2822 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2823 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2824 .build());
2825
Jeff Sharkey53313d72017-07-13 16:47:32 -06002826 } else if ("month_none".equals(fake)) {
2827 plans.add(SubscriptionPlan.Builder
2828 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2829 .setTitle("G-Mobile")
2830 .build());
2831 } else if ("prepaid".equals(fake)) {
2832 plans.add(SubscriptionPlan.Builder
2833 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2834 ZonedDateTime.now().plusDays(10))
2835 .setTitle("G-Mobile")
2836 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2837 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2838 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2839 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2840 .build());
2841 } else if ("prepaid_crazy".equals(fake)) {
2842 plans.add(SubscriptionPlan.Builder
2843 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2844 ZonedDateTime.now().plusDays(10))
2845 .setTitle("G-Mobile Anytime")
2846 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2847 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2848 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2849 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2850 .build());
2851 plans.add(SubscriptionPlan.Builder
2852 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2853 ZonedDateTime.now().plusDays(20))
2854 .setTitle("G-Mobile Nickel Nights")
2855 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002856 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2857 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002858 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2859 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2860 .build());
2861 plans.add(SubscriptionPlan.Builder
2862 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2863 ZonedDateTime.now().plusDays(20))
2864 .setTitle("G-Mobile Bonus 3G")
2865 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002866 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002867 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2868 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2869 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2870 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002871 } else if ("unlimited".equals(fake)) {
2872 plans.add(SubscriptionPlan.Builder
2873 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2874 ZonedDateTime.now().plusDays(10))
2875 .setTitle("G-Mobile Awesome")
2876 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2877 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2878 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2879 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2880 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002881 }
2882 return plans.toArray(new SubscriptionPlan[plans.size()]);
2883 }
2884
Jeff Sharkey4635f102017-09-01 11:27:13 -06002885 synchronized (mNetworkPoliciesSecondLock) {
2886 // Only give out plan details to the package that defined them,
2887 // so that we don't risk leaking plans between apps. We always
2888 // let in core system components (like the Settings app).
2889 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2890 if (Objects.equals(ownerPackage, callingPackage)
2891 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2892 return mSubscriptionPlans.get(subId);
2893 } else {
2894 Log.w(TAG, "Not returning plans because caller " + callingPackage
2895 + " doesn't match owner " + ownerPackage);
2896 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002897 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002898 }
2899 }
2900
2901 @Override
2902 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2903 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2904
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002905 for (SubscriptionPlan plan : plans) {
2906 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002907 }
2908
2909 final long token = Binder.clearCallingIdentity();
2910 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002911 maybeRefreshTrustedTime();
2912 synchronized (mUidRulesFirstLock) {
2913 synchronized (mNetworkPoliciesSecondLock) {
2914 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002915 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002916
2917 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2918 .getSubscriberId(subId);
2919 ensureActiveMobilePolicyAL(subId, subscriberId);
2920 maybeUpdateMobilePolicyCycleAL(subId);
2921 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002922 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002923 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002924
2925 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2926 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2927 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2928 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002929 } finally {
2930 Binder.restoreCallingIdentity(token);
2931 }
2932 }
2933
2934 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002935 public String getSubscriptionPlansOwner(int subId) {
2936 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2937 throw new SecurityException();
2938 }
2939
2940 synchronized (mNetworkPoliciesSecondLock) {
2941 return mSubscriptionPlansOwner.get(subId);
2942 }
2943 }
2944
2945 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09002946 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
2947 long timeoutMillis, String callingPackage) {
2948 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2949
2950 // We can only override when carrier told us about plans
2951 synchronized (mNetworkPoliciesSecondLock) {
2952 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
2953 throw new IllegalStateException(
2954 "Must provide SubscriptionPlan information before overriding");
2955 }
2956 }
2957
2958 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2959 overrideMask, overrideValue, subId));
2960 if (timeoutMillis > 0) {
2961 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2962 overrideMask, 0, subId), timeoutMillis);
2963 }
2964 }
2965
2966 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002967 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002968 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002969
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002970 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2971
Dianne Hackborn497175b2014-07-01 12:56:08 -07002972 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002973 for (String arg : args) {
2974 argSet.add(arg);
2975 }
2976
Felipe Lemef0823852016-06-08 13:43:08 -07002977 synchronized (mUidRulesFirstLock) {
2978 synchronized (mNetworkPoliciesSecondLock) {
2979 if (argSet.contains("--unsnooze")) {
2980 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2981 mNetworkPolicy.valueAt(i).clearSnooze();
2982 }
2983
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002984 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002985
2986 fout.println("Cleared snooze timestamps");
2987 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002988 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002989
Felipe Lemef0823852016-06-08 13:43:08 -07002990 fout.print("System ready: "); fout.println(mSystemReady);
2991 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2992 fout.print("Restrict power: "); fout.println(mRestrictPower);
2993 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002994 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2995
2996 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002997 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002998 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002999 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3000 fout.println(mNetworkPolicy.valueAt(i).toString());
3001 }
3002 fout.decreaseIndent();
3003
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003004 fout.println();
3005 fout.println("Subscription plans:");
3006 fout.increaseIndent();
3007 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3008 final int subId = mSubscriptionPlans.keyAt(i);
3009 fout.println("Subscriber ID " + subId + ":");
3010 fout.increaseIndent();
3011 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3012 if (!ArrayUtils.isEmpty(plans)) {
3013 for (SubscriptionPlan plan : plans) {
3014 fout.println(plan);
3015 }
3016 }
3017 fout.decreaseIndent();
3018 }
3019 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003020
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003021 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003022 fout.println("Policy for UIDs:");
3023 fout.increaseIndent();
3024 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003025 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003026 final int uid = mUidPolicy.keyAt(i);
3027 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003028 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003029 fout.print(uid);
3030 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003031 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003032 fout.println();
3033 }
3034 fout.decreaseIndent();
3035
3036 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3037 if (size > 0) {
3038 fout.println("Power save whitelist (except idle) app ids:");
3039 fout.increaseIndent();
3040 for (int i = 0; i < size; i++) {
3041 fout.print("UID=");
3042 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3043 fout.print(": ");
3044 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3045 fout.println();
3046 }
3047 fout.decreaseIndent();
3048 }
3049
3050 size = mPowerSaveWhitelistAppIds.size();
3051 if (size > 0) {
3052 fout.println("Power save whitelist app ids:");
3053 fout.increaseIndent();
3054 for (int i = 0; i < size; i++) {
3055 fout.print("UID=");
3056 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3057 fout.print(": ");
3058 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3059 fout.println();
3060 }
3061 fout.decreaseIndent();
3062 }
3063
Felipe Lemef0823852016-06-08 13:43:08 -07003064 size = mDefaultRestrictBackgroundWhitelistUids.size();
3065 if (size > 0) {
3066 fout.println("Default restrict background whitelist uids:");
3067 fout.increaseIndent();
3068 for (int i = 0; i < size; i++) {
3069 fout.print("UID=");
3070 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3071 fout.println();
3072 }
3073 fout.decreaseIndent();
3074 }
3075
3076 size = mRestrictBackgroundWhitelistRevokedUids.size();
3077 if (size > 0) {
3078 fout.println("Default restrict background whitelist uids revoked by users:");
3079 fout.increaseIndent();
3080 for (int i = 0; i < size; i++) {
3081 fout.print("UID=");
3082 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3083 fout.println();
3084 }
3085 fout.decreaseIndent();
3086 }
3087
3088 final SparseBooleanArray knownUids = new SparseBooleanArray();
3089 collectKeys(mUidState, knownUids);
3090 collectKeys(mUidRules, knownUids);
3091
3092 fout.println("Status for all known UIDs:");
3093 fout.increaseIndent();
3094 size = knownUids.size();
3095 for (int i = 0; i < size; i++) {
3096 final int uid = knownUids.keyAt(i);
3097 fout.print("UID=");
3098 fout.print(uid);
3099
3100 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3101 fout.print(" state=");
3102 fout.print(state);
3103 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3104 fout.print(" (fg)");
3105 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003106 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003107 ? " (fg svc)" : " (bg)");
3108 }
3109
3110 final int uidRules = mUidRules.get(uid, RULE_NONE);
3111 fout.print(" rules=");
3112 fout.print(uidRulesToString(uidRules));
3113 fout.println();
3114 }
3115 fout.decreaseIndent();
3116
3117 fout.println("Status for just UIDs with rules:");
3118 fout.increaseIndent();
3119 size = mUidRules.size();
3120 for (int i = 0; i < size; i++) {
3121 final int uid = mUidRules.keyAt(i);
3122 fout.print("UID=");
3123 fout.print(uid);
3124 final int uidRules = mUidRules.get(uid, RULE_NONE);
3125 fout.print(" rules=");
3126 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003127 fout.println();
3128 }
3129 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003130
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003131 fout.println("Admin restricted uids for metered data:");
3132 fout.increaseIndent();
3133 size = mMeteredRestrictedUids.size();
3134 for (int i = 0; i < size; ++i) {
3135 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3136 fout.println(mMeteredRestrictedUids.valueAt(i));
3137 }
3138 fout.decreaseIndent();
3139
Sudheer Shanka352dc572017-09-22 17:09:38 -07003140 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003141 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003142 }
3143 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003144
3145 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003146 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003147 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003148 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003149 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003150 }
3151
3152 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003153 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003154 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3155
Felipe Lemef0823852016-06-08 13:43:08 -07003156 synchronized (mUidRulesFirstLock) {
3157 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003158 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003159 }
3160
Felipe Lemef0823852016-06-08 13:43:08 -07003161 private boolean isUidForegroundUL(int uid) {
3162 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003163 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3164 }
3165
Felipe Lemef0823852016-06-08 13:43:08 -07003166 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003167 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003168 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003169 }
3170
Felipe Lemef0823852016-06-08 13:43:08 -07003171 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003172 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3173 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3174 }
3175
Felipe Lemef0823852016-06-08 13:43:08 -07003176 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003177 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003178 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003179 }
3180
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003181 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003182 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003183 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3184 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003185 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003186 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003187 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3188 try {
3189 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3190 if (oldUidState != uidState) {
3191 // state changed, push updated rules
3192 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003193 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3194 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3195 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003196 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003197 if (mDeviceIdleMode) {
3198 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003199 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003200 if (mRestrictPower) {
3201 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003202 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003203 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003204 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003205 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003206 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003207 } finally {
3208 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003209 }
3210 }
3211
Felipe Lemef0823852016-06-08 13:43:08 -07003212 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003213 final int index = mUidState.indexOfKey(uid);
3214 if (index >= 0) {
3215 final int oldUidState = mUidState.valueAt(index);
3216 mUidState.removeAt(index);
3217 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003218 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003219 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003220 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003221 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003222 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003223 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003224 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003225 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003226 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003227 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003228 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003229 }
3230 }
3231
Felipe Lemef28983d2016-03-25 12:18:23 -07003232 // adjust stats accounting based on foreground status
3233 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003234 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3235 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3236 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3237 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003238 try {
3239 mNetworkStats.setUidForeground(uid, uidForeground);
3240 } catch (RemoteException e) {
3241 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003242 } finally {
3243 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003244 }
3245 }
3246
Sudheer Shankac9d94072017-02-22 22:13:55 +00003247 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3248 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003249 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003250 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003251 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003252 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003253 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003254 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003255 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003256 }
3257
Felipe Lemef0823852016-06-08 13:43:08 -07003258 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003259 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3260 try {
3261 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3262 mUidFirewallPowerSaveRules);
3263 } finally {
3264 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3265 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003266 }
3267
Felipe Lemef0823852016-06-08 13:43:08 -07003268 void updateRuleForRestrictPowerUL(int uid) {
3269 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003270 }
3271
Felipe Lemef0823852016-06-08 13:43:08 -07003272 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003273 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3274 try {
3275 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3276 mUidFirewallDozableRules);
3277 } finally {
3278 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3279 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003280 }
3281
Felipe Lemef0823852016-06-08 13:43:08 -07003282 void updateRuleForDeviceIdleUL(int uid) {
3283 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003284 }
3285
Felipe Lemef28983d2016-03-25 12:18:23 -07003286 // NOTE: since both fw_dozable and fw_powersave uses the same map
3287 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003288 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003289 SparseIntArray rules) {
3290 if (enabled) {
3291 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003292 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003293 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003294 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003295 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003296 for (int ui = users.size() - 1; ui >= 0; ui--) {
3297 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003298 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3299 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3300 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3301 updateRulesForWhitelistedAppIds(uidRules,
3302 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003303 }
3304 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003305 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003306 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003307 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3308 }
3309 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003310 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003311 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003312 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003313 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003314 }
3315
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003316 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3317 final SparseBooleanArray whitelistedAppIds, int userId) {
3318 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3319 if (whitelistedAppIds.valueAt(i)) {
3320 final int appId = whitelistedAppIds.keyAt(i);
3321 final int uid = UserHandle.getUid(userId, appId);
3322 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3323 }
3324 }
3325 }
3326
3327 /**
3328 * @param deviceIdleMode if true then we don't consider
3329 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3330 * whitelisted.
3331 */
3332 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003333 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003334 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3335 || mPowerSaveWhitelistAppIds.get(appId);
3336 if (!deviceIdleMode) {
3337 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3338 }
3339 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003340 }
3341
Felipe Lemef28983d2016-03-25 12:18:23 -07003342 // NOTE: since both fw_dozable and fw_powersave uses the same map
3343 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003344 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003345 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003346 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3347 chain == FIREWALL_CHAIN_DOZABLE);
3348 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003349 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003350 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003351 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003352 }
3353 }
3354 }
3355
Felipe Lemef0823852016-06-08 13:43:08 -07003356 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003357 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3358 try {
3359 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3360 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003361
Felipe Leme873a83a2016-09-07 11:34:10 -07003362 // Fully update the app idle firewall chain.
3363 final List<UserInfo> users = mUserManager.getUsers();
3364 for (int ui = users.size() - 1; ui >= 0; ui--) {
3365 UserInfo user = users.get(ui);
3366 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3367 for (int uid : idleUids) {
3368 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3369 // quick check: if this uid doesn't have INTERNET permission, it
3370 // doesn't have network access anyway, so it is a waste to mess
3371 // with it here.
3372 if (hasInternetPermissions(uid)) {
3373 uidRules.put(uid, FIREWALL_RULE_DENY);
3374 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003375 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003376 }
3377 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003378
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003379 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003380 } finally {
3381 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3382 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003383 }
3384
Felipe Lemef0823852016-06-08 13:43:08 -07003385 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003386 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003387
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003388 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3389 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3390 }
3391 try {
3392 int appId = UserHandle.getAppId(uid);
3393 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3394 && !isUidForegroundOnRestrictPowerUL(uid)) {
3395 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3396 } else {
3397 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3398 }
3399 } finally {
3400 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003401 }
3402 }
3403
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003404 /**
3405 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3406 * changed.
3407 */
Felipe Lemef0823852016-06-08 13:43:08 -07003408 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003409 boolean paroled = mUsageStats.isAppIdleParoleOn();
3410 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003411 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003412
3413 int ruleCount = mUidFirewallStandbyRules.size();
3414 for (int i = 0; i < ruleCount; i++) {
3415 int uid = mUidFirewallStandbyRules.keyAt(i);
3416 int oldRules = mUidRules.get(uid);
3417 if (enableChain) {
3418 // Chain wasn't enabled before and the other power-related
3419 // chains are whitelists, so we can clear the
3420 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3421 // the effective rules result in blocking network access.
3422 oldRules &= MASK_METERED_NETWORKS;
3423 } else {
3424 // Skip if it had no restrictions to begin with
3425 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3426 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003427 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3428 if (newUidRules == RULE_NONE) {
3429 mUidRules.delete(uid);
3430 } else {
3431 mUidRules.put(uid, newUidRules);
3432 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003433 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003434 }
3435
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003436 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003437 * Update rules that might be changed by {@link #mRestrictBackground},
3438 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003439 */
Felipe Lemef0823852016-06-08 13:43:08 -07003440 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003441 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3442 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3443 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3444 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003445 try {
Felipe Leme09700462016-09-08 09:33:48 -07003446 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003447 updateRulesForRestrictPowerUL();
3448 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003449
Felipe Leme873a83a2016-09-07 11:34:10 -07003450 // If the set of restricted networks may have changed, re-evaluate those.
3451 if (restrictedNetworksChanged) {
3452 normalizePoliciesNL();
3453 updateNetworkRulesNL();
3454 }
3455 } finally {
3456 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003457 }
3458 }
3459
Felipe Leme09700462016-09-08 09:33:48 -07003460 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003461 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003462 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3463 try {
3464 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003465 updateRulesForPowerSaveUL();
3466 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3467 } finally {
3468 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3469 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003470 }
3471
Felipe Lemef0823852016-06-08 13:43:08 -07003472 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003473 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3474 try {
3475 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3476 } finally {
3477 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3478 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003479 }
3480
3481 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3482 private static final int TYPE_RESTRICT_POWER = 2;
3483 @Retention(RetentionPolicy.SOURCE)
3484 @IntDef(flag = false, value = {
3485 TYPE_RESTRICT_BACKGROUND,
3486 TYPE_RESTRICT_POWER,
3487 })
3488 public @interface RestrictType {
3489 }
3490
3491 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003492 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003493 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3494 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3495 }
3496 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003497 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003498
3499 final PackageManager pm = mContext.getPackageManager();
3500 final List<UserInfo> users;
3501 final List<ApplicationInfo> apps;
3502
3503 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3504 try {
3505 users = mUserManager.getUsers();
3506 } finally {
3507 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3508 }
3509 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3510 try {
3511 apps = pm.getInstalledApplications(
3512 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3513 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3514 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3515 } finally {
3516 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3517 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003518
Felipe Leme873a83a2016-09-07 11:34:10 -07003519 final int usersSize = users.size();
3520 final int appsSize = apps.size();
3521 for (int i = 0; i < usersSize; i++) {
3522 final UserInfo user = users.get(i);
3523 for (int j = 0; j < appsSize; j++) {
3524 final ApplicationInfo app = apps.get(j);
3525 final int uid = UserHandle.getUid(user.id, app.uid);
3526 switch (type) {
3527 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003528 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003529 break;
3530 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003531 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003532 break;
3533 default:
3534 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3535 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003536 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003537 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003538 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003539 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003540 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003541 }
3542
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003543 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003544 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003545 final int numUsers = users.size();
3546 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003547 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003548 int uid = UserHandle.getUid(user.id, appId);
3549 // Update external firewall rules.
3550 updateRuleForAppIdleUL(uid);
3551 updateRuleForDeviceIdleUL(uid);
3552 updateRuleForRestrictPowerUL(uid);
3553 // Update internal rules.
3554 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003555 }
3556 }
3557
Felipe Leme70c57c22016-03-29 10:45:13 -07003558 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3559 // methods below could be merged into a isUidValidForRules() method.
3560 private boolean isUidValidForBlacklistRules(int uid) {
3561 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003562 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003563 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003564 return true;
3565 }
3566
3567 return false;
3568 }
3569
Felipe Leme70c57c22016-03-29 10:45:13 -07003570 private boolean isUidValidForWhitelistRules(int uid) {
3571 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3572 }
3573
Amith Yamasani15e472352015-04-24 19:06:07 -07003574 private boolean isUidIdle(int uid) {
3575 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3576 final int userId = UserHandle.getUserId(uid);
3577
songjinshi0655edd2016-05-18 19:55:32 +08003578 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003579 for (String packageName : packages) {
3580 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3581 return false;
3582 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003583 }
3584 }
3585 return true;
3586 }
3587
3588 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003589 * Checks if an uid has INTERNET permissions.
3590 * <p>
3591 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003592 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003593 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003594 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003595 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003596 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003597 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003598 }
3599 } catch (RemoteException e) {
3600 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003601 return true;
3602 }
3603
3604 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003605 * Clears all state - internal and external - associated with an UID.
3606 */
3607 private void onUidDeletedUL(int uid) {
3608 // First cleanup in-memory state synchronously...
3609 mUidRules.delete(uid);
3610 mUidPolicy.delete(uid);
3611 mUidFirewallStandbyRules.delete(uid);
3612 mUidFirewallDozableRules.delete(uid);
3613 mUidFirewallPowerSaveRules.delete(uid);
3614 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3615 mPowerSaveWhitelistAppIds.delete(uid);
3616 mPowerSaveTempWhitelistAppIds.delete(uid);
3617
3618 // ...then update iptables asynchronously.
3619 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3620 }
3621
3622 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003623 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003624 *
Felipe Leme781ba142016-05-09 16:24:48 -07003625 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003626 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003627 * <li>Doze mode
3628 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003629 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003630 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003631 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003632 *
3633 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003634 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003635 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003636 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003637 updateRuleForDeviceIdleUL(uid);
3638 updateRuleForAppIdleUL(uid);
3639 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003640
3641 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003642 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003643
3644 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003645 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003646 }
3647
Felipe Leme70c57c22016-03-29 10:45:13 -07003648 /**
3649 * Applies network rules to bandwidth controllers based on process state and user-defined
3650 * restrictions (blacklist / whitelist).
3651 *
3652 * <p>
3653 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3654 * networks:
3655 * <ul>
3656 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3657 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3658 * also blacklisted.
3659 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3660 * no UIDs other those whitelisted will have access.
3661 * <ul>
3662 *
3663 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3664 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3665 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3666 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003667 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003668 * {@link INetworkManagementService}, but this method should also be called in events (like
3669 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3670 * following rules should also be applied:
3671 *
3672 * <ul>
3673 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3674 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3675 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3676 * {@code bw_penalty_box}.
3677 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3678 * </ul>
3679 *
3680 * <p>For optimization, the rules are only applied on user apps that have internet access
3681 * permission, since there is no need to change the {@code iptables} rule if the app does not
3682 * have permission to use the internet.
3683 *
3684 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003685 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003686 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003687 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003688 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3689 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3690 "updateRulesForDataUsageRestrictionsUL: " + uid);
3691 }
3692 try {
3693 updateRulesForDataUsageRestrictionsULInner(uid);
3694 } finally {
3695 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3696 }
3697 }
3698
3699 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003700 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003701 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003702 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003703 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003704
Dianne Hackborn497175b2014-07-01 12:56:08 -07003705 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003706 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003707 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003708 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003709
Felipe Leme781ba142016-05-09 16:24:48 -07003710 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003711 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003712 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3713 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003714
Felipe Leme70c57c22016-03-29 10:45:13 -07003715 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003716 if (isRestrictedByAdmin) {
3717 newRule = RULE_REJECT_METERED;
3718 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003719 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3720 newRule = RULE_TEMPORARY_ALLOW_METERED;
3721 } else if (isWhitelisted) {
3722 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003723 }
3724 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003725 if (isBlacklisted) {
3726 newRule = RULE_REJECT_METERED;
3727 } else if (mRestrictBackground && isWhitelisted) {
3728 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003729 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003730 }
Felipe Leme781ba142016-05-09 16:24:48 -07003731 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003732
Felipe Lemef28983d2016-03-25 12:18:23 -07003733 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003734 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003735 + ": isForeground=" +isForeground
3736 + ", isBlacklisted=" + isBlacklisted
3737 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003738 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003739 + ", oldRule=" + uidRulesToString(oldRule)
3740 + ", newRule=" + uidRulesToString(newRule)
3741 + ", newUidRules=" + uidRulesToString(newUidRules)
3742 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003743 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003744
Felipe Leme46c4fc32016-05-04 09:21:43 -07003745 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003746 mUidRules.delete(uid);
3747 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003748 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003749 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003750
Felipe Leme70c57c22016-03-29 10:45:13 -07003751 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003752 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003753 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003754 // Temporarily whitelist foreground app, removing from blacklist if necessary
3755 // (since bw_penalty_box prevails over bw_happy_box).
3756
3757 setMeteredNetworkWhitelist(uid, true);
3758 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3759 // but ideally it should be just:
3760 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003761 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003762 setMeteredNetworkBlacklist(uid, false);
3763 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003764 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003765 // Remove temporary whitelist from app that is not on foreground anymore.
3766
3767 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3768 // but ideally they should be just:
3769 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3770 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003771 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003772 setMeteredNetworkWhitelist(uid, false);
3773 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003774 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003775 setMeteredNetworkBlacklist(uid, true);
3776 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003777 } else if (hasRule(newRule, RULE_REJECT_METERED)
3778 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003779 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003780 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003781 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003782 // Since blacklist prevails over whitelist, we need to handle the special case
3783 // where app is whitelisted and blacklisted at the same time (although such
3784 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003785 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003786 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003787 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3788 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003789 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003790 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003791 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003792 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003793 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3794 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003795 + ", whitelisted=" + isWhitelisted
3796 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003797 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003798 + ", newRule=" + uidRulesToString(newUidRules)
3799 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003800 }
Felipe Leme781ba142016-05-09 16:24:48 -07003801
Sudheer Shankac9d94072017-02-22 22:13:55 +00003802 // Dispatch changed rule to existing listeners.
3803 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003804 }
3805 }
3806
3807 /**
3808 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3809 * listeners in case of change.
3810 * <p>
3811 * There are 3 power-related rules that affects whether an app has background access on
3812 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3813 * restriction, it's added to the equivalent firewall chain:
3814 * <ul>
3815 * <li>App is idle: {@code fw_standby} firewall chain.
3816 * <li>Device is idle: {@code fw_dozable} firewall chain.
3817 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3818 * </ul>
3819 * <p>
3820 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3821 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3822 * <p>
3823 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3824 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003825 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003826 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3827
Sudheer Shankac9d94072017-02-22 22:13:55 +00003828 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003829
Sudheer Shankac9d94072017-02-22 22:13:55 +00003830 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003831 mUidRules.delete(uid);
3832 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003833 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003834 }
3835 }
3836
3837 /**
3838 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3839 *
3840 * @param uid the uid of the app to update rules for
3841 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3842 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3843 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003844 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003845 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003846 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003847 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3848 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3849 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3850 + (paroled ? "P" : "-"));
3851 }
3852 try {
3853 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3854 } finally {
3855 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3856 }
3857 }
3858
3859 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003860 if (!isUidValidForBlacklistRules(uid)) {
3861 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003862 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003863 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003864
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003865 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003866 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003867 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003868
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003869 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003870 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3871 int newRule = RULE_NONE;
3872
3873 // First step: define the new rule based on user restrictions and foreground state.
3874
3875 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3876 // by considering the foreground and non-foreground states.
3877 if (isForeground) {
3878 if (restrictMode) {
3879 newRule = RULE_ALLOW_ALL;
3880 }
3881 } else if (restrictMode) {
3882 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3883 }
3884
3885 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3886
3887 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003888 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003889 + ", isIdle: " + isIdle
3890 + ", mRestrictPower: " + mRestrictPower
3891 + ", mDeviceIdleMode: " + mDeviceIdleMode
3892 + ", isForeground=" + isForeground
3893 + ", isWhitelisted=" + isWhitelisted
3894 + ", oldRule=" + uidRulesToString(oldRule)
3895 + ", newRule=" + uidRulesToString(newRule)
3896 + ", newUidRules=" + uidRulesToString(newUidRules)
3897 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3898 }
3899
Felipe Leme781ba142016-05-09 16:24:48 -07003900 // Second step: notify listeners if state changed.
3901 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003902 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003903 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003904 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003905 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3906 } else {
3907 // All scenarios should have been covered above
3908 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3909 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003910 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003911 + ", newRule=" + uidRulesToString(newUidRules)
3912 + ", oldRule=" + uidRulesToString(oldUidRules));
3913 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003914 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003915 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003916
Sudheer Shankac9d94072017-02-22 22:13:55 +00003917 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003918 }
3919
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003920 private class AppIdleStateChangeListener
3921 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3922
3923 @Override
Amith Yamasani84cd7b72017-11-07 13:59:37 -08003924 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003925 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003926 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3927 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003928 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003929 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003930 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003931 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003932 }
3933 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003934 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003935 }
3936
3937 @Override
3938 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003939 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003940 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003941 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003942 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003943 }
3944 }
3945
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003946 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3947 if (listener != null) {
3948 try {
3949 listener.onUidRulesChanged(uid, uidRules);
3950 } catch (RemoteException ignored) {
3951 }
3952 }
3953 }
3954
3955 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3956 String[] meteredIfaces) {
3957 if (listener != null) {
3958 try {
3959 listener.onMeteredIfacesChanged(meteredIfaces);
3960 } catch (RemoteException ignored) {
3961 }
3962 }
3963 }
3964
3965 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3966 boolean restrictBackground) {
3967 if (listener != null) {
3968 try {
3969 listener.onRestrictBackgroundChanged(restrictBackground);
3970 } catch (RemoteException ignored) {
3971 }
3972 }
3973 }
3974
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003975 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3976 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003977 if (listener != null) {
3978 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003979 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003980 } catch (RemoteException ignored) {
3981 }
3982 }
3983 }
3984
Jeff Sharkey9252b342018-01-19 07:58:35 +09003985 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
3986 int overrideMask, int overrideValue) {
3987 if (listener != null) {
3988 try {
3989 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
3990 } catch (RemoteException ignored) {
3991 }
3992 }
3993 }
3994
Makoto Onuki8e777332017-03-28 11:25:47 -07003995 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003996 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003997 public boolean handleMessage(Message msg) {
3998 switch (msg.what) {
3999 case MSG_RULES_CHANGED: {
4000 final int uid = msg.arg1;
4001 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004002 final int length = mListeners.beginBroadcast();
4003 for (int i = 0; i < length; i++) {
4004 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4005 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004006 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004007 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004008 return true;
4009 }
4010 case MSG_METERED_IFACES_CHANGED: {
4011 final String[] meteredIfaces = (String[]) msg.obj;
4012 final int length = mListeners.beginBroadcast();
4013 for (int i = 0; i < length; i++) {
4014 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004015 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004016 }
4017 mListeners.finishBroadcast();
4018 return true;
4019 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004020 case MSG_LIMIT_REACHED: {
4021 final String iface = (String) msg.obj;
4022
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004023 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07004024 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004025 if (mMeteredIfaces.contains(iface)) {
4026 try {
4027 // force stats update to make sure we have
4028 // numbers that caused alert to trigger.
4029 mNetworkStats.forceUpdate();
4030 } catch (RemoteException e) {
4031 // ignored; service lives in system_server
4032 }
4033
Felipe Lemef0823852016-06-08 13:43:08 -07004034 updateNetworkEnabledNL();
4035 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004036 }
4037 }
4038 return true;
4039 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004040 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4041 final boolean restrictBackground = msg.arg1 != 0;
4042 final int length = mListeners.beginBroadcast();
4043 for (int i = 0; i < length; i++) {
4044 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004045 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004046 }
4047 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004048 final Intent intent =
4049 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4050 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4051 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4052 return true;
4053 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004054 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004055 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004056 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004057 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004058 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004059 final int length = mListeners.beginBroadcast();
4060 for (int i = 0; i < length; i++) {
4061 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004062 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004063 }
4064 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004065 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4066 if (notifyApp.booleanValue()) {
4067 broadcastRestrictBackgroundChanged(uid, notifyApp);
4068 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004069 return true;
4070 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004071 case MSG_ADVISE_PERSIST_THRESHOLD: {
4072 final long lowestRule = (Long) msg.obj;
4073 try {
4074 // make sure stats are recorded frequently enough; we aim
4075 // for 2MB threshold for 2GB/month rules.
4076 final long persistThreshold = lowestRule / 1000;
4077 mNetworkStats.advisePersistThreshold(persistThreshold);
4078 } catch (RemoteException e) {
4079 // ignored; service lives in system_server
4080 }
4081 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004082 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004083 case MSG_UPDATE_INTERFACE_QUOTA: {
4084 removeInterfaceQuota((String) msg.obj);
4085 // int params need to be stitched back into a long
4086 setInterfaceQuota((String) msg.obj,
4087 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4088 return true;
4089 }
4090 case MSG_REMOVE_INTERFACE_QUOTA: {
4091 removeInterfaceQuota((String) msg.obj);
4092 return true;
4093 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004094 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4095 resetUidFirewallRules(msg.arg1);
4096 return true;
4097 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004098 case MSG_SUBSCRIPTION_OVERRIDE: {
4099 final int overrideMask = msg.arg1;
4100 final int overrideValue = msg.arg2;
4101 final int subId = (int) msg.obj;
4102 final int length = mListeners.beginBroadcast();
4103 for (int i = 0; i < length; i++) {
4104 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4105 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4106 }
4107 mListeners.finishBroadcast();
4108 return true;
4109 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004110 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4111 final int userId = msg.arg1;
4112 final Set<String> packageNames = (Set<String>) msg.obj;
4113 setMeteredRestrictedPackagesInternal(packageNames, userId);
4114 return true;
4115 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004116 default: {
4117 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004118 }
4119 }
4120 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004121 };
4122
4123 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4124 @Override
4125 public boolean handleMessage(Message msg) {
4126 switch (msg.what) {
4127 case UID_MSG_STATE_CHANGED: {
4128 final int uid = msg.arg1;
4129 final int procState = msg.arg2;
4130 final long procStateSeq = (Long) msg.obj;
4131
4132 handleUidChanged(uid, procState, procStateSeq);
4133 return true;
4134 }
4135 case UID_MSG_GONE: {
4136 final int uid = msg.arg1;
4137 handleUidGone(uid);
4138 return true;
4139 }
4140 default: {
4141 return false;
4142 }
4143 }
4144 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004145
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004146 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004147
Makoto Onuki8e777332017-03-28 11:25:47 -07004148 void handleUidChanged(int uid, int procState, long procStateSeq) {
4149 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4150 try {
4151 synchronized (mUidRulesFirstLock) {
4152 // We received a uid state change callback, add it to the history so that it
4153 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004154 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004155 // Now update the network policy rules as per the updated uid state.
4156 updateUidStateUL(uid, procState);
4157 // Updating the network rules is done, so notify AMS about this.
4158 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4159 }
4160 } finally {
4161 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4162 }
4163 }
4164
4165 void handleUidGone(int uid) {
4166 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4167 try {
4168 synchronized (mUidRulesFirstLock) {
4169 removeUidStateUL(uid);
4170 }
4171 } finally {
4172 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4173 }
4174 }
4175
Felipe Leme57e3d312016-08-23 14:42:52 -07004176 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4177 final PackageManager pm = mContext.getPackageManager();
4178 final String[] packages = pm.getPackagesForUid(uid);
4179 if (packages != null) {
4180 final int userId = UserHandle.getUserId(uid);
4181 for (String packageName : packages) {
4182 final Intent intent =
4183 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4184 intent.setPackage(packageName);
4185 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4186 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4187 }
4188 }
4189 }
4190
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004191 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4192 // long quotaBytes split up into two ints to fit in message
4193 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4194 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4195 }
4196
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004197 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004198 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004199 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004200 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004201 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004202 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004203 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004204 }
4205 }
4206
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004207 private void removeInterfaceQuotaAsync(String iface) {
4208 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4209 }
4210
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004211 private void removeInterfaceQuota(String iface) {
4212 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004213 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004214 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004215 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004216 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004217 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004218 }
4219 }
4220
Felipe Leme70c57c22016-03-29 10:45:13 -07004221 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4222 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004223 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004224 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004225 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004226 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4227 } catch (RemoteException e) {
4228 // ignored; service lives in system_server
4229 }
4230 }
4231
4232 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4233 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4234 try {
4235 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4236 } catch (IllegalStateException e) {
4237 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004238 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004239 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004240 }
4241 }
4242
Felipe Lemebc853dd2016-09-08 13:26:55 -07004243 private static final int CHAIN_TOGGLE_NONE = 0;
4244 private static final int CHAIN_TOGGLE_ENABLE = 1;
4245 private static final int CHAIN_TOGGLE_DISABLE = 2;
4246 @Retention(RetentionPolicy.SOURCE)
4247 @IntDef(flag = false, value = {
4248 CHAIN_TOGGLE_NONE,
4249 CHAIN_TOGGLE_ENABLE,
4250 CHAIN_TOGGLE_DISABLE
4251 })
4252 public @interface ChainToggleType {
4253 }
4254
4255 /**
4256 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004257 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004258 *
4259 * @param chain firewall chain.
4260 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4261 * @param toggle whether the chain should be enabled, disabled, or not changed.
4262 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004263 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004264 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004265 if (uidRules != null) {
4266 setUidFirewallRulesUL(chain, uidRules);
4267 }
4268 if (toggle != CHAIN_TOGGLE_NONE) {
4269 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4270 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004271 }
4272
Amith Yamasani15e472352015-04-24 19:06:07 -07004273 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004274 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4275 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4276 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004277 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004278 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004279 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004280 int size = uidRules.size();
4281 int[] uids = new int[size];
4282 int[] rules = new int[size];
4283 for(int index = size - 1; index >= 0; --index) {
4284 uids[index] = uidRules.keyAt(index);
4285 rules[index] = uidRules.valueAt(index);
4286 }
4287 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004288 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004289 } catch (IllegalStateException e) {
4290 Log.wtf(TAG, "problem setting firewall uid rules", e);
4291 } catch (RemoteException e) {
4292 // ignored; service lives in system_server
4293 }
4294 }
4295
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004296 /**
4297 * Add or remove a uid to the firewall blacklist for all network ifaces.
4298 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004299 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004300 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4301 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4302 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004303 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004304 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004305 if (chain == FIREWALL_CHAIN_DOZABLE) {
4306 mUidFirewallDozableRules.put(uid, rule);
4307 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4308 mUidFirewallStandbyRules.put(uid, rule);
4309 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4310 mUidFirewallPowerSaveRules.put(uid, rule);
4311 }
4312
4313 try {
4314 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004315 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004316 } catch (IllegalStateException e) {
4317 Log.wtf(TAG, "problem setting firewall uid rules", e);
4318 } catch (RemoteException e) {
4319 // ignored; service lives in system_server
4320 }
4321 } finally {
4322 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004323 }
4324 }
4325
4326 /**
4327 * Add or remove a uid to the firewall blacklist for all network ifaces.
4328 */
Felipe Lemef0823852016-06-08 13:43:08 -07004329 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004330 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4331 mFirewallChainStates.get(chain) == enable) {
4332 // All is the same, nothing to do.
4333 return;
4334 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004335 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004336 try {
4337 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004338 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004339 } catch (IllegalStateException e) {
4340 Log.wtf(TAG, "problem enable firewall chain", e);
4341 } catch (RemoteException e) {
4342 // ignored; service lives in system_server
4343 }
4344 }
4345
Felipe Leme03e95e22016-09-09 09:25:31 -07004346 /**
4347 * Resets all firewall rules associated with an UID.
4348 */
4349 private void resetUidFirewallRules(int uid) {
4350 try {
4351 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4352 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4353 mNetworkManager
4354 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4355 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4356 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4357 } catch (IllegalStateException e) {
4358 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4359 } catch (RemoteException e) {
4360 // ignored; service lives in system_server
4361 }
4362 }
4363
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004364 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4365 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004366 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004367 } catch (RuntimeException e) {
4368 Slog.w(TAG, "problem reading network stats: " + e);
4369 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004370 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004371 // ignored; service lives in system_server
4372 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004373 }
4374 }
4375
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004376 private boolean isBandwidthControlEnabled() {
4377 final long token = Binder.clearCallingIdentity();
4378 try {
4379 return mNetworkManager.isBandwidthControlEnabled();
4380 } catch (RemoteException e) {
4381 // ignored; service lives in system_server
4382 return false;
4383 } finally {
4384 Binder.restoreCallingIdentity(token);
4385 }
4386 }
4387
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004388 /**
4389 * Try refreshing {@link #mTime} when stale.
4390 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004391 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004392 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004393 mTime.forceRefresh();
4394 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004395 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004396
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004397 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004398 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4399 }
4400
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004401 private static Intent buildAllowBackgroundDataIntent() {
4402 return new Intent(ACTION_ALLOW_BACKGROUND);
4403 }
4404
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004405 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4406 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
Jeff Sharkeybfb43ea2018-02-03 12:08:16 -07004407 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
4408 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4409 return intent;
4410 }
4411
4412 private static Intent buildSnoozeRapidIntent(NetworkTemplate template) {
4413 final Intent intent = new Intent(ACTION_SNOOZE_RAPID);
4414 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004415 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4416 return intent;
4417 }
4418
Wei Liu546cb772016-07-21 16:19:01 -07004419 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004420 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004421 intent.setComponent(ComponentName.unflattenFromString(
4422 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004423 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4424 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4425 return intent;
4426 }
4427
Wei Liu546cb772016-07-21 16:19:01 -07004428 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004429 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004430 intent.setComponent(ComponentName.unflattenFromString(
4431 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004432 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4433 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4434 return intent;
4435 }
4436
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004437 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004438 public void addIdleHandler(IdleHandler handler) {
4439 mHandler.getLooper().getQueue().addIdleHandler(handler);
4440 }
4441
jackqdyulei29c82ab2017-03-10 14:09:16 -08004442 @VisibleForTesting
4443 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4444 mRestrictBackgroundPowerState = result;
4445
4446 boolean restrictBackground = result.batterySaverEnabled;
4447 boolean shouldInvokeRestrictBackground;
4448 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4449 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4450
4451 if (result.globalBatterySaverEnabled) {
4452 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4453 // turn it on.
4454 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4455 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4456 localRestrictBgChangedInBsm = false;
4457 } else {
4458 // Try to restore the restrictBackground if it doesn't change in bsm
4459 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4460 restrictBackground = mRestrictBackgroundBeforeBsm;
4461 }
4462
4463 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004464 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004465 }
4466
4467 // Change it at last so setRestrictBackground() won't affect this variable
4468 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4469 }
4470
Jeff Sharkey1b861272011-05-22 00:34:52 -07004471 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4472 final int size = source.size();
4473 for (int i = 0; i < size; i++) {
4474 target.put(source.keyAt(i), true);
4475 }
4476 }
4477
Stuart Scottf1fb3972015-04-02 18:00:02 -07004478 @Override
4479 public void factoryReset(String subscriber) {
4480 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4481
Stuart Scotte3e314d2015-04-20 14:07:45 -07004482 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4483 return;
4484 }
4485
Stuart Scottf1fb3972015-04-02 18:00:02 -07004486 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004487 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004488 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4489 for (NetworkPolicy policy : policies) {
4490 if (policy.template.equals(template)) {
4491 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4492 policy.inferred = false;
4493 policy.clearSnooze();
4494 }
4495 }
4496 setNetworkPolicies(policies);
4497
4498 // Turn restrict background data off
4499 setRestrictBackground(false);
4500
Stuart Scotte3e314d2015-04-20 14:07:45 -07004501 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4502 // Remove app's "restrict background data" flag
4503 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4504 setUidPolicy(uid, POLICY_NONE);
4505 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004506 }
4507 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004508
Sudheer Shankab8f23162017-08-04 13:30:10 -07004509 @Override
4510 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4511 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4512 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4513 }
4514
4515 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4516 final int uidRules;
4517 final boolean isBackgroundRestricted;
4518 synchronized (mUidRulesFirstLock) {
4519 uidRules = mUidRules.get(uid, RULE_NONE);
4520 isBackgroundRestricted = mRestrictBackground;
4521 }
4522 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004523 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004524 return true;
4525 }
4526 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004527 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004528 return false;
4529 }
4530 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004531 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004532 return true;
4533 }
4534 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004535 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004536 return false;
4537 }
4538 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004539 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004540 return false;
4541 }
4542 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004543 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004544 return true;
4545 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004546 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004547 return false;
4548 }
4549
Felipe Lemed17fda42016-04-29 11:12:45 -07004550 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4551
4552 @Override
4553 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004554 synchronized (mUidRulesFirstLock) {
4555 boolean changed = removeUserStateUL(userId, false);
4556 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004557 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004558 synchronized (mNetworkPoliciesSecondLock) {
4559 writePolicyAL();
4560 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004561 }
4562 }
4563 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004564
4565 /**
4566 * @return true if the given uid is restricted from doing networking on metered networks.
4567 */
4568 @Override
4569 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4570 final int uidRules;
4571 final boolean isBackgroundRestricted;
4572 synchronized (mUidRulesFirstLock) {
4573 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4574 isBackgroundRestricted = mRestrictBackground;
4575 }
4576 return isBackgroundRestricted
4577 && !hasRule(uidRules, RULE_ALLOW_METERED)
4578 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4579 }
4580
4581 /**
4582 * @return true if networking is blocked on the given interface for the given uid according
4583 * to current networking policies.
4584 */
4585 @Override
4586 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004587 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004588 synchronized (mNetworkPoliciesSecondLock) {
4589 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004590 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004591 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004592 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004593
4594 @Override
4595 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4596 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004597 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004598 if (added) {
4599 mPowerSaveTempWhitelistAppIds.put(appId, true);
4600 } else {
4601 mPowerSaveTempWhitelistAppIds.delete(appId);
4602 }
4603 updateRulesForTempWhitelistChangeUL(appId);
4604 }
4605 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004606
4607 @Override
4608 public SubscriptionPlan getSubscriptionPlan(Network network) {
4609 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004610 final int subId = getSubIdLocked(network);
4611 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004612 }
4613 }
4614
4615 @Override
4616 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4617 synchronized (mNetworkPoliciesSecondLock) {
4618 // TODO: handle splitting quota between use-cases
4619 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network));
4620 }
4621 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004622
4623 @Override
4624 public void onAdminDataAvailable() {
4625 mAdminDataAvailableLatch.countDown();
4626 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004627
4628 @Override
4629 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4630 setMeteredRestrictedPackagesInternal(packageNames, userId);
4631 }
4632
4633 @Override
4634 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4635 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4636 userId, 0, packageNames).sendToTarget();
4637 }
4638 }
4639
4640 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4641 synchronized (mUidRulesFirstLock) {
4642 final Set<Integer> newRestrictedUids = new ArraySet<>();
4643 for (String packageName : packageNames) {
4644 final int uid = getUidForPackage(packageName, userId);
4645 if (uid >= 0) {
4646 newRestrictedUids.add(uid);
4647 }
4648 }
4649 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4650 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4651 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4652 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4653 }
4654 }
4655
4656 private int getUidForPackage(String packageName, int userId) {
4657 try {
4658 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4659 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4660 } catch (NameNotFoundException e) {
4661 return -1;
4662 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004663 }
4664
4665 private int parseSubId(NetworkState state) {
4666 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4667 int subId = INVALID_SUBSCRIPTION_ID;
4668 if (state != null && state.networkCapabilities != null
4669 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4670 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4671 if (spec instanceof StringNetworkSpecifier) {
4672 try {
4673 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4674 } catch (NumberFormatException e) {
4675 }
4676 }
4677 }
4678 return subId;
4679 }
4680
4681 private int getSubIdLocked(Network network) {
4682 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004683 }
4684
Jeff Sharkey2e471452018-01-19 18:02:47 +09004685 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4686 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4687 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4688 }
4689
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004690 /**
4691 * This will only ever be called once - during device boot.
4692 */
4693 private void waitForAdminData() {
4694 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4695 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4696 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4697 }
4698 }
4699
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004700 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4701 Set<Integer> newRestrictedUids) {
4702 if (oldRestrictedUids == null) {
4703 for (int uid : newRestrictedUids) {
4704 updateRulesForDataUsageRestrictionsUL(uid);
4705 }
4706 return;
4707 }
4708 for (int uid : oldRestrictedUids) {
4709 if (!newRestrictedUids.contains(uid)) {
4710 updateRulesForDataUsageRestrictionsUL(uid);
4711 }
4712 }
4713 for (int uid : newRestrictedUids) {
4714 if (!oldRestrictedUids.contains(uid)) {
4715 updateRulesForDataUsageRestrictionsUL(uid);
4716 }
4717 }
4718 }
4719
4720 private boolean isRestrictedByAdminUL(int uid) {
4721 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4722 UserHandle.getUserId(uid));
4723 return restrictedUids != null && restrictedUids.contains(uid);
4724 }
4725
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004726 private static boolean hasRule(int uidRules, int rule) {
4727 return (uidRules & rule) != 0;
4728 }
4729
Jeff Sharkey2e471452018-01-19 18:02:47 +09004730 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4731 return (val != null) ? val : new NetworkState[0];
4732 }
4733
Chris Wren193ae6b2017-03-31 15:17:11 -04004734 private class NotificationId {
4735 private final String mTag;
4736 private final int mId;
4737
4738 NotificationId(NetworkPolicy policy, int type) {
4739 mTag = buildNotificationTag(policy, type);
4740 mId = type;
4741 }
4742
4743 @Override
4744 public boolean equals(Object o) {
4745 if (this == o) return true;
4746 if (!(o instanceof NotificationId)) return false;
4747 NotificationId that = (NotificationId) o;
4748 return Objects.equals(mTag, that.mTag);
4749 }
4750
4751 @Override
4752 public int hashCode() {
4753 return Objects.hash(mTag);
4754 }
4755
4756 /**
4757 * Build unique tag that identifies an active {@link NetworkPolicy}
4758 * notification of a specific type, like {@link #TYPE_LIMIT}.
4759 */
4760 private String buildNotificationTag(NetworkPolicy policy, int type) {
4761 return TAG + ":" + policy.template.hashCode() + ":" + type;
4762 }
4763
4764 public String getTag() {
4765 return mTag;
4766 }
4767
4768 public int getId() {
4769 return mId;
4770 }
4771 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004772}