blob: 0e54768bfa87e1968fedcd16301c3a1d6c45a333 [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;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700109import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700110import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700111import android.app.Notification;
112import 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 Sharkey497e4432011-06-14 17:27:29 -0700178import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700179import android.util.ArrayMap;
180import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700181import android.util.AtomicFile;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900182import android.util.DataUnit;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700183import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700184import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700185import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600186import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700187import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600188import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700189import android.util.SparseBooleanArray;
190import android.util.SparseIntArray;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900191import android.util.SparseLongArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700192import android.util.TrustedTime;
193import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700194
Jeff Sharkey497e4432011-06-14 17:27:29 -0700195import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700196import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800197import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400198import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500199import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700200import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800201import com.android.internal.util.ArrayUtils;
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800202import com.android.internal.util.ConcurrentUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600203import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700205import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600206import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700207import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700208import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700209import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800210import com.android.server.SystemConfig;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900211import com.android.server.SystemService;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600212
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600213import libcore.io.IoUtils;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900214import libcore.util.EmptyArray;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600215
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700216import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217import org.xmlpull.v1.XmlSerializer;
218
219import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700220import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700221import java.io.FileInputStream;
222import java.io.FileNotFoundException;
223import java.io.FileOutputStream;
224import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700225import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700226import java.lang.annotation.Retention;
227import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100228import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600229import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600230import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700231import java.util.ArrayList;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700232import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600233import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400234import java.util.Objects;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800235import java.util.Set;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800236import java.util.concurrent.CountDownLatch;
237import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700239/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700240 * Service that maintains low-level network policy rules, using
241 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700242 * <p>
243 * Derives active rules by combining a given policy with other system status,
244 * and delivers to listeners, such as {@link ConnectivityManager}, for
245 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700246 *
247 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000248 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700249 * <ul>
250 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
251 * rules).
252 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
253 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000254 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
255 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700256 * </ul>
257 *
258 * <p>
259 * As such, methods that require synchronization have the following prefixes:
260 * <ul>
261 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
262 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000263 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
264 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700265 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700266 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700267public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Sudheer Shanka352dc572017-09-22 17:09:38 -0700268 static final String TAG = NetworkPolicyLogger.TAG;
269 private static final boolean LOGD = NetworkPolicyLogger.LOGD;
270 private static final boolean LOGV = NetworkPolicyLogger.LOGV;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700271
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700272 private static final int VERSION_INIT = 1;
273 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700274 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800275 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800276 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800277 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700278 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700279 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700280 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700281 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600282 private static final int VERSION_ADDED_CYCLE = 11;
283 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700284
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800285 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400286 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800287 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400288 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800289 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400290 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey2e471452018-01-19 18:02:47 +0900291 @VisibleForTesting
292 public static final int TYPE_RAPID = SystemMessage.NOTE_NET_RAPID;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700293
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294 private static final String TAG_POLICY_LIST = "policy-list";
295 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600296 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700297 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700298 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800299 private static final String TAG_WHITELIST = "whitelist";
300 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800301 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302
303 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700304 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
306 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700307 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600308 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
309 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
310 private static final String ATTR_CYCLE_START = "cycleStart";
311 private static final String ATTR_CYCLE_END = "cycleEnd";
312 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700313 private static final String ATTR_WARNING_BYTES = "warningBytes";
314 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700315 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800316 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
317 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800318 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700319 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700321 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600323 private static final String ATTR_SUB_ID = "subId";
324 private static final String ATTR_TITLE = "title";
325 private static final String ATTR_SUMMARY = "summary";
326 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
327 private static final String ATTR_USAGE_BYTES = "usageBytes";
328 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600329 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800331 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800332 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800333 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800334 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700335
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700336 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
337
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800338 /**
339 * Indicates the maximum wait time for admin data to be available;
340 */
341 private static final long WAIT_FOR_ADMIN_DATA_TIMEOUT_MS = 10_000;
342
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700343 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700344 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800345 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800346 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700347 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700348 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
349 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700350 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700351 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey9252b342018-01-19 07:58:35 +0900352 private static final int MSG_SUBSCRIPTION_OVERRIDE = 16;
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800353 private static final int MSG_METERED_RESTRICTED_PACKAGES_CHANGED = 17;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700354
Makoto Onuki8e777332017-03-28 11:25:47 -0700355 private static final int UID_MSG_STATE_CHANGED = 100;
356 private static final int UID_MSG_GONE = 101;
357
Jeff Sharkey75279902011-05-24 18:39:45 -0700358 private final Context mContext;
359 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700360 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700361 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700362 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700363 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700364 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700365 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700366
367 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700368 private INotificationManager mNotifManager;
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
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700554 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
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
Jeff Sharkey497e4432011-06-14 17:27:29 -0700567 public void bindNotificationManager(INotificationManager notifManager) {
568 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
569 }
570
Felipe Lemef0823852016-06-08 13:43:08 -0700571 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700572 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700573 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
574 mPowerSaveWhitelistExceptIdleAppIds.clear();
575 if (whitelist != null) {
576 for (int uid : whitelist) {
577 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
578 }
579 }
580 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700581 mPowerSaveWhitelistAppIds.clear();
582 if (whitelist != null) {
583 for (int uid : whitelist) {
584 mPowerSaveWhitelistAppIds.put(uid, true);
585 }
586 }
587 } catch (RemoteException e) {
588 }
589 }
590
Felipe Lemea9505cc2016-02-26 10:28:41 -0800591 /**
592 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
593 * revoke the whitelist.
594 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700595 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800596 */
Felipe Lemef0823852016-06-08 13:43:08 -0700597 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800598 final List<UserInfo> users = mUserManager.getUsers();
599 final int numberUsers = users.size();
600
Felipe Lemea110eec2016-04-29 09:58:06 -0700601 boolean changed = false;
602 for (int i = 0; i < numberUsers; i++) {
603 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700604 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700605 }
606 return changed;
607 }
608
Felipe Lemef0823852016-06-08 13:43:08 -0700609 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700610 final SystemConfig sysConfig = SystemConfig.getInstance();
611 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800612 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
613 boolean changed = false;
614 for (int i = 0; i < allowDataUsage.size(); i++) {
615 final String pkg = allowDataUsage.valueAt(i);
616 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700617 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
618 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 final ApplicationInfo app;
620 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700621 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800622 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700623 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
624 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800625 continue;
626 }
627 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700628 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
629 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800630 continue;
631 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700632 final int uid = UserHandle.getUid(userId, app.uid);
633 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
634 if (LOGD)
635 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
636 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800637 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700638 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700639 if (LOGD)
640 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
641 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700642 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700643 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800644 }
645 }
646 return changed;
647 }
648
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800649 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700650 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800651 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700652 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800653 // Boost thread's priority during system server init
654 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700655 if (!isBandwidthControlEnabled()) {
656 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
657 return;
658 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700659
Felipe Leme873a83a2016-09-07 11:34:10 -0700660 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700661
Felipe Leme873a83a2016-09-07 11:34:10 -0700662 synchronized (mUidRulesFirstLock) {
663 synchronized (mNetworkPoliciesSecondLock) {
664 updatePowerSaveWhitelistUL();
665 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
666 mPowerManagerInternal.registerLowPowerModeObserver(
667 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800668 @Override
669 public int getServiceType() {
670 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700671 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800672
673 @Override
674 public void onLowPowerModeChanged(PowerSaveState result) {
675 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800676 if (LOGD) {
677 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
678 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800679 synchronized (mUidRulesFirstLock) {
680 if (mRestrictPower != enabled) {
681 mRestrictPower = enabled;
682 updateRulesForRestrictPowerUL();
683 }
684 }
685 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800686 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800687 mRestrictPower = mPowerManagerInternal.getLowPowerState(
688 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700689
690 mSystemReady = true;
691
Sudheer Shankac53c47f2018-01-16 12:01:00 -0800692 waitForAdminData();
693
Felipe Leme873a83a2016-09-07 11:34:10 -0700694 // read policy from disk
695 readPolicyAL();
696
jackqdyulei29c82ab2017-03-10 14:09:16 -0800697 // Update the restrictBackground if battery saver is turned on
Sudheer Shanka543339f2017-07-28 15:18:07 -0700698 mRestrictBackgroundBeforeBsm = mLoadedRestrictBackground;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800699 mRestrictBackgroundPowerState = mPowerManagerInternal
700 .getLowPowerState(ServiceType.DATA_SAVER);
701 final boolean localRestrictBackground =
702 mRestrictBackgroundPowerState.batterySaverEnabled;
Sudheer Shanka543339f2017-07-28 15:18:07 -0700703 if (localRestrictBackground && !mLoadedRestrictBackground) {
704 mLoadedRestrictBackground = true;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800705 }
706 mPowerManagerInternal.registerLowPowerModeObserver(
707 new PowerManagerInternal.LowPowerModeListener() {
708 @Override
709 public int getServiceType() {
710 return ServiceType.DATA_SAVER;
711 }
712
713 @Override
714 public void onLowPowerModeChanged(PowerSaveState result) {
715 synchronized (mUidRulesFirstLock) {
716 updateRestrictBackgroundByLowPowerModeUL(result);
717 }
718 }
719 });
720
Felipe Leme873a83a2016-09-07 11:34:10 -0700721 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
722 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700723 }
Felipe Lemef0823852016-06-08 13:43:08 -0700724
Sudheer Shanka543339f2017-07-28 15:18:07 -0700725 setRestrictBackgroundUL(mLoadedRestrictBackground);
Felipe Leme873a83a2016-09-07 11:34:10 -0700726 updateRulesForGlobalChangeAL(false);
727 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700728 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800729 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700730
Sudheer Shankae7361852017-03-07 11:51:46 -0800731 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700732 try {
733 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000734 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800735 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700736 mNetworkManager.registerObserver(mAlertObserver);
737 } catch (RemoteException e) {
738 // ignored; both services live in system_server
739 }
740
741 // listen for changes to power save whitelist
742 final IntentFilter whitelistFilter = new IntentFilter(
743 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
744 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
745
Felipe Leme873a83a2016-09-07 11:34:10 -0700746 // watch for network interfaces to be claimed
747 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
748 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
749
750 // listen for package changes to update policy
751 final IntentFilter packageFilter = new IntentFilter();
752 packageFilter.addAction(ACTION_PACKAGE_ADDED);
753 packageFilter.addDataScheme("package");
754 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
755
756 // listen for UID changes to update policy
757 mContext.registerReceiver(
758 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
759
760 // listen for user changes to update policy
761 final IntentFilter userFilter = new IntentFilter();
762 userFilter.addAction(ACTION_USER_ADDED);
763 userFilter.addAction(ACTION_USER_REMOVED);
764 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
765
766 // listen for stats update events
767 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
768 mContext.registerReceiver(
769 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
770
771 // listen for restrict background changes from notifications
772 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
773 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
774
775 // listen for snooze warning from notifications
776 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
777 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
778 MANAGE_NETWORK_POLICY, mHandler);
779
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600780 // listen for configured wifi networks to be loaded
781 final IntentFilter wifiFilter =
782 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
783 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700784
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700785 // listen for carrier config changes to update data cycle information
786 final IntentFilter carrierConfigFilter = new IntentFilter(
787 ACTION_CARRIER_CONFIG_CHANGED);
788 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
789
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600790 // listen for meteredness changes
791 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
792 new NetworkRequest.Builder().build(), mNetworkCallback);
793
Felipe Leme873a83a2016-09-07 11:34:10 -0700794 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800795 // tell systemReady() that the service has been initialized
796 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700797 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800798 // Restore the default priority after init is done
799 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700800 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700801 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700802 }
803
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800804 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
805 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
806 mHandler.post(() -> initService(initCompleteSignal));
807 return initCompleteSignal;
808 }
809
810 public void systemReady(CountDownLatch initCompleteSignal) {
811 // wait for initService to complete
812 try {
813 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
814 throw new IllegalStateException("Service " + TAG +" init timeout");
815 }
816 } catch (InterruptedException e) {
817 Thread.currentThread().interrupt();
818 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
819 }
820 }
821
Sudheer Shankac9d94072017-02-22 22:13:55 +0000822 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700823 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700824 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
825 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700826 }
827
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700828 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700829 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700830 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700831
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700832 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700833 }
834
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700835 @Override public void onUidIdle(int uid, boolean disabled) {
836 }
837
838 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700839 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700840 };
841
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700842 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700843 @Override
844 public void onReceive(Context context, Intent intent) {
845 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700846 synchronized (mUidRulesFirstLock) {
847 updatePowerSaveWhitelistUL();
848 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700849 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700850 }
851 }
852 };
853
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700854 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700855 @Override
856 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700857 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700858
859 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700860 final int uid = intent.getIntExtra(EXTRA_UID, -1);
861 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700862
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700863 if (ACTION_PACKAGE_ADDED.equals(action)) {
864 // update rules for UID, since it might be subject to
865 // global background data policy
866 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700867 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700868 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700869 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700870 }
871 }
872 };
873
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700874 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700875 @Override
876 public void onReceive(Context context, Intent intent) {
877 // on background handler thread, and UID_REMOVED is protected
878
879 final int uid = intent.getIntExtra(EXTRA_UID, -1);
880 if (uid == -1) return;
881
882 // remove any policy and update rules to clean up
883 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700884 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700885 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700886 synchronized (mNetworkPoliciesSecondLock) {
887 writePolicyAL();
888 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700889 }
890 }
891 };
892
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700893 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700894 @Override
895 public void onReceive(Context context, Intent intent) {
896 // on background handler thread, and USER_ADDED and USER_REMOVED
897 // broadcasts are protected
898
899 final String action = intent.getAction();
900 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
901 if (userId == -1) return;
902
Amith Yamasani15e472352015-04-24 19:06:07 -0700903 switch (action) {
904 case ACTION_USER_REMOVED:
905 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700906 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800907 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700908 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700909 removeUserStateUL(userId, true);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -0800910 // Removing outside removeUserStateUL since that can also be called when
911 // user resets app preferences.
912 mMeteredRestrictedUids.remove(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700913 if (action == ACTION_USER_ADDED) {
914 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700915 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700916 }
917 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700918 synchronized (mNetworkPoliciesSecondLock) {
919 updateRulesForGlobalChangeAL(true);
920 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700921 }
922 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700923 }
924 }
925 };
926
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700927 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928 * Receiver that watches for {@link INetworkStatsService} updates, which we
929 * use to check against {@link NetworkPolicy#warningBytes}.
930 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700931 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700932 @Override
933 public void onReceive(Context context, Intent intent) {
934 // on background handler thread, and verified
935 // READ_NETWORK_USAGE_HISTORY permission above.
936
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800937 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700938 synchronized (mNetworkPoliciesSecondLock) {
939 updateNetworkEnabledNL();
940 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700941 }
942 }
943 };
944
945 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700946 * Receiver that watches for {@link Notification} control of
947 * {@link #mRestrictBackground}.
948 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700950 @Override
951 public void onReceive(Context context, Intent intent) {
952 // on background handler thread, and verified MANAGE_NETWORK_POLICY
953 // permission above.
954
955 setRestrictBackground(false);
956 }
957 };
958
959 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800960 * Receiver that watches for {@link Notification} control of
961 * {@link NetworkPolicy#lastWarningSnooze}.
962 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700963 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800964 @Override
965 public void onReceive(Context context, Intent intent) {
966 // on background handler thread, and verified MANAGE_NETWORK_POLICY
967 // permission above.
968
969 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
970 performSnooze(template, TYPE_WARNING);
971 }
972 };
973
974 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600975 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600976 * we can perform upgrade logic. After initial upgrade logic, it updates
977 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700978 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600979 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700980 @Override
981 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900982 synchronized (mUidRulesFirstLock) {
983 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600984 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600985 }
986 }
987 // Only need to perform upgrade logic once
988 mContext.unregisterReceiver(this);
989 }
990 };
991
992 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
993 @Override
994 public void onCapabilitiesChanged(Network network,
995 NetworkCapabilities networkCapabilities) {
996 if (network == null || networkCapabilities == null) return;
997
998 synchronized (mNetworkPoliciesSecondLock) {
999 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1000 final boolean newMetered = !networkCapabilities
1001 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1002
1003 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07001004 mLogger.meterednessChanged(network.netId, newMetered);
Jeff Sharkeyb43a2922017-09-13 17:30:45 -06001005 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001006 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001007 }
1008 }
1009 }
1010 };
1011
1012 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 * Observer that watches for {@link INetworkManagementService} alerts.
1014 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001015 final private INetworkManagementEventObserver mAlertObserver
1016 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001017 @Override
1018 public void limitReached(String limitName, String iface) {
1019 // only someone like NMS should be calling us
1020 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1021
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001022 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1023 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001024 }
1025 }
1026 };
1027
Jeff Sharkey2e471452018-01-19 18:02:47 +09001028 @VisibleForTesting
1029 public void updateNotifications() {
1030 synchronized (mNetworkPoliciesSecondLock) {
1031 updateNotificationsNL();
1032 }
1033 }
1034
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001035 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1037 * to show visible notifications as needed.
1038 */
Felipe Lemef0823852016-06-08 13:43:08 -07001039 void updateNotificationsNL() {
1040 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001041
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001042 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001043 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001044 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045
1046 // TODO: when switching to kernel notifications, compute next future
1047 // cycle boundary to recompute notifications.
1048
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001049 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001050 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1051 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 // ignore policies that aren't relevant to user
1053 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001054 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055
Jeff Sharkey53313d72017-07-13 16:47:32 -06001056 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1057 .cycleIterator(policy).next();
1058 final long start = cycle.first.toInstant().toEpochMilli();
1059 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001061
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001062 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001063 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1065 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001067 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 }
1069
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001071 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001073 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 }
1076 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001077 }
1078
Jeff Sharkey2e471452018-01-19 18:02:47 +09001079 // Alert the user about heavy recent data usage that might result in
1080 // going over their carrier limit.
1081 for (int i = 0; i < mNetIdToSubId.size(); i++) {
1082 final int subId = mNetIdToSubId.valueAt(i);
1083 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
1084 if (plan == null) continue;
1085
1086 final long limitBytes = plan.getDataLimitBytes();
1087 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1088 // Ignore missing limits
1089 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1090 // Unlimited data; no rapid usage alerting
1091 } else {
1092 // Warn if average usage over last 4 days is on track to blow
1093 // pretty far past the plan limits.
1094 final long recentDuration = TimeUnit.DAYS.toMillis(4);
1095 final long end = RecurrenceRule.sClock.millis();
1096 final long start = end - recentDuration;
1097
1098 final NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(
1099 mContext.getSystemService(TelephonyManager.class).getSubscriberId(subId));
1100 final long recentBytes = getTotalBytes(template, start, end);
1101
1102 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
1103 final long cycleDuration = cycle.second.toInstant().toEpochMilli()
1104 - cycle.first.toInstant().toEpochMilli();
1105
1106 final long projectedBytes = (recentBytes * cycleDuration) / recentDuration;
1107 final long alertBytes = (limitBytes * 3) / 2;
1108 if (projectedBytes > alertBytes) {
1109 final NetworkPolicy policy = new NetworkPolicy(template, plan.getCycleRule(),
1110 NetworkPolicy.WARNING_DISABLED, NetworkPolicy.LIMIT_DISABLED,
1111 NetworkPolicy.SNOOZE_NEVER, NetworkPolicy.SNOOZE_NEVER, true, true);
1112 enqueueNotification(policy, TYPE_RAPID, 0);
1113 }
1114 }
1115 }
1116
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001117 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001118 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001119 final NotificationId notificationId = beforeNotifs.valueAt(i);
1120 if (!mActiveNotifs.contains(notificationId)) {
1121 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 }
1123 }
1124 }
1125
1126 /**
1127 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001128 * current device state, such as when
1129 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1130 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001131 */
1132 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001133 if (template.isMatchRuleMobile()) {
1134 final TelephonyManager tele = TelephonyManager.from(mContext);
1135 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001136
Jeff Sharkey32566012014-12-02 18:30:14 -08001137 // Mobile template is relevant when any active subscriber matches
Jeff Sharkey2e471452018-01-19 18:02:47 +09001138 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001139 for (int subId : subIds) {
1140 final String subscriberId = tele.getSubscriberId(subId);
1141 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001142 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1143 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001144 if (template.matches(probeIdent)) {
1145 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001146 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001147 }
1148 return false;
1149 } else {
1150 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152 }
1153
1154 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001155 * Notify that given {@link NetworkTemplate} is over
1156 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1157 */
Felipe Lemef0823852016-06-08 13:43:08 -07001158 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001159 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001160 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001161 mOverLimitNotified.add(template);
1162 }
1163 }
1164
Felipe Lemef0823852016-06-08 13:43:08 -07001165 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001166 mOverLimitNotified.remove(template);
1167 }
1168
1169 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001170 * Show notification for combined {@link NetworkPolicy} and specific type,
1171 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1172 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001173 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001174 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001175 final Notification.Builder builder =
1176 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001177 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001178 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001179 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001180 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001181
1182 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001183 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 switch (type) {
1185 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001186 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001187 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001189 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001190 builder.setTicker(title);
1191 builder.setContentTitle(title);
1192 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001193 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001194 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001195
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001196 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1197 builder.setDeleteIntent(PendingIntent.getBroadcast(
1198 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1199
Wei Liu546cb772016-07-21 16:19:01 -07001200 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001201 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001202 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1203
Jeff Sharkey497e4432011-06-14 17:27:29 -07001204 break;
1205 }
1206 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001207 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001208
1209 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001210 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001211 switch (policy.template.getMatchRule()) {
1212 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001213 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001214 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001215 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001216 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001217 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001219 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001220 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001221 case MATCH_WIFI:
1222 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001223 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001224 break;
1225 default:
1226 title = null;
1227 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001228 }
1229
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001230 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001231 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001232 builder.setTicker(title);
1233 builder.setContentTitle(title);
1234 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001235
Wei Liu546cb772016-07-21 16:19:01 -07001236 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001237 builder.setContentIntent(PendingIntent.getActivity(
1238 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1239 break;
1240 }
1241 case TYPE_LIMIT_SNOOZED: {
1242 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001243 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001244 Formatter.formatFileSize(mContext, overBytes));
1245
1246 final CharSequence title;
1247 switch (policy.template.getMatchRule()) {
1248 case MATCH_MOBILE_3G_LOWER:
1249 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1250 break;
1251 case MATCH_MOBILE_4G:
1252 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1253 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001254 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001255 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1256 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001257 case MATCH_WIFI:
1258 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1259 break;
1260 default:
1261 title = null;
1262 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001263 }
1264
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001265 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001266 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001267 builder.setTicker(title);
1268 builder.setContentTitle(title);
1269 builder.setContentText(body);
1270
Wei Liu546cb772016-07-21 16:19:01 -07001271 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001272 builder.setContentIntent(PendingIntent.getActivity(
1273 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001274 break;
1275 }
Jeff Sharkey2e471452018-01-19 18:02:47 +09001276 case TYPE_RAPID: {
1277 final CharSequence title = res.getText(R.string.data_usage_rapid_title);
1278 body = res.getText(R.string.data_usage_rapid_body);
1279
1280 builder.setOngoing(true);
1281 builder.setSmallIcon(R.drawable.stat_notify_error);
1282 builder.setTicker(title);
1283 builder.setContentTitle(title);
1284 builder.setContentText(body);
1285
1286 final Intent intent = buildViewDataUsageIntent(res, policy.template);
1287 builder.setContentIntent(PendingIntent.getActivity(
1288 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1289 break;
1290 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001291 }
1292
1293 // TODO: move to NotificationManager once we can mock it
1294 try {
1295 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001296 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001297 builder.setStyle(new Notification.BigTextStyle()
1298 .bigText(body));
1299 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001300 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001301 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001302 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001303 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001304 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001305 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001306 }
1307 }
1308
Chris Wren193ae6b2017-03-31 15:17:11 -04001309 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001310 // TODO: move to NotificationManager once we can mock it
1311 try {
1312 final String packageName = mContext.getPackageName();
1313 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001314 packageName, notificationId.getTag(), notificationId.getId(),
1315 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001316 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001317 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001318 }
1319 }
1320
1321 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001323 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001325 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326 @Override
1327 public void onReceive(Context context, Intent intent) {
1328 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1329 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001330
1331 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001332 synchronized (mUidRulesFirstLock) {
1333 synchronized (mNetworkPoliciesSecondLock) {
1334 ensureActiveMobilePolicyAL();
1335 normalizePoliciesNL();
1336 updateNetworkEnabledNL();
1337 updateNetworkRulesNL();
1338 updateNotificationsNL();
1339 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340 }
1341 }
1342 };
1343
Jeff Sharkey2e471452018-01-19 18:02:47 +09001344 @VisibleForTesting
1345 public void updateNetworks() {
1346 mConnReceiver.onReceive(null, null);
1347 }
1348
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001349 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001350 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1351 * if necessary.
1352 *
1353 * @param subId that has its associated NetworkPolicy updated if necessary
1354 * @return if any policies were updated
1355 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001356 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1357 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001358
1359 boolean policyUpdated = false;
1360 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1361
1362 // find and update the mobile NetworkPolicy for this subscriber id
1363 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001364 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001365 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1366 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1367 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001368 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1369 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001370 }
1371 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001372 return policyUpdated;
1373 }
1374
1375 /**
1376 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1377 *
1378 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1379 * to do so, it returns the fallback value.
1380 *
1381 * @param config The CarrierConfig to read the value from.
1382 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1383 * @return cycleDay to use in the mobile NetworkPolicy.
1384 */
1385 @VisibleForTesting
1386 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1387 int fallbackCycleDay) {
1388 if (config == null) {
1389 return fallbackCycleDay;
1390 }
1391 int cycleDay =
1392 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1393 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1394 return fallbackCycleDay;
1395 }
1396 // validate cycleDay value
1397 final Calendar cal = Calendar.getInstance();
1398 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1399 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1400 Slog.e(TAG, "Invalid date in "
1401 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1402 return fallbackCycleDay;
1403 }
1404 return cycleDay;
1405 }
1406
1407 /**
1408 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1409 *
1410 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1411 * to do so, it returns the fallback value.
1412 *
1413 * @param config The CarrierConfig to read the value from.
1414 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1415 * @return warningBytes to use in the mobile NetworkPolicy.
1416 */
1417 @VisibleForTesting
1418 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1419 long fallbackWarningBytes) {
1420 if (config == null) {
1421 return fallbackWarningBytes;
1422 }
1423 long warningBytes =
1424 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1425
1426 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1427 return WARNING_DISABLED;
1428 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1429 return getPlatformDefaultWarningBytes();
1430 } else if (warningBytes < 0) {
1431 Slog.e(TAG, "Invalid value in "
1432 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1433 + "non-negative value but got: " + warningBytes);
1434 return fallbackWarningBytes;
1435 }
1436
1437 return warningBytes;
1438 }
1439
1440 /**
1441 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1442 *
1443 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1444 * to do so, it returns the fallback value.
1445 *
1446 * @param config The CarrierConfig to read the value from.
1447 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1448 * @return limitBytes to use in the mobile NetworkPolicy.
1449 */
1450 @VisibleForTesting
1451 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1452 long fallbackLimitBytes) {
1453 if (config == null) {
1454 return fallbackLimitBytes;
1455 }
1456 long limitBytes =
1457 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1458
1459 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1460 return LIMIT_DISABLED;
1461 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1462 return getPlatformDefaultLimitBytes();
1463 } else if (limitBytes < 0) {
1464 Slog.e(TAG, "Invalid value in "
1465 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1466 + "non-negative value but got: " + limitBytes);
1467 return fallbackLimitBytes;
1468 }
1469 return limitBytes;
1470 }
1471
1472 /**
1473 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1474 */
1475 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1476 @Override
1477 public void onReceive(Context context, Intent intent) {
1478 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1479 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1480
1481 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1482 return;
1483 }
1484 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1485 final TelephonyManager tele = TelephonyManager.from(mContext);
1486 final String subscriberId = tele.getSubscriberId(subId);
1487
1488 maybeRefreshTrustedTime();
1489 synchronized (mUidRulesFirstLock) {
1490 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001491 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001492 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001493 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001494 if (!updated) return;
1495 // update network and notification rules, as the data cycle changed and it's
1496 // possible that we should be triggering warnings/limits now
1497 handleNetworkPoliciesUpdateAL(true);
1498 }
1499 }
1500 }
1501 };
1502
1503 /**
1504 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1505 * one has been updated.
1506 *
1507 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1508 * update.
1509 */
1510 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1511 if (shouldNormalizePolicies) {
1512 normalizePoliciesNL();
1513 }
1514 updateNetworkEnabledNL();
1515 updateNetworkRulesNL();
1516 updateNotificationsNL();
1517 writePolicyAL();
1518 }
1519
1520 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001521 * Proactively control network data connections when they exceed
1522 * {@link NetworkPolicy#limitBytes}.
1523 */
Felipe Lemef0823852016-06-08 13:43:08 -07001524 void updateNetworkEnabledNL() {
1525 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001526
1527 // TODO: reset any policy-disabled networks when any policy is removed
1528 // completely, which is currently rare case.
1529
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001530 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1531 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001532 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001533 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001534 setNetworkTemplateEnabled(policy.template, true);
1535 continue;
1536 }
1537
Jeff Sharkey53313d72017-07-13 16:47:32 -06001538 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1539 .cycleIterator(policy).next();
1540 final long start = cycle.first.toInstant().toEpochMilli();
1541 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001542 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001543
1544 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001545 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1546 && policy.lastLimitSnooze < start;
1547 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001548
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001549 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001550 }
1551 }
1552
1553 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001554 * Proactively disable networks that match the given
1555 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001556 */
1557 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001558 // TODO: reach into ConnectivityManager to proactively disable bringing
1559 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001560
1561 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1562 // If mobile data usage hits the limit or if the user resumes the data, we need to
1563 // notify telephony.
1564 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1565 final TelephonyManager tm = TelephonyManager.from(mContext);
1566
Jeff Sharkey2e471452018-01-19 18:02:47 +09001567 final int[] subIds = ArrayUtils.defeatNullable(sm.getActiveSubscriptionIdList());
Jack Yu8781b682016-07-08 14:28:51 -07001568 for (int subId : subIds) {
1569 final String subscriberId = tm.getSubscriberId(subId);
1570 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001571 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1572 true);
Jack Yu8781b682016-07-08 14:28:51 -07001573 // Template is matched when subscriber id matches.
1574 if (template.matches(probeIdent)) {
1575 tm.setPolicyDataEnabled(enabled, subId);
1576 }
1577 }
1578 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001579 }
1580
1581 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001582 * Collect all ifaces from a {@link NetworkState} into the given set.
1583 */
1584 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1585 final String baseIface = state.linkProperties.getInterfaceName();
1586 if (baseIface != null) {
1587 ifaces.add(baseIface);
1588 }
1589 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1590 final String stackedIface = stackedLink.getInterfaceName();
1591 if (stackedIface != null) {
1592 ifaces.add(stackedIface);
1593 }
1594 }
1595 }
1596
1597 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001598 * Examine all connected {@link NetworkState}, looking for
1599 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1600 * remaining quota based on usage cycle and historical stats.
1601 */
Felipe Lemef0823852016-06-08 13:43:08 -07001602 void updateNetworkRulesNL() {
1603 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001604
1605 final NetworkState[] states;
1606 try {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001607 states = defeatNullable(mConnManager.getAllNetworkState());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001609 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 return;
1611 }
1612
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001613 // First, generate identities of all connected networks so we can
1614 // quickly compare them against all defined policies below.
Jeff Sharkey9252b342018-01-19 07:58:35 +09001615 mNetIdToSubId.clear();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001616 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001618 if (state.network != null) {
1619 mNetIdToSubId.put(state.network.netId, parseSubId(state));
1620 }
Wei Liub8eaf452016-01-25 10:32:27 -08001621 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001622 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1623 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001624 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 }
1626 }
1627
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001628 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001629 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001630
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001631 // For every well-defined policy, compute remaining data based on
1632 // current cycle and historical stats, and push to kernel.
1633 final ArraySet<String> matchingIfaces = new ArraySet<>();
1634 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1635 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1636
1637 // Collect all ifaces that match this policy
1638 matchingIfaces.clear();
1639 for (int j = identified.size() - 1; j >= 0; j--) {
1640 if (policy.template.matches(identified.valueAt(j))) {
1641 collectIfaces(matchingIfaces, identified.keyAt(j));
1642 }
1643 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001646 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647 }
1648
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001649 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001650 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001651 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001652 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001653 if (hasLimit && policy.hasCycle()) {
1654 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1655 .cycleIterator(policy).next();
1656 final long start = cycle.first.toInstant().toEpochMilli();
1657 final long end = cycle.second.toInstant().toEpochMilli();
1658 final long totalBytes = getTotalBytes(policy.template, start, end);
1659
1660 if (policy.lastLimitSnooze >= start) {
1661 // snoozing past quota, but we still need to restrict apps,
1662 // so push really high quota.
1663 quotaBytes = Long.MAX_VALUE;
1664 } else {
1665 // remaining "quota" bytes are based on total usage in
1666 // current cycle. kernel doesn't like 0-byte rules, so we
1667 // set 1-byte quota and disable the radio later.
1668 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1669 }
1670 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001671 // metered network, but no policy limit; we still need to
1672 // restrict apps, so push really high quota.
1673 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001674 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001675
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001676 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001677 // TODO: switch to shared quota once NMS supports
1678 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001679 }
1680
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001681 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1682 final String iface = matchingIfaces.valueAt(j);
1683 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001684 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001685 }
1686 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001687
1688 // keep track of lowest warning or limit of active policies
1689 if (hasWarning && policy.warningBytes < lowestRule) {
1690 lowestRule = policy.warningBytes;
1691 }
1692 if (hasLimit && policy.limitBytes < lowestRule) {
1693 lowestRule = policy.limitBytes;
1694 }
1695 }
1696
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001697 // One final pass to catch any metered ifaces that don't have explicitly
1698 // defined policies; typically Wi-Fi networks.
1699 for (NetworkState state : states) {
1700 if (state.networkInfo != null && state.networkInfo.isConnected()
1701 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1702 matchingIfaces.clear();
1703 collectIfaces(matchingIfaces, state);
1704 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1705 final String iface = matchingIfaces.valueAt(j);
1706 if (!newMeteredIfaces.contains(iface)) {
1707 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1708 newMeteredIfaces.add(iface);
1709 }
1710 }
1711 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001712 }
1713
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001714 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001715 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1716 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001717 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001718 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001719 }
1720 }
1721 mMeteredIfaces = newMeteredIfaces;
1722
Jeff Sharkey9252b342018-01-19 07:58:35 +09001723 // Finally, calculate our opportunistic quotas
1724 // TODO: add experiments support to disable or tweak ratios
1725 mSubscriptionOpportunisticQuota.clear();
1726 for (NetworkState state : states) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09001727 if (state.network == null) continue;
Jeff Sharkey9252b342018-01-19 07:58:35 +09001728 final int subId = getSubIdLocked(state.network);
Jeff Sharkey2e471452018-01-19 18:02:47 +09001729 final SubscriptionPlan plan = getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09001730 if (plan == null) continue;
1731
1732 // By default assume we have no quota
Jeff Sharkey9252b342018-01-19 07:58:35 +09001733 long quotaBytes = 0;
1734
Jeff Sharkey2e471452018-01-19 18:02:47 +09001735 final long limitBytes = plan.getDataLimitBytes();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001736 if (limitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1737 // Ignore missing limits
Jeff Sharkey2e471452018-01-19 18:02:47 +09001738 } else if (limitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
Jeff Sharkey9252b342018-01-19 07:58:35 +09001739 // Unlimited data; let's use 20MiB/day (600MiB/month)
1740 quotaBytes = DataUnit.MEBIBYTES.toBytes(20);
1741 } else {
1742 // Limited data; let's only use 10% of remaining budget
Jeff Sharkey2e471452018-01-19 18:02:47 +09001743 final Pair<ZonedDateTime, ZonedDateTime> cycle = plan.cycleIterator().next();
Jeff Sharkey9252b342018-01-19 07:58:35 +09001744 final long start = cycle.first.toInstant().toEpochMilli();
1745 final long end = cycle.second.toInstant().toEpochMilli();
1746 final long totalBytes = getTotalBytes(
1747 NetworkTemplate.buildTemplateMobileAll(state.subscriberId), start, end);
1748 final long remainingBytes = limitBytes - totalBytes;
1749 final long remainingDays = Math.min(1, (end - RecurrenceRule.sClock.millis())
1750 / TimeUnit.DAYS.toMillis(1));
1751 if (remainingBytes > 0) {
1752 quotaBytes = (remainingBytes / remainingDays) / 10;
1753 }
1754 }
1755
1756 mSubscriptionOpportunisticQuota.put(subId, quotaBytes);
1757 }
1758
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001759 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001760 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001761
1762 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001763 }
1764
1765 /**
1766 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1767 * have at least a default mobile policy defined.
1768 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001769 private void ensureActiveMobilePolicyAL() {
1770 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001771 if (mSuppressDefaultPolicy) return;
1772
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001773 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001774 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001775
Jeff Sharkey2e471452018-01-19 18:02:47 +09001776 final int[] subIds = ArrayUtils.defeatNullable(sub.getActiveSubscriptionIdList());
Jeff Sharkey32566012014-12-02 18:30:14 -08001777 for (int subId : subIds) {
1778 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001779 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001780 }
1781 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001782
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001783 /**
1784 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1785 * have at least a default mobile policy defined.
1786 *
1787 * @param subId to build a default policy for
1788 * @param subscriberId that we check for an existing policy
1789 * @return true if a mobile network policy was added, or false one already existed.
1790 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001791 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001792 // Poke around to see if we already have a policy
1793 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001794 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001795 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1796 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1797 if (template.matches(probeIdent)) {
1798 if (LOGD) {
1799 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1800 + NetworkIdentity.scrubSubscriberId(subscriberId));
1801 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001802 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001803 }
1804 }
1805
Jeff Sharkey32566012014-12-02 18:30:14 -08001806 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1807 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001808 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001809 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001810 return true;
1811 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001812
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001813 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001814 final int dataWarningConfig = mContext.getResources().getInteger(
1815 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001816 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001817 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001818 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001819 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001820 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001821 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001822
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001823 private long getPlatformDefaultLimitBytes() {
1824 return LIMIT_DISABLED;
1825 }
1826
1827 @VisibleForTesting
1828 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001829 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001830 final RecurrenceRule cycleRule = NetworkPolicy
1831 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001832 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001833 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1834 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1835 synchronized (mUidRulesFirstLock) {
1836 synchronized (mNetworkPoliciesSecondLock) {
1837 updateDefaultMobilePolicyAL(subId, policy);
1838 }
1839 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001840 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001841 }
1842
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001843 /**
1844 * Update the given {@link NetworkPolicy} based on any carrier-provided
1845 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1846 * Leaves policy untouched if the user has modified it.
1847 *
1848 * @return if the policy was modified
1849 */
1850 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1851 if (!policy.inferred) {
1852 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1853 return false;
1854 }
1855
1856 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1857 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1858 policy.lastLimitSnooze, policy.metered, policy.inferred);
1859
1860 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1861 if (!ArrayUtils.isEmpty(plans)) {
1862 final SubscriptionPlan plan = plans[0];
1863 policy.cycleRule = plan.getCycleRule();
1864 final long planLimitBytes = plan.getDataLimitBytes();
1865 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1866 policy.warningBytes = getPlatformDefaultWarningBytes();
1867 policy.limitBytes = getPlatformDefaultLimitBytes();
1868 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1869 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1870 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1871 } else {
1872 policy.warningBytes = (planLimitBytes * 9) / 10;
1873 switch (plan.getDataLimitBehavior()) {
1874 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1875 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1876 policy.limitBytes = planLimitBytes;
1877 break;
1878 default:
1879 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1880 break;
1881 }
1882 }
1883 } else {
1884 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1885 final int currentCycleDay;
1886 if (policy.cycleRule.isMonthly()) {
1887 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1888 } else {
1889 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1890 }
1891 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1892 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1893 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1894 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1895 }
1896
1897 if (policy.equals(original)) {
1898 return false;
1899 } else {
1900 Slog.d(TAG, "Updated " + original + " to " + policy);
1901 return true;
1902 }
1903 }
1904
Felipe Lemef0823852016-06-08 13:43:08 -07001905 private void readPolicyAL() {
1906 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001907
1908 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001909 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001910 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001911 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001912 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001913
1914 FileInputStream fis = null;
1915 try {
1916 fis = mPolicyFile.openRead();
1917 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001918 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001919
Felipe Leme46b451f2016-08-19 08:46:17 -07001920 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1921 // to skip UIDs that were explicitly blacklisted.
1922 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1923
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001924 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001925 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001926 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001927 while ((type = in.next()) != END_DOCUMENT) {
1928 final String tag = in.getName();
1929 if (type == START_TAG) {
1930 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001931 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001932 version = readIntAttribute(in, ATTR_VERSION);
Sudheer Shanka543339f2017-07-28 15:18:07 -07001933 mLoadedRestrictBackground = (version >= VERSION_ADDED_RESTRICT_BACKGROUND)
1934 && readBooleanAttribute(in, ATTR_RESTRICT_BACKGROUND);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001935 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1936 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1937 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001938 final String networkId;
1939 if (version >= VERSION_ADDED_NETWORK_ID) {
1940 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1941 } else {
1942 networkId = null;
1943 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001944 final RecurrenceRule cycleRule;
1945 if (version >= VERSION_ADDED_CYCLE) {
1946 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1947 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1948 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1949 cycleRule = new RecurrenceRule(
1950 RecurrenceRule.convertZonedDateTime(start),
1951 RecurrenceRule.convertZonedDateTime(end),
1952 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001953 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001954 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1955 final String cycleTimezone;
1956 if (version >= VERSION_ADDED_TIMEZONE) {
1957 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1958 } else {
1959 cycleTimezone = "UTC";
1960 }
1961 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001962 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001963 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1964 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001965 final long lastLimitSnooze;
1966 if (version >= VERSION_SPLIT_SNOOZE) {
1967 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1968 } else if (version >= VERSION_ADDED_SNOOZE) {
1969 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001970 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001971 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001972 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001973 final boolean metered;
1974 if (version >= VERSION_ADDED_METERED) {
1975 metered = readBooleanAttribute(in, ATTR_METERED);
1976 } else {
1977 switch (networkTemplate) {
1978 case MATCH_MOBILE_3G_LOWER:
1979 case MATCH_MOBILE_4G:
1980 case MATCH_MOBILE_ALL:
1981 metered = true;
1982 break;
1983 default:
1984 metered = false;
1985 }
1986 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001987 final long lastWarningSnooze;
1988 if (version >= VERSION_SPLIT_SNOOZE) {
1989 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1990 } else {
1991 lastWarningSnooze = SNOOZE_NEVER;
1992 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001993 final boolean inferred;
1994 if (version >= VERSION_ADDED_INFERRED) {
1995 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1996 } else {
1997 inferred = false;
1998 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001999
Jeff Sharkey32566012014-12-02 18:30:14 -08002000 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
2001 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002002 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002003 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
2004 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002005 lastLimitSnooze, metered, inferred));
2006 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002007
2008 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
2009 final String start = readStringAttribute(in, ATTR_CYCLE_START);
2010 final String end = readStringAttribute(in, ATTR_CYCLE_END);
2011 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
2012 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
2013 RecurrenceRule.convertZonedDateTime(start),
2014 RecurrenceRule.convertZonedDateTime(end),
2015 RecurrenceRule.convertPeriod(period));
2016 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
2017 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
2018
2019 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
2020 SubscriptionPlan.BYTES_UNKNOWN);
2021 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
2022 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
2023 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
2024 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
2025 builder.setDataLimit(limitBytes, limitBehavior);
2026 }
2027
2028 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
2029 SubscriptionPlan.BYTES_UNKNOWN);
2030 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
2031 SubscriptionPlan.TIME_UNKNOWN);
2032 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
2033 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
2034 builder.setDataUsage(usageBytes, usageTime);
2035 }
2036
2037 final int subId = readIntAttribute(in, ATTR_SUB_ID);
2038 final SubscriptionPlan plan = builder.build();
2039 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
2040 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
2041
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002042 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
2043 mSubscriptionPlansOwner.put(subId, ownerPackage);
2044
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002045 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002046 final int uid = readIntAttribute(in, ATTR_UID);
2047 final int policy = readIntAttribute(in, ATTR_POLICY);
2048
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002049 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002050 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002051 } else {
2052 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
2053 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002054 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002055 final int appId = readIntAttribute(in, ATTR_APP_ID);
2056 final int policy = readIntAttribute(in, ATTR_POLICY);
2057
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002058 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07002059 // app policy is deprecated so this is only used in pre system user split.
2060 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002061 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002062 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002063 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002064 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002065 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002066 } else if (TAG_WHITELIST.equals(tag)) {
2067 insideWhitelist = true;
2068 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2069 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07002070 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002071 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
2072 final int uid = readIntAttribute(in, ATTR_UID);
2073 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002074 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002075 } else if (type == END_TAG) {
2076 if (TAG_WHITELIST.equals(tag)) {
2077 insideWhitelist = false;
2078 }
2079
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002080 }
2081 }
2082
Felipe Leme46b451f2016-08-19 08:46:17 -07002083 final int size = whitelistedRestrictBackground.size();
2084 for (int i = 0; i < size; i++) {
2085 final int uid = whitelistedRestrictBackground.keyAt(i);
2086 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2087 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2088 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2089 + " because its policy is " + uidPoliciesToString(policy));
2090 continue;
2091 }
2092 if (UserHandle.isApp(uid)) {
2093 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2094 if (LOGV)
2095 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2096 setUidPolicyUncheckedUL(uid, newPolicy, false);
2097 } else {
2098 Slog.w(TAG, "unable to update policy on UID " + uid);
2099 }
2100 }
2101
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002102 } catch (FileNotFoundException e) {
2103 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002104 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002105 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002106 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002107 } finally {
2108 IoUtils.closeQuietly(fis);
2109 }
2110 }
2111
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002112 /**
2113 * Upgrade legacy background data flags, notifying listeners of one last
2114 * change to always-true.
2115 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002116 private void upgradeDefaultBackgroundDataUL() {
2117 // This method is only called when we're unable to find the network policy flag, which
2118 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002119
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002120 // Seed from the default value configured for this device.
Sudheer Shanka543339f2017-07-28 15:18:07 -07002121 mLoadedRestrictBackground = Settings.Global.getInt(
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002122 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2123
2124 // NOTE: We used to read the legacy setting here :
2125 //
2126 // final int legacyFlagValue = Settings.Secure.getInt(
2127 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2128 //
2129 // This is no longer necessary because we will never upgrade directly from Gingerbread
2130 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2131 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002132 }
2133
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002134 /**
2135 * Perform upgrade step of moving any user-defined meterness overrides over
2136 * into {@link WifiConfiguration}.
2137 */
2138 private void upgradeWifiMeteredOverrideAL() {
2139 boolean modified = false;
2140 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2141 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2142 for (int i = 0; i < mNetworkPolicy.size(); ) {
2143 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2144 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2145 && !policy.inferred) {
2146 mNetworkPolicy.removeAt(i);
2147 modified = true;
2148
2149 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2150 for (WifiConfiguration config : configs) {
2151 if (Objects.equals(resolveNetworkId(config), networkId)) {
2152 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2153 config.meteredOverride = policy.metered
2154 ? WifiConfiguration.METERED_OVERRIDE_METERED
2155 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2156 wm.updateNetwork(config);
2157 }
2158 }
2159 } else {
2160 i++;
2161 }
2162 }
2163 if (modified) {
2164 writePolicyAL();
2165 }
2166 }
2167
Felipe Lemef0823852016-06-08 13:43:08 -07002168 void writePolicyAL() {
2169 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002170
2171 FileOutputStream fos = null;
2172 try {
2173 fos = mPolicyFile.startWrite();
2174
2175 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002176 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002177 out.startDocument(null, true);
2178
2179 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002180 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002181 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002182
2183 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002184 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2185 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002186 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002187 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002188
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002189 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002190 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2191 final String subscriberId = template.getSubscriberId();
2192 if (subscriberId != null) {
2193 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002194 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002195 final String networkId = template.getNetworkId();
2196 if (networkId != null) {
2197 out.attribute(null, ATTR_NETWORK_ID, networkId);
2198 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002199 writeStringAttribute(out, ATTR_CYCLE_START,
2200 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2201 writeStringAttribute(out, ATTR_CYCLE_END,
2202 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2203 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2204 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002205 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2206 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002207 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2208 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002209 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002210 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002211 out.endTag(null, TAG_NETWORK_POLICY);
2212 }
2213
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002214 // write all known subscription plans
2215 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2216 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002217 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002218 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2219 if (ArrayUtils.isEmpty(plans)) continue;
2220
2221 for (SubscriptionPlan plan : plans) {
2222 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2223 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002224 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002225 final RecurrenceRule cycleRule = plan.getCycleRule();
2226 writeStringAttribute(out, ATTR_CYCLE_START,
2227 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2228 writeStringAttribute(out, ATTR_CYCLE_END,
2229 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2230 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2231 RecurrenceRule.convertPeriod(cycleRule.period));
2232 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2233 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2234 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2235 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2236 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2237 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2238 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2239 }
2240 }
2241
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002242 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002243 for (int i = 0; i < mUidPolicy.size(); i++) {
2244 final int uid = mUidPolicy.keyAt(i);
2245 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002246
Jeff Sharkey497e4432011-06-14 17:27:29 -07002247 // skip writing empty policies
2248 if (policy == POLICY_NONE) continue;
2249
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002250 out.startTag(null, TAG_UID_POLICY);
2251 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002252 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002253 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002254 }
2255
2256 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002257
2258 // write all whitelists
2259 out.startTag(null, TAG_WHITELIST);
2260
Felipe Lemea9505cc2016-02-26 10:28:41 -08002261 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002262 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002263 for (int i = 0; i < size; i++) {
2264 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2265 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2266 writeIntAttribute(out, ATTR_UID, uid);
2267 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2268 }
2269
Felipe Lemeb85a6372016-01-14 16:16:16 -08002270 out.endTag(null, TAG_WHITELIST);
2271
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002272 out.endDocument();
2273
2274 mPolicyFile.finishWrite(fos);
2275 } catch (IOException e) {
2276 if (fos != null) {
2277 mPolicyFile.failWrite(fos);
2278 }
2279 }
2280 }
2281
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002282 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002283 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002284 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002285
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002286 if (!UserHandle.isApp(uid)) {
2287 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002288 }
Felipe Lemef0823852016-06-08 13:43:08 -07002289 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002290 final long token = Binder.clearCallingIdentity();
2291 try {
2292 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2293 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002294 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002295 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002296 }
2297 } finally {
2298 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002299 }
2300 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002301 }
2302
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002303 @Override
2304 public void addUidPolicy(int uid, int policy) {
2305 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002306
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002307 if (!UserHandle.isApp(uid)) {
2308 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2309 }
2310
Felipe Lemef0823852016-06-08 13:43:08 -07002311 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002312 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2313 policy |= oldPolicy;
2314 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002315 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002316 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002317 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002318 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002319 }
2320
2321 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002322 public void removeUidPolicy(int uid, int policy) {
2323 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2324
2325 if (!UserHandle.isApp(uid)) {
2326 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2327 }
2328
Felipe Lemef0823852016-06-08 13:43:08 -07002329 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002330 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2331 policy = oldPolicy & ~policy;
2332 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002333 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Sudheer Shanka352dc572017-09-22 17:09:38 -07002334 mLogger.uidPolicyChanged(uid, oldPolicy, policy);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002335 }
2336 }
2337 }
2338
Felipe Lemef0823852016-06-08 13:43:08 -07002339 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2340 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002341
Felipe Leme57e3d312016-08-23 14:42:52 -07002342 final boolean notifyApp;
2343 if (!isUidValidForWhitelistRules(uid)) {
2344 notifyApp = false;
2345 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002346 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2347 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2348 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2349 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002350 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2351 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002352 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2353 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2354 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2355 if (LOGD)
2356 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2357 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2358 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002359 notifyApp = wasBlocked != isBlocked;
2360 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002361 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2362 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002363 }
2364
Felipe Lemef0823852016-06-08 13:43:08 -07002365 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002366 if (policy == POLICY_NONE) {
2367 mUidPolicy.delete(uid);
2368 } else {
2369 mUidPolicy.put(uid, policy);
2370 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002371
2372 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002373 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002374 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002375 synchronized (mNetworkPoliciesSecondLock) {
2376 writePolicyAL();
2377 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002378 }
2379 }
2380
2381 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002382 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002383 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2384
Felipe Lemef0823852016-06-08 13:43:08 -07002385 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002386 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002387 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002388 }
2389
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002390 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002391 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002392 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2393
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002394 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002395 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002396 for (int i = 0; i < mUidPolicy.size(); i++) {
2397 final int uid = mUidPolicy.keyAt(i);
2398 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002399 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2400 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002401 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002402 }
2403 }
2404 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002405 return uids;
2406 }
2407
2408 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002409 * Removes any persistable state associated with given {@link UserHandle}, persisting
2410 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002411 */
Felipe Lemef0823852016-06-08 13:43:08 -07002412 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002413
Sudheer Shanka352dc572017-09-22 17:09:38 -07002414 mLogger.removingUserState(userId);
Felipe Lemed17fda42016-04-29 11:12:45 -07002415 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002416
Felipe Lemea110eec2016-04-29 09:58:06 -07002417 // Remove entries from revoked default restricted background UID whitelist
2418 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2419 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2420 if (UserHandle.getUserId(uid) == userId) {
2421 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002422 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002423 }
2424 }
2425
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002426 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002427 int[] uids = new int[0];
2428 for (int i = 0; i < mUidPolicy.size(); i++) {
2429 final int uid = mUidPolicy.keyAt(i);
2430 if (UserHandle.getUserId(uid) == userId) {
2431 uids = appendInt(uids, uid);
2432 }
2433 }
2434
2435 if (uids.length > 0) {
2436 for (int uid : uids) {
2437 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002438 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002439 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002440 }
Felipe Lemef0823852016-06-08 13:43:08 -07002441 synchronized (mNetworkPoliciesSecondLock) {
2442 updateRulesForGlobalChangeAL(true);
2443 if (writePolicy && changed) {
2444 writePolicyAL();
2445 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002446 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002447 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002448 }
2449
2450 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002451 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002452 // TODO: create permission for observing network policy
2453 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002454 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002455 }
2456
2457 @Override
2458 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002459 // TODO: create permission for observing network policy
2460 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002461 mListeners.unregister(listener);
2462 }
2463
Jeff Sharkey1b861272011-05-22 00:34:52 -07002464 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002465 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002466 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2467
Felipe Leme6a05eee2016-02-19 14:43:51 -08002468 final long token = Binder.clearCallingIdentity();
2469 try {
2470 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002471 synchronized (mUidRulesFirstLock) {
2472 synchronized (mNetworkPoliciesSecondLock) {
2473 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002474 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002475 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002476 }
2477 } finally {
2478 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002479 }
2480 }
2481
Hugo Benichi446c9c92017-04-10 09:41:10 +09002482 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002483 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002484 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2485 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002486 }
2487
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002488 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002489 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002490 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002491 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002492 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2493 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2494 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002495 } catch (SecurityException e) {
2496 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002497
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002498 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2499 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2500 return new NetworkPolicy[0];
2501 }
Svet Ganov16a16892015-04-16 10:32:04 -07002502 }
2503
Felipe Lemef0823852016-06-08 13:43:08 -07002504 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002505 final int size = mNetworkPolicy.size();
2506 final NetworkPolicy[] policies = new NetworkPolicy[size];
2507 for (int i = 0; i < size; i++) {
2508 policies[i] = mNetworkPolicy.valueAt(i);
2509 }
2510 return policies;
2511 }
2512 }
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 private void normalizePoliciesNL() {
2515 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002516 }
2517
Felipe Lemef0823852016-06-08 13:43:08 -07002518 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002519 final TelephonyManager tele = TelephonyManager.from(mContext);
2520 final String[] merged = tele.getMergedSubscriberIds();
2521
2522 mNetworkPolicy.clear();
2523 for (NetworkPolicy policy : policies) {
2524 // When two normalized templates conflict, prefer the most
2525 // restrictive policy
2526 policy.template = NetworkTemplate.normalize(policy.template, merged);
2527 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2528 if (existing == null || existing.compareTo(policy) > 0) {
2529 if (existing != null) {
2530 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2531 }
2532 mNetworkPolicy.put(policy.template, policy);
2533 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002534 }
2535 }
2536
2537 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002538 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002539 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002540
2541 final long token = Binder.clearCallingIdentity();
2542 try {
2543 performSnooze(template, TYPE_LIMIT);
2544 } finally {
2545 Binder.restoreCallingIdentity(token);
2546 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002547 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002548
Dianne Hackborn497175b2014-07-01 12:56:08 -07002549 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002550 maybeRefreshTrustedTime();
2551 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002552 synchronized (mUidRulesFirstLock) {
2553 synchronized (mNetworkPoliciesSecondLock) {
2554 // find and snooze local policy that matches
2555 final NetworkPolicy policy = mNetworkPolicy.get(template);
2556 if (policy == null) {
2557 throw new IllegalArgumentException("unable to find policy for " + template);
2558 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002559
Felipe Lemef0823852016-06-08 13:43:08 -07002560 switch (type) {
2561 case TYPE_WARNING:
2562 policy.lastWarningSnooze = currentTime;
2563 break;
2564 case TYPE_LIMIT:
2565 policy.lastLimitSnooze = currentTime;
2566 break;
2567 default:
2568 throw new IllegalArgumentException("unexpected type");
2569 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002570
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002571 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002572 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002573 }
2574 }
2575
2576 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002577 public void onTetheringChanged(String iface, boolean tethering) {
2578 // No need to enforce permission because setRestrictBackground() will do it.
Felipe Lemef0823852016-06-08 13:43:08 -07002579 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002580 if (mRestrictBackground && tethering) {
2581 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2582 setRestrictBackground(false);
2583 }
2584 }
2585 }
2586
2587 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002588 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002589 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002590 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002591 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2592 final long token = Binder.clearCallingIdentity();
2593 try {
2594 maybeRefreshTrustedTime();
2595 synchronized (mUidRulesFirstLock) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002596 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002597 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002598 } finally {
2599 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002600 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002601 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002602 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002603 }
2604 }
2605
Felipe Lemef0823852016-06-08 13:43:08 -07002606 private void setRestrictBackgroundUL(boolean restrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002607 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackgroundUL");
Felipe Leme70c57c22016-03-29 10:45:13 -07002608 try {
Sudheer Shanka543339f2017-07-28 15:18:07 -07002609 if (restrictBackground == mRestrictBackground) {
2610 // Ideally, UI should never allow this scenario...
2611 Slog.w(TAG, "setRestrictBackgroundUL: already " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002612 return;
2613 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002614 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
2615 final boolean oldRestrictBackground = mRestrictBackground;
2616 mRestrictBackground = restrictBackground;
2617 // Must whitelist foreground apps before turning data saver mode on.
2618 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2619 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
2620 updateRulesForRestrictBackgroundUL();
2621 try {
2622 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2623 Slog.e(TAG,
2624 "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2625 mRestrictBackground = oldRestrictBackground;
2626 // TODO: if it knew the foreground apps (see TODO above), it could call
2627 // updateRulesForRestrictBackgroundUL() again to restore state.
2628 return;
2629 }
2630 } catch (RemoteException e) {
2631 // ignored; service lives in system_server
2632 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002633
Sudheer Shanka543339f2017-07-28 15:18:07 -07002634 sendRestrictBackgroundChangedMsg();
Sudheer Shanka352dc572017-09-22 17:09:38 -07002635 mLogger.restrictBackgroundChanged(oldRestrictBackground, mRestrictBackground);
Sudheer Shanka543339f2017-07-28 15:18:07 -07002636
2637 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2638 mRestrictBackgroundChangedInBsm = true;
2639 }
2640 synchronized (mNetworkPoliciesSecondLock) {
2641 updateNotificationsNL();
2642 writePolicyAL();
2643 }
2644 } finally {
2645 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
jackqdyulei29c82ab2017-03-10 14:09:16 -08002646 }
Sudheer Shanka543339f2017-07-28 15:18:07 -07002647 }
2648
2649 private void sendRestrictBackgroundChangedMsg() {
2650 mHandler.removeMessages(MSG_RESTRICT_BACKGROUND_CHANGED);
2651 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, mRestrictBackground ? 1 : 0, 0)
2652 .sendToTarget();
Felipe Leme70c57c22016-03-29 10:45:13 -07002653 }
2654
Felipe Lemeb85a6372016-01-14 16:16:16 -08002655 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002656 public int getRestrictBackgroundByCaller() {
2657 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2658 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002659
Felipe Lemef0823852016-06-08 13:43:08 -07002660 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002661 // Must clear identity because getUidPolicy() is restricted to system.
2662 final long token = Binder.clearCallingIdentity();
2663 final int policy;
2664 try {
2665 policy = getUidPolicy(uid);
2666 } finally {
2667 Binder.restoreCallingIdentity(token);
2668 }
2669 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2670 // App is blacklisted.
2671 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2672 }
Felipe Leme1b103232016-01-22 09:44:57 -08002673 if (!mRestrictBackground) {
2674 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2675 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002676 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002677 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2678 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2679 }
2680 }
2681
2682 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002683 public boolean getRestrictBackground() {
2684 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2685
Felipe Lemef0823852016-06-08 13:43:08 -07002686 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002687 return mRestrictBackground;
2688 }
2689 }
2690
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002691 @Override
2692 public void setDeviceIdleMode(boolean enabled) {
2693 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002694 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2695 try {
2696 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002697 if (mDeviceIdleMode == enabled) {
2698 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002699 }
Felipe Lemeea014392016-09-06 13:59:54 -07002700 mDeviceIdleMode = enabled;
Sudheer Shanka352dc572017-09-22 17:09:38 -07002701 mLogger.deviceIdleModeEnabled(enabled);
Felipe Lemeea014392016-09-06 13:59:54 -07002702 if (mSystemReady) {
2703 // Device idle change means we need to rebuild rules for all
2704 // known apps, so do a global refresh.
2705 updateRulesForRestrictPowerUL();
2706 }
2707 }
2708 if (enabled) {
2709 EventLogTags.writeDeviceIdleOnPhase("net");
2710 } else {
2711 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002712 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002713 } finally {
2714 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002715 }
2716 }
2717
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002718 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002719 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2720 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002721 final long token = Binder.clearCallingIdentity();
2722 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002723 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2724 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2725 for (WifiConfiguration config : configs) {
2726 if (Objects.equals(resolveNetworkId(config), networkId)) {
2727 config.meteredOverride = meteredOverride;
2728 wm.updateNetwork(config);
2729 }
2730 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002731 } finally {
2732 Binder.restoreCallingIdentity(token);
2733 }
2734 }
2735
Jeff Sharkey46645002011-07-27 21:11:21 -07002736 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002737 @Deprecated
2738 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2739 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2740 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2741 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002742 }
2743
Jeff Sharkey53313d72017-07-13 16:47:32 -06002744 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2745 // Verify they're not lying about package name
2746 mAppOps.checkPackage(callingUid, callingPackage);
2747
Jeff Sharkey53313d72017-07-13 16:47:32 -06002748 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002749 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002750 final long token = Binder.clearCallingIdentity();
2751 try {
2752 si = mContext.getSystemService(SubscriptionManager.class)
2753 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002754 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002755 } finally {
2756 Binder.restoreCallingIdentity(token);
2757 }
2758
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002759 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002760 if (si != null) {
2761 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2762 return;
2763 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002764 }
2765
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002766 // Second check: has the CarrierService delegated access?
2767 if (config != null) {
2768 final String overridePackage = config
2769 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2770 if (!TextUtils.isEmpty(overridePackage)
2771 && Objects.equals(overridePackage, callingPackage)) {
2772 return;
2773 }
2774 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002775
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002776 // Third check: is caller the fallback/default CarrierService?
2777 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2778 if (!TextUtils.isEmpty(defaultPackage)
2779 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002780 return;
2781 }
2782
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002783 // Final check: does the caller hold a permission?
2784 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002785 }
2786
2787 @Override
2788 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2789 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2790
Jeff Sharkey53313d72017-07-13 16:47:32 -06002791 final String fake = SystemProperties.get("fw.fake_plan");
2792 if (!TextUtils.isEmpty(fake)) {
2793 final List<SubscriptionPlan> plans = new ArrayList<>();
2794 if ("month_hard".equals(fake)) {
2795 plans.add(SubscriptionPlan.Builder
2796 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2797 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002798 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2799 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2800 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2801 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2802 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002803 plans.add(SubscriptionPlan.Builder
2804 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2805 .setTitle("G-Mobile Happy")
2806 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2807 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2808 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2809 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2810 .build());
2811 plans.add(SubscriptionPlan.Builder
2812 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2813 .setTitle("G-Mobile, Charged after limit")
2814 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2815 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2816 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2817 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2818 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002819 } else if ("month_soft".equals(fake)) {
2820 plans.add(SubscriptionPlan.Builder
2821 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2822 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2823 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2824 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002825 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2826 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2827 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2828 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2829 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002830 plans.add(SubscriptionPlan.Builder
2831 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2832 .setTitle("G-Mobile, Throttled after limit")
2833 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2834 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2835 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2836 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2837 .build());
2838 plans.add(SubscriptionPlan.Builder
2839 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2840 .setTitle("G-Mobile, No data connection after limit")
2841 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2842 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2843 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2844 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2845 .build());
2846
Jeff Sharkey53313d72017-07-13 16:47:32 -06002847 } else if ("month_none".equals(fake)) {
2848 plans.add(SubscriptionPlan.Builder
2849 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2850 .setTitle("G-Mobile")
2851 .build());
2852 } else if ("prepaid".equals(fake)) {
2853 plans.add(SubscriptionPlan.Builder
2854 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2855 ZonedDateTime.now().plusDays(10))
2856 .setTitle("G-Mobile")
2857 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2858 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2859 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2860 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2861 .build());
2862 } else if ("prepaid_crazy".equals(fake)) {
2863 plans.add(SubscriptionPlan.Builder
2864 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2865 ZonedDateTime.now().plusDays(10))
2866 .setTitle("G-Mobile Anytime")
2867 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2868 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2869 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2870 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2871 .build());
2872 plans.add(SubscriptionPlan.Builder
2873 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2874 ZonedDateTime.now().plusDays(20))
2875 .setTitle("G-Mobile Nickel Nights")
2876 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002877 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2878 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002879 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2880 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2881 .build());
2882 plans.add(SubscriptionPlan.Builder
2883 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2884 ZonedDateTime.now().plusDays(20))
2885 .setTitle("G-Mobile Bonus 3G")
2886 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002887 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002888 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2889 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2890 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2891 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002892 } else if ("unlimited".equals(fake)) {
2893 plans.add(SubscriptionPlan.Builder
2894 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2895 ZonedDateTime.now().plusDays(10))
2896 .setTitle("G-Mobile Awesome")
2897 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2898 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2899 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2900 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2901 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002902 }
2903 return plans.toArray(new SubscriptionPlan[plans.size()]);
2904 }
2905
Jeff Sharkey4635f102017-09-01 11:27:13 -06002906 synchronized (mNetworkPoliciesSecondLock) {
2907 // Only give out plan details to the package that defined them,
2908 // so that we don't risk leaking plans between apps. We always
2909 // let in core system components (like the Settings app).
2910 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2911 if (Objects.equals(ownerPackage, callingPackage)
2912 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2913 return mSubscriptionPlans.get(subId);
2914 } else {
2915 Log.w(TAG, "Not returning plans because caller " + callingPackage
2916 + " doesn't match owner " + ownerPackage);
2917 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002918 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002919 }
2920 }
2921
2922 @Override
2923 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2924 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2925
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002926 for (SubscriptionPlan plan : plans) {
2927 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002928 }
2929
2930 final long token = Binder.clearCallingIdentity();
2931 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002932 maybeRefreshTrustedTime();
2933 synchronized (mUidRulesFirstLock) {
2934 synchronized (mNetworkPoliciesSecondLock) {
2935 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002936 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002937
2938 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2939 .getSubscriberId(subId);
2940 ensureActiveMobilePolicyAL(subId, subscriberId);
2941 maybeUpdateMobilePolicyCycleAL(subId);
2942 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002943 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002944 }
Jeff Sharkeye92ed6f2018-01-10 20:47:42 -07002945
2946 final Intent intent = new Intent(SubscriptionManager.ACTION_SUBSCRIPTION_PLANS_CHANGED);
2947 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2948 intent.putExtra(SubscriptionManager.EXTRA_SUBSCRIPTION_INDEX, subId);
2949 mContext.sendBroadcast(intent, android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002950 } finally {
2951 Binder.restoreCallingIdentity(token);
2952 }
2953 }
2954
2955 @Override
Jeff Sharkey717f52f2018-01-04 16:04:11 -07002956 public String getSubscriptionPlansOwner(int subId) {
2957 if (UserHandle.getCallingAppId() != android.os.Process.SYSTEM_UID) {
2958 throw new SecurityException();
2959 }
2960
2961 synchronized (mNetworkPoliciesSecondLock) {
2962 return mSubscriptionPlansOwner.get(subId);
2963 }
2964 }
2965
2966 @Override
Jeff Sharkey9252b342018-01-19 07:58:35 +09002967 public void setSubscriptionOverride(int subId, int overrideMask, int overrideValue,
2968 long timeoutMillis, String callingPackage) {
2969 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2970
2971 // We can only override when carrier told us about plans
2972 synchronized (mNetworkPoliciesSecondLock) {
2973 if (ArrayUtils.isEmpty(mSubscriptionPlans.get(subId))) {
2974 throw new IllegalStateException(
2975 "Must provide SubscriptionPlan information before overriding");
2976 }
2977 }
2978
2979 mHandler.sendMessage(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2980 overrideMask, overrideValue, subId));
2981 if (timeoutMillis > 0) {
2982 mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_SUBSCRIPTION_OVERRIDE,
2983 overrideMask, 0, subId), timeoutMillis);
2984 }
2985 }
2986
2987 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002988 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002989 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002990
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002991 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2992
Dianne Hackborn497175b2014-07-01 12:56:08 -07002993 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002994 for (String arg : args) {
2995 argSet.add(arg);
2996 }
2997
Felipe Lemef0823852016-06-08 13:43:08 -07002998 synchronized (mUidRulesFirstLock) {
2999 synchronized (mNetworkPoliciesSecondLock) {
3000 if (argSet.contains("--unsnooze")) {
3001 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
3002 mNetworkPolicy.valueAt(i).clearSnooze();
3003 }
3004
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07003005 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07003006
3007 fout.println("Cleared snooze timestamps");
3008 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003009 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003010
Felipe Lemef0823852016-06-08 13:43:08 -07003011 fout.print("System ready: "); fout.println(mSystemReady);
3012 fout.print("Restrict background: "); fout.println(mRestrictBackground);
3013 fout.print("Restrict power: "); fout.println(mRestrictPower);
3014 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003015 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
3016
3017 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003018 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003019 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003020 for (int i = 0; i < mNetworkPolicy.size(); i++) {
3021 fout.println(mNetworkPolicy.valueAt(i).toString());
3022 }
3023 fout.decreaseIndent();
3024
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003025 fout.println();
3026 fout.println("Subscription plans:");
3027 fout.increaseIndent();
3028 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
3029 final int subId = mSubscriptionPlans.keyAt(i);
3030 fout.println("Subscriber ID " + subId + ":");
3031 fout.increaseIndent();
3032 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
3033 if (!ArrayUtils.isEmpty(plans)) {
3034 for (SubscriptionPlan plan : plans) {
3035 fout.println(plan);
3036 }
3037 }
3038 fout.decreaseIndent();
3039 }
3040 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07003041
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06003042 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07003043 fout.println("Policy for UIDs:");
3044 fout.increaseIndent();
3045 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003046 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07003047 final int uid = mUidPolicy.keyAt(i);
3048 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003049 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07003050 fout.print(uid);
3051 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07003052 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07003053 fout.println();
3054 }
3055 fout.decreaseIndent();
3056
3057 size = mPowerSaveWhitelistExceptIdleAppIds.size();
3058 if (size > 0) {
3059 fout.println("Power save whitelist (except idle) app ids:");
3060 fout.increaseIndent();
3061 for (int i = 0; i < size; i++) {
3062 fout.print("UID=");
3063 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
3064 fout.print(": ");
3065 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
3066 fout.println();
3067 }
3068 fout.decreaseIndent();
3069 }
3070
3071 size = mPowerSaveWhitelistAppIds.size();
3072 if (size > 0) {
3073 fout.println("Power save whitelist app ids:");
3074 fout.increaseIndent();
3075 for (int i = 0; i < size; i++) {
3076 fout.print("UID=");
3077 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
3078 fout.print(": ");
3079 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
3080 fout.println();
3081 }
3082 fout.decreaseIndent();
3083 }
3084
Felipe Lemef0823852016-06-08 13:43:08 -07003085 size = mDefaultRestrictBackgroundWhitelistUids.size();
3086 if (size > 0) {
3087 fout.println("Default restrict background whitelist uids:");
3088 fout.increaseIndent();
3089 for (int i = 0; i < size; i++) {
3090 fout.print("UID=");
3091 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
3092 fout.println();
3093 }
3094 fout.decreaseIndent();
3095 }
3096
3097 size = mRestrictBackgroundWhitelistRevokedUids.size();
3098 if (size > 0) {
3099 fout.println("Default restrict background whitelist uids revoked by users:");
3100 fout.increaseIndent();
3101 for (int i = 0; i < size; i++) {
3102 fout.print("UID=");
3103 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
3104 fout.println();
3105 }
3106 fout.decreaseIndent();
3107 }
3108
3109 final SparseBooleanArray knownUids = new SparseBooleanArray();
3110 collectKeys(mUidState, knownUids);
3111 collectKeys(mUidRules, knownUids);
3112
3113 fout.println("Status for all known UIDs:");
3114 fout.increaseIndent();
3115 size = knownUids.size();
3116 for (int i = 0; i < size; i++) {
3117 final int uid = knownUids.keyAt(i);
3118 fout.print("UID=");
3119 fout.print(uid);
3120
3121 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3122 fout.print(" state=");
3123 fout.print(state);
3124 if (state <= ActivityManager.PROCESS_STATE_TOP) {
3125 fout.print(" (fg)");
3126 } else {
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003127 fout.print(state <= ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE
Felipe Lemef0823852016-06-08 13:43:08 -07003128 ? " (fg svc)" : " (bg)");
3129 }
3130
3131 final int uidRules = mUidRules.get(uid, RULE_NONE);
3132 fout.print(" rules=");
3133 fout.print(uidRulesToString(uidRules));
3134 fout.println();
3135 }
3136 fout.decreaseIndent();
3137
3138 fout.println("Status for just UIDs with rules:");
3139 fout.increaseIndent();
3140 size = mUidRules.size();
3141 for (int i = 0; i < size; i++) {
3142 final int uid = mUidRules.keyAt(i);
3143 fout.print("UID=");
3144 fout.print(uid);
3145 final int uidRules = mUidRules.get(uid, RULE_NONE);
3146 fout.print(" rules=");
3147 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003148 fout.println();
3149 }
3150 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003151
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003152 fout.println("Admin restricted uids for metered data:");
3153 fout.increaseIndent();
3154 size = mMeteredRestrictedUids.size();
3155 for (int i = 0; i < size; ++i) {
3156 fout.print("u" + mMeteredRestrictedUids.keyAt(i) + ": ");
3157 fout.println(mMeteredRestrictedUids.valueAt(i));
3158 }
3159 fout.decreaseIndent();
3160
Sudheer Shanka352dc572017-09-22 17:09:38 -07003161 mLogger.dumpLogs(fout);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003162 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003163 }
3164 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003165
3166 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003167 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003168 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003169 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003170 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003171 }
3172
3173 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003174 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003175 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3176
Felipe Lemef0823852016-06-08 13:43:08 -07003177 synchronized (mUidRulesFirstLock) {
3178 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003179 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003180 }
3181
Felipe Lemef0823852016-06-08 13:43:08 -07003182 private boolean isUidForegroundUL(int uid) {
3183 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003184 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3185 }
3186
Felipe Lemef0823852016-06-08 13:43:08 -07003187 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003188 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003189 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003190 }
3191
Felipe Lemef0823852016-06-08 13:43:08 -07003192 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003193 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3194 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3195 }
3196
Felipe Lemef0823852016-06-08 13:43:08 -07003197 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003198 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003199 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003200 }
3201
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003202 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003203 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003204 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3205 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003206 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003207 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003208 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3209 try {
3210 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3211 if (oldUidState != uidState) {
3212 // state changed, push updated rules
3213 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003214 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3215 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3216 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003217 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003218 if (mDeviceIdleMode) {
3219 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003220 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003221 if (mRestrictPower) {
3222 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003223 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003224 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003225 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003226 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003227 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003228 } finally {
3229 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003230 }
3231 }
3232
Felipe Lemef0823852016-06-08 13:43:08 -07003233 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003234 final int index = mUidState.indexOfKey(uid);
3235 if (index >= 0) {
3236 final int oldUidState = mUidState.valueAt(index);
3237 mUidState.removeAt(index);
3238 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003239 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003240 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003241 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003242 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003243 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003244 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003245 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003246 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003247 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003248 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003249 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003250 }
3251 }
3252
Felipe Lemef28983d2016-03-25 12:18:23 -07003253 // adjust stats accounting based on foreground status
3254 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003255 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3256 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3257 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3258 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003259 try {
3260 mNetworkStats.setUidForeground(uid, uidForeground);
3261 } catch (RemoteException e) {
3262 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003263 } finally {
3264 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003265 }
3266 }
3267
Sudheer Shankac9d94072017-02-22 22:13:55 +00003268 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3269 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003270 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003271 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003272 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003273 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003274 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003275 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003276 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003277 }
3278
Felipe Lemef0823852016-06-08 13:43:08 -07003279 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003280 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3281 try {
3282 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3283 mUidFirewallPowerSaveRules);
3284 } finally {
3285 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3286 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003287 }
3288
Felipe Lemef0823852016-06-08 13:43:08 -07003289 void updateRuleForRestrictPowerUL(int uid) {
3290 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003291 }
3292
Felipe Lemef0823852016-06-08 13:43:08 -07003293 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003294 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3295 try {
3296 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3297 mUidFirewallDozableRules);
3298 } finally {
3299 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3300 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003301 }
3302
Felipe Lemef0823852016-06-08 13:43:08 -07003303 void updateRuleForDeviceIdleUL(int uid) {
3304 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003305 }
3306
Felipe Lemef28983d2016-03-25 12:18:23 -07003307 // NOTE: since both fw_dozable and fw_powersave uses the same map
3308 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003309 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003310 SparseIntArray rules) {
3311 if (enabled) {
3312 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003313 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003314 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003315 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003316 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003317 for (int ui = users.size() - 1; ui >= 0; ui--) {
3318 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003319 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3320 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3321 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3322 updateRulesForWhitelistedAppIds(uidRules,
3323 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003324 }
3325 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003326 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003327 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003328 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3329 }
3330 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003331 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003332 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003333 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003334 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003335 }
3336
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003337 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3338 final SparseBooleanArray whitelistedAppIds, int userId) {
3339 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3340 if (whitelistedAppIds.valueAt(i)) {
3341 final int appId = whitelistedAppIds.keyAt(i);
3342 final int uid = UserHandle.getUid(userId, appId);
3343 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3344 }
3345 }
3346 }
3347
3348 /**
3349 * @param deviceIdleMode if true then we don't consider
3350 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3351 * whitelisted.
3352 */
3353 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003354 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003355 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3356 || mPowerSaveWhitelistAppIds.get(appId);
3357 if (!deviceIdleMode) {
3358 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3359 }
3360 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003361 }
3362
Felipe Lemef28983d2016-03-25 12:18:23 -07003363 // NOTE: since both fw_dozable and fw_powersave uses the same map
3364 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003365 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003366 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003367 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3368 chain == FIREWALL_CHAIN_DOZABLE);
3369 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003370 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003371 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003372 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003373 }
3374 }
3375 }
3376
Felipe Lemef0823852016-06-08 13:43:08 -07003377 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003378 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3379 try {
3380 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3381 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003382
Felipe Leme873a83a2016-09-07 11:34:10 -07003383 // Fully update the app idle firewall chain.
3384 final List<UserInfo> users = mUserManager.getUsers();
3385 for (int ui = users.size() - 1; ui >= 0; ui--) {
3386 UserInfo user = users.get(ui);
3387 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3388 for (int uid : idleUids) {
3389 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3390 // quick check: if this uid doesn't have INTERNET permission, it
3391 // doesn't have network access anyway, so it is a waste to mess
3392 // with it here.
3393 if (hasInternetPermissions(uid)) {
3394 uidRules.put(uid, FIREWALL_RULE_DENY);
3395 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003396 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003397 }
3398 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003399
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003400 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003401 } finally {
3402 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3403 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003404 }
3405
Felipe Lemef0823852016-06-08 13:43:08 -07003406 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003407 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003408
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003409 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3410 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3411 }
3412 try {
3413 int appId = UserHandle.getAppId(uid);
3414 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3415 && !isUidForegroundOnRestrictPowerUL(uid)) {
3416 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3417 } else {
3418 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3419 }
3420 } finally {
3421 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003422 }
3423 }
3424
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003425 /**
3426 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3427 * changed.
3428 */
Felipe Lemef0823852016-06-08 13:43:08 -07003429 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003430 boolean paroled = mUsageStats.isAppIdleParoleOn();
3431 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003432 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003433
3434 int ruleCount = mUidFirewallStandbyRules.size();
3435 for (int i = 0; i < ruleCount; i++) {
3436 int uid = mUidFirewallStandbyRules.keyAt(i);
3437 int oldRules = mUidRules.get(uid);
3438 if (enableChain) {
3439 // Chain wasn't enabled before and the other power-related
3440 // chains are whitelists, so we can clear the
3441 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3442 // the effective rules result in blocking network access.
3443 oldRules &= MASK_METERED_NETWORKS;
3444 } else {
3445 // Skip if it had no restrictions to begin with
3446 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3447 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003448 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3449 if (newUidRules == RULE_NONE) {
3450 mUidRules.delete(uid);
3451 } else {
3452 mUidRules.put(uid, newUidRules);
3453 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003454 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003455 }
3456
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003457 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003458 * Update rules that might be changed by {@link #mRestrictBackground},
3459 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003460 */
Felipe Lemef0823852016-06-08 13:43:08 -07003461 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003462 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3463 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3464 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3465 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003466 try {
Felipe Leme09700462016-09-08 09:33:48 -07003467 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003468 updateRulesForRestrictPowerUL();
3469 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003470
Felipe Leme873a83a2016-09-07 11:34:10 -07003471 // If the set of restricted networks may have changed, re-evaluate those.
3472 if (restrictedNetworksChanged) {
3473 normalizePoliciesNL();
3474 updateNetworkRulesNL();
3475 }
3476 } finally {
3477 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003478 }
3479 }
3480
Felipe Leme09700462016-09-08 09:33:48 -07003481 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003482 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003483 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3484 try {
3485 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003486 updateRulesForPowerSaveUL();
3487 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3488 } finally {
3489 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3490 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003491 }
3492
Felipe Lemef0823852016-06-08 13:43:08 -07003493 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003494 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3495 try {
3496 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3497 } finally {
3498 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3499 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003500 }
3501
3502 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3503 private static final int TYPE_RESTRICT_POWER = 2;
3504 @Retention(RetentionPolicy.SOURCE)
3505 @IntDef(flag = false, value = {
3506 TYPE_RESTRICT_BACKGROUND,
3507 TYPE_RESTRICT_POWER,
3508 })
3509 public @interface RestrictType {
3510 }
3511
3512 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003513 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003514 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3515 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3516 }
3517 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003518 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003519
3520 final PackageManager pm = mContext.getPackageManager();
3521 final List<UserInfo> users;
3522 final List<ApplicationInfo> apps;
3523
3524 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3525 try {
3526 users = mUserManager.getUsers();
3527 } finally {
3528 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3529 }
3530 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3531 try {
3532 apps = pm.getInstalledApplications(
3533 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3534 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3535 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3536 } finally {
3537 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3538 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003539
Felipe Leme873a83a2016-09-07 11:34:10 -07003540 final int usersSize = users.size();
3541 final int appsSize = apps.size();
3542 for (int i = 0; i < usersSize; i++) {
3543 final UserInfo user = users.get(i);
3544 for (int j = 0; j < appsSize; j++) {
3545 final ApplicationInfo app = apps.get(j);
3546 final int uid = UserHandle.getUid(user.id, app.uid);
3547 switch (type) {
3548 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003549 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003550 break;
3551 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003552 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003553 break;
3554 default:
3555 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3556 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003557 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003558 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003559 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003560 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003561 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003562 }
3563
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003564 private void updateRulesForTempWhitelistChangeUL(int appId) {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003565 final List<UserInfo> users = mUserManager.getUsers();
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003566 final int numUsers = users.size();
3567 for (int i = 0; i < numUsers; i++) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003568 final UserInfo user = users.get(i);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07003569 int uid = UserHandle.getUid(user.id, appId);
3570 // Update external firewall rules.
3571 updateRuleForAppIdleUL(uid);
3572 updateRuleForDeviceIdleUL(uid);
3573 updateRuleForRestrictPowerUL(uid);
3574 // Update internal rules.
3575 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003576 }
3577 }
3578
Felipe Leme70c57c22016-03-29 10:45:13 -07003579 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3580 // methods below could be merged into a isUidValidForRules() method.
3581 private boolean isUidValidForBlacklistRules(int uid) {
3582 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003583 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003584 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003585 return true;
3586 }
3587
3588 return false;
3589 }
3590
Felipe Leme70c57c22016-03-29 10:45:13 -07003591 private boolean isUidValidForWhitelistRules(int uid) {
3592 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3593 }
3594
Amith Yamasani15e472352015-04-24 19:06:07 -07003595 private boolean isUidIdle(int uid) {
3596 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3597 final int userId = UserHandle.getUserId(uid);
3598
songjinshi0655edd2016-05-18 19:55:32 +08003599 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003600 for (String packageName : packages) {
3601 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3602 return false;
3603 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003604 }
3605 }
3606 return true;
3607 }
3608
3609 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003610 * Checks if an uid has INTERNET permissions.
3611 * <p>
3612 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003613 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003614 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003615 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003616 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003617 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003618 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003619 }
3620 } catch (RemoteException e) {
3621 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003622 return true;
3623 }
3624
3625 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003626 * Clears all state - internal and external - associated with an UID.
3627 */
3628 private void onUidDeletedUL(int uid) {
3629 // First cleanup in-memory state synchronously...
3630 mUidRules.delete(uid);
3631 mUidPolicy.delete(uid);
3632 mUidFirewallStandbyRules.delete(uid);
3633 mUidFirewallDozableRules.delete(uid);
3634 mUidFirewallPowerSaveRules.delete(uid);
3635 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3636 mPowerSaveWhitelistAppIds.delete(uid);
3637 mPowerSaveTempWhitelistAppIds.delete(uid);
3638
3639 // ...then update iptables asynchronously.
3640 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3641 }
3642
3643 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003644 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003645 *
Felipe Leme781ba142016-05-09 16:24:48 -07003646 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003647 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003648 * <li>Doze mode
3649 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003650 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003651 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003652 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003653 *
3654 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003655 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003656 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003657 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003658 updateRuleForDeviceIdleUL(uid);
3659 updateRuleForAppIdleUL(uid);
3660 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003661
3662 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003663 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003664
3665 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003666 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003667 }
3668
Felipe Leme70c57c22016-03-29 10:45:13 -07003669 /**
3670 * Applies network rules to bandwidth controllers based on process state and user-defined
3671 * restrictions (blacklist / whitelist).
3672 *
3673 * <p>
3674 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3675 * networks:
3676 * <ul>
3677 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3678 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3679 * also blacklisted.
3680 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3681 * no UIDs other those whitelisted will have access.
3682 * <ul>
3683 *
3684 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3685 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3686 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3687 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003688 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003689 * {@link INetworkManagementService}, but this method should also be called in events (like
3690 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3691 * following rules should also be applied:
3692 *
3693 * <ul>
3694 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3695 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3696 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3697 * {@code bw_penalty_box}.
3698 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3699 * </ul>
3700 *
3701 * <p>For optimization, the rules are only applied on user apps that have internet access
3702 * permission, since there is no need to change the {@code iptables} rule if the app does not
3703 * have permission to use the internet.
3704 *
3705 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003706 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003707 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003708 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003709 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3710 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3711 "updateRulesForDataUsageRestrictionsUL: " + uid);
3712 }
3713 try {
3714 updateRulesForDataUsageRestrictionsULInner(uid);
3715 } finally {
3716 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3717 }
3718 }
3719
3720 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003721 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003722 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003723 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003724 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003725
Dianne Hackborn497175b2014-07-01 12:56:08 -07003726 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003727 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003728 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003729 final boolean isRestrictedByAdmin = isRestrictedByAdminUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003730
Felipe Leme781ba142016-05-09 16:24:48 -07003731 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003732 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003733 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3734 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003735
Felipe Leme70c57c22016-03-29 10:45:13 -07003736 // First step: define the new rule based on user restrictions and foreground state.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003737 if (isRestrictedByAdmin) {
3738 newRule = RULE_REJECT_METERED;
3739 } else if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003740 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3741 newRule = RULE_TEMPORARY_ALLOW_METERED;
3742 } else if (isWhitelisted) {
3743 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003744 }
3745 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003746 if (isBlacklisted) {
3747 newRule = RULE_REJECT_METERED;
3748 } else if (mRestrictBackground && isWhitelisted) {
3749 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003750 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003751 }
Felipe Leme781ba142016-05-09 16:24:48 -07003752 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003753
Felipe Lemef28983d2016-03-25 12:18:23 -07003754 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003755 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003756 + ": isForeground=" +isForeground
3757 + ", isBlacklisted=" + isBlacklisted
3758 + ", isWhitelisted=" + isWhitelisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003759 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Leme781ba142016-05-09 16:24:48 -07003760 + ", oldRule=" + uidRulesToString(oldRule)
3761 + ", newRule=" + uidRulesToString(newRule)
3762 + ", newUidRules=" + uidRulesToString(newUidRules)
3763 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003764 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003765
Felipe Leme46c4fc32016-05-04 09:21:43 -07003766 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003767 mUidRules.delete(uid);
3768 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003769 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003770 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003771
Felipe Leme70c57c22016-03-29 10:45:13 -07003772 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003773 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003774 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003775 // Temporarily whitelist foreground app, removing from blacklist if necessary
3776 // (since bw_penalty_box prevails over bw_happy_box).
3777
3778 setMeteredNetworkWhitelist(uid, true);
3779 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3780 // but ideally it should be just:
3781 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003782 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003783 setMeteredNetworkBlacklist(uid, false);
3784 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003785 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003786 // Remove temporary whitelist from app that is not on foreground anymore.
3787
3788 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3789 // but ideally they should be just:
3790 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3791 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003792 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003793 setMeteredNetworkWhitelist(uid, false);
3794 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003795 if (isBlacklisted || isRestrictedByAdmin) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003796 setMeteredNetworkBlacklist(uid, true);
3797 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003798 } else if (hasRule(newRule, RULE_REJECT_METERED)
3799 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003800 // Flip state because app was explicitly added or removed to blacklist.
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003801 setMeteredNetworkBlacklist(uid, (isBlacklisted || isRestrictedByAdmin));
Hugo Benichi2966c182017-03-28 17:17:13 +09003802 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003803 // Since blacklist prevails over whitelist, we need to handle the special case
3804 // where app is whitelisted and blacklisted at the same time (although such
3805 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003806 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003807 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003808 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3809 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003810 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003811 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003812 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003813 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003814 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3815 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003816 + ", whitelisted=" + isWhitelisted
3817 + ", blacklisted=" + isBlacklisted
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08003818 + ", isRestrictedByAdmin=" + isRestrictedByAdmin
Felipe Lemed31a97f2016-05-06 14:53:50 -07003819 + ", newRule=" + uidRulesToString(newUidRules)
3820 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003821 }
Felipe Leme781ba142016-05-09 16:24:48 -07003822
Sudheer Shankac9d94072017-02-22 22:13:55 +00003823 // Dispatch changed rule to existing listeners.
3824 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003825 }
3826 }
3827
3828 /**
3829 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3830 * listeners in case of change.
3831 * <p>
3832 * There are 3 power-related rules that affects whether an app has background access on
3833 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3834 * restriction, it's added to the equivalent firewall chain:
3835 * <ul>
3836 * <li>App is idle: {@code fw_standby} firewall chain.
3837 * <li>Device is idle: {@code fw_dozable} firewall chain.
3838 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3839 * </ul>
3840 * <p>
3841 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3842 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3843 * <p>
3844 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3845 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003846 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003847 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3848
Sudheer Shankac9d94072017-02-22 22:13:55 +00003849 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003850
Sudheer Shankac9d94072017-02-22 22:13:55 +00003851 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003852 mUidRules.delete(uid);
3853 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003854 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003855 }
3856 }
3857
3858 /**
3859 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3860 *
3861 * @param uid the uid of the app to update rules for
3862 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3863 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3864 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003865 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003866 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003867 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003868 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3869 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3870 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3871 + (paroled ? "P" : "-"));
3872 }
3873 try {
3874 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3875 } finally {
3876 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3877 }
3878 }
3879
3880 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003881 if (!isUidValidForBlacklistRules(uid)) {
3882 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003883 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003884 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003885
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003886 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003887 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003888 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003889
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003890 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003891 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3892 int newRule = RULE_NONE;
3893
3894 // First step: define the new rule based on user restrictions and foreground state.
3895
3896 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3897 // by considering the foreground and non-foreground states.
3898 if (isForeground) {
3899 if (restrictMode) {
3900 newRule = RULE_ALLOW_ALL;
3901 }
3902 } else if (restrictMode) {
3903 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3904 }
3905
3906 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3907
3908 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003909 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003910 + ", isIdle: " + isIdle
3911 + ", mRestrictPower: " + mRestrictPower
3912 + ", mDeviceIdleMode: " + mDeviceIdleMode
3913 + ", isForeground=" + isForeground
3914 + ", isWhitelisted=" + isWhitelisted
3915 + ", oldRule=" + uidRulesToString(oldRule)
3916 + ", newRule=" + uidRulesToString(newRule)
3917 + ", newUidRules=" + uidRulesToString(newUidRules)
3918 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3919 }
3920
Felipe Leme781ba142016-05-09 16:24:48 -07003921 // Second step: notify listeners if state changed.
3922 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003923 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003924 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003925 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003926 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3927 } else {
3928 // All scenarios should have been covered above
3929 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3930 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003931 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003932 + ", newRule=" + uidRulesToString(newUidRules)
3933 + ", oldRule=" + uidRulesToString(oldUidRules));
3934 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003935 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003936 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003937
Sudheer Shankac9d94072017-02-22 22:13:55 +00003938 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003939 }
3940
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003941 private class AppIdleStateChangeListener
3942 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3943
3944 @Override
Amith Yamasani84cd7b72017-11-07 13:59:37 -08003945 public void onAppIdleStateChanged(String packageName, int userId, boolean idle, int bucket) {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003946 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003947 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3948 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Lemef0823852016-06-08 13:43:08 -07003949 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003950 mLogger.appIdleStateChanged(uid, idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003951 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003952 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003953 }
3954 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003955 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003956 }
3957
3958 @Override
3959 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003960 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07003961 mLogger.paroleStateChanged(isParoleOn);
Felipe Lemef0823852016-06-08 13:43:08 -07003962 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003963 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003964 }
3965 }
3966
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003967 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3968 if (listener != null) {
3969 try {
3970 listener.onUidRulesChanged(uid, uidRules);
3971 } catch (RemoteException ignored) {
3972 }
3973 }
3974 }
3975
3976 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3977 String[] meteredIfaces) {
3978 if (listener != null) {
3979 try {
3980 listener.onMeteredIfacesChanged(meteredIfaces);
3981 } catch (RemoteException ignored) {
3982 }
3983 }
3984 }
3985
3986 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3987 boolean restrictBackground) {
3988 if (listener != null) {
3989 try {
3990 listener.onRestrictBackgroundChanged(restrictBackground);
3991 } catch (RemoteException ignored) {
3992 }
3993 }
3994 }
3995
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003996 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3997 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003998 if (listener != null) {
3999 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004000 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004001 } catch (RemoteException ignored) {
4002 }
4003 }
4004 }
4005
Jeff Sharkey9252b342018-01-19 07:58:35 +09004006 private void dispatchSubscriptionOverride(INetworkPolicyListener listener, int subId,
4007 int overrideMask, int overrideValue) {
4008 if (listener != null) {
4009 try {
4010 listener.onSubscriptionOverride(subId, overrideMask, overrideValue);
4011 } catch (RemoteException ignored) {
4012 }
4013 }
4014 }
4015
Makoto Onuki8e777332017-03-28 11:25:47 -07004016 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07004017 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004018 public boolean handleMessage(Message msg) {
4019 switch (msg.what) {
4020 case MSG_RULES_CHANGED: {
4021 final int uid = msg.arg1;
4022 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00004023 final int length = mListeners.beginBroadcast();
4024 for (int i = 0; i < length; i++) {
4025 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4026 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004027 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00004028 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004029 return true;
4030 }
4031 case MSG_METERED_IFACES_CHANGED: {
4032 final String[] meteredIfaces = (String[]) msg.obj;
4033 final int length = mListeners.beginBroadcast();
4034 for (int i = 0; i < length; i++) {
4035 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004036 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004037 }
4038 mListeners.finishBroadcast();
4039 return true;
4040 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004041 case MSG_LIMIT_REACHED: {
4042 final String iface = (String) msg.obj;
4043
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004044 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07004045 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004046 if (mMeteredIfaces.contains(iface)) {
4047 try {
4048 // force stats update to make sure we have
4049 // numbers that caused alert to trigger.
4050 mNetworkStats.forceUpdate();
4051 } catch (RemoteException e) {
4052 // ignored; service lives in system_server
4053 }
4054
Felipe Lemef0823852016-06-08 13:43:08 -07004055 updateNetworkEnabledNL();
4056 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08004057 }
4058 }
4059 return true;
4060 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004061 case MSG_RESTRICT_BACKGROUND_CHANGED: {
4062 final boolean restrictBackground = msg.arg1 != 0;
4063 final int length = mListeners.beginBroadcast();
4064 for (int i = 0; i < length; i++) {
4065 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004066 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004067 }
4068 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08004069 final Intent intent =
4070 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4071 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4072 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
4073 return true;
4074 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004075 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08004076 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004077 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07004078 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06004079 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07004080 final int length = mListeners.beginBroadcast();
4081 for (int i = 0; i < length; i++) {
4082 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07004083 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004084 }
4085 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07004086 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
4087 if (notifyApp.booleanValue()) {
4088 broadcastRestrictBackgroundChanged(uid, notifyApp);
4089 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07004090 return true;
4091 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07004092 case MSG_ADVISE_PERSIST_THRESHOLD: {
4093 final long lowestRule = (Long) msg.obj;
4094 try {
4095 // make sure stats are recorded frequently enough; we aim
4096 // for 2MB threshold for 2GB/month rules.
4097 final long persistThreshold = lowestRule / 1000;
4098 mNetworkStats.advisePersistThreshold(persistThreshold);
4099 } catch (RemoteException e) {
4100 // ignored; service lives in system_server
4101 }
4102 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08004103 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07004104 case MSG_UPDATE_INTERFACE_QUOTA: {
4105 removeInterfaceQuota((String) msg.obj);
4106 // int params need to be stitched back into a long
4107 setInterfaceQuota((String) msg.obj,
4108 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
4109 return true;
4110 }
4111 case MSG_REMOVE_INTERFACE_QUOTA: {
4112 removeInterfaceQuota((String) msg.obj);
4113 return true;
4114 }
Felipe Leme03e95e22016-09-09 09:25:31 -07004115 case MSG_RESET_FIREWALL_RULES_BY_UID: {
4116 resetUidFirewallRules(msg.arg1);
4117 return true;
4118 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004119 case MSG_SUBSCRIPTION_OVERRIDE: {
4120 final int overrideMask = msg.arg1;
4121 final int overrideValue = msg.arg2;
4122 final int subId = (int) msg.obj;
4123 final int length = mListeners.beginBroadcast();
4124 for (int i = 0; i < length; i++) {
4125 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
4126 dispatchSubscriptionOverride(listener, subId, overrideMask, overrideValue);
4127 }
4128 mListeners.finishBroadcast();
4129 return true;
4130 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004131 case MSG_METERED_RESTRICTED_PACKAGES_CHANGED: {
4132 final int userId = msg.arg1;
4133 final Set<String> packageNames = (Set<String>) msg.obj;
4134 setMeteredRestrictedPackagesInternal(packageNames, userId);
4135 return true;
4136 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004137 default: {
4138 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07004139 }
4140 }
4141 }
Makoto Onuki8e777332017-03-28 11:25:47 -07004142 };
4143
4144 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
4145 @Override
4146 public boolean handleMessage(Message msg) {
4147 switch (msg.what) {
4148 case UID_MSG_STATE_CHANGED: {
4149 final int uid = msg.arg1;
4150 final int procState = msg.arg2;
4151 final long procStateSeq = (Long) msg.obj;
4152
4153 handleUidChanged(uid, procState, procStateSeq);
4154 return true;
4155 }
4156 case UID_MSG_GONE: {
4157 final int uid = msg.arg1;
4158 handleUidGone(uid);
4159 return true;
4160 }
4161 default: {
4162 return false;
4163 }
4164 }
4165 }
Felipe Leme57e3d312016-08-23 14:42:52 -07004166
Jeff Sharkey4414cea2011-06-24 17:05:24 -07004167 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07004168
Makoto Onuki8e777332017-03-28 11:25:47 -07004169 void handleUidChanged(int uid, int procState, long procStateSeq) {
4170 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
4171 try {
4172 synchronized (mUidRulesFirstLock) {
4173 // We received a uid state change callback, add it to the history so that it
4174 // will be useful for debugging.
Sudheer Shanka352dc572017-09-22 17:09:38 -07004175 mLogger.uidStateChanged(uid, procState, procStateSeq);
Makoto Onuki8e777332017-03-28 11:25:47 -07004176 // Now update the network policy rules as per the updated uid state.
4177 updateUidStateUL(uid, procState);
4178 // Updating the network rules is done, so notify AMS about this.
4179 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4180 }
4181 } finally {
4182 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4183 }
4184 }
4185
4186 void handleUidGone(int uid) {
4187 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4188 try {
4189 synchronized (mUidRulesFirstLock) {
4190 removeUidStateUL(uid);
4191 }
4192 } finally {
4193 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4194 }
4195 }
4196
Felipe Leme57e3d312016-08-23 14:42:52 -07004197 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4198 final PackageManager pm = mContext.getPackageManager();
4199 final String[] packages = pm.getPackagesForUid(uid);
4200 if (packages != null) {
4201 final int userId = UserHandle.getUserId(uid);
4202 for (String packageName : packages) {
4203 final Intent intent =
4204 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4205 intent.setPackage(packageName);
4206 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4207 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4208 }
4209 }
4210 }
4211
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004212 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4213 // long quotaBytes split up into two ints to fit in message
4214 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4215 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4216 }
4217
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004218 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004219 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004220 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004221 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004222 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004223 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004224 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004225 }
4226 }
4227
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004228 private void removeInterfaceQuotaAsync(String iface) {
4229 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4230 }
4231
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004232 private void removeInterfaceQuota(String iface) {
4233 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004234 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004235 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004236 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004237 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004238 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004239 }
4240 }
4241
Felipe Leme70c57c22016-03-29 10:45:13 -07004242 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4243 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004244 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004245 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004246 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004247 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4248 } catch (RemoteException e) {
4249 // ignored; service lives in system_server
4250 }
4251 }
4252
4253 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4254 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4255 try {
4256 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4257 } catch (IllegalStateException e) {
4258 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004259 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004260 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004261 }
4262 }
4263
Felipe Lemebc853dd2016-09-08 13:26:55 -07004264 private static final int CHAIN_TOGGLE_NONE = 0;
4265 private static final int CHAIN_TOGGLE_ENABLE = 1;
4266 private static final int CHAIN_TOGGLE_DISABLE = 2;
4267 @Retention(RetentionPolicy.SOURCE)
4268 @IntDef(flag = false, value = {
4269 CHAIN_TOGGLE_NONE,
4270 CHAIN_TOGGLE_ENABLE,
4271 CHAIN_TOGGLE_DISABLE
4272 })
4273 public @interface ChainToggleType {
4274 }
4275
4276 /**
4277 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004278 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004279 *
4280 * @param chain firewall chain.
4281 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4282 * @param toggle whether the chain should be enabled, disabled, or not changed.
4283 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004284 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004285 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004286 if (uidRules != null) {
4287 setUidFirewallRulesUL(chain, uidRules);
4288 }
4289 if (toggle != CHAIN_TOGGLE_NONE) {
4290 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4291 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004292 }
4293
Amith Yamasani15e472352015-04-24 19:06:07 -07004294 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004295 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4296 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4297 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004298 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004299 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004300 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004301 int size = uidRules.size();
4302 int[] uids = new int[size];
4303 int[] rules = new int[size];
4304 for(int index = size - 1; index >= 0; --index) {
4305 uids[index] = uidRules.keyAt(index);
4306 rules[index] = uidRules.valueAt(index);
4307 }
4308 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004309 mLogger.firewallRulesChanged(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004310 } catch (IllegalStateException e) {
4311 Log.wtf(TAG, "problem setting firewall uid rules", e);
4312 } catch (RemoteException e) {
4313 // ignored; service lives in system_server
4314 }
4315 }
4316
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004317 /**
4318 * Add or remove a uid to the firewall blacklist for all network ifaces.
4319 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004320 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004321 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4322 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4323 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004324 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004325 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004326 if (chain == FIREWALL_CHAIN_DOZABLE) {
4327 mUidFirewallDozableRules.put(uid, rule);
4328 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4329 mUidFirewallStandbyRules.put(uid, rule);
4330 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4331 mUidFirewallPowerSaveRules.put(uid, rule);
4332 }
4333
4334 try {
4335 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004336 mLogger.uidFirewallRuleChanged(chain, uid, rule);
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004337 } catch (IllegalStateException e) {
4338 Log.wtf(TAG, "problem setting firewall uid rules", e);
4339 } catch (RemoteException e) {
4340 // ignored; service lives in system_server
4341 }
4342 } finally {
4343 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004344 }
4345 }
4346
4347 /**
4348 * Add or remove a uid to the firewall blacklist for all network ifaces.
4349 */
Felipe Lemef0823852016-06-08 13:43:08 -07004350 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004351 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4352 mFirewallChainStates.get(chain) == enable) {
4353 // All is the same, nothing to do.
4354 return;
4355 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004356 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004357 try {
4358 mNetworkManager.setFirewallChainEnabled(chain, enable);
Sudheer Shanka352dc572017-09-22 17:09:38 -07004359 mLogger.firewallChainEnabled(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004360 } catch (IllegalStateException e) {
4361 Log.wtf(TAG, "problem enable firewall chain", e);
4362 } catch (RemoteException e) {
4363 // ignored; service lives in system_server
4364 }
4365 }
4366
Felipe Leme03e95e22016-09-09 09:25:31 -07004367 /**
4368 * Resets all firewall rules associated with an UID.
4369 */
4370 private void resetUidFirewallRules(int uid) {
4371 try {
4372 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4373 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4374 mNetworkManager
4375 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4376 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4377 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4378 } catch (IllegalStateException e) {
4379 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4380 } catch (RemoteException e) {
4381 // ignored; service lives in system_server
4382 }
4383 }
4384
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004385 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4386 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004387 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004388 } catch (RuntimeException e) {
4389 Slog.w(TAG, "problem reading network stats: " + e);
4390 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004391 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004392 // ignored; service lives in system_server
4393 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004394 }
4395 }
4396
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004397 private boolean isBandwidthControlEnabled() {
4398 final long token = Binder.clearCallingIdentity();
4399 try {
4400 return mNetworkManager.isBandwidthControlEnabled();
4401 } catch (RemoteException e) {
4402 // ignored; service lives in system_server
4403 return false;
4404 } finally {
4405 Binder.restoreCallingIdentity(token);
4406 }
4407 }
4408
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004409 /**
4410 * Try refreshing {@link #mTime} when stale.
4411 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004412 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004413 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004414 mTime.forceRefresh();
4415 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004416 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004417
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004418 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004419 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4420 }
4421
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004422 private static Intent buildAllowBackgroundDataIntent() {
4423 return new Intent(ACTION_ALLOW_BACKGROUND);
4424 }
4425
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004426 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4427 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4428 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4429 return intent;
4430 }
4431
Wei Liu546cb772016-07-21 16:19:01 -07004432 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004433 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004434 intent.setComponent(ComponentName.unflattenFromString(
4435 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004436 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4437 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4438 return intent;
4439 }
4440
Wei Liu546cb772016-07-21 16:19:01 -07004441 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004442 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004443 intent.setComponent(ComponentName.unflattenFromString(
4444 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004445 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4446 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4447 return intent;
4448 }
4449
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004450 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004451 public void addIdleHandler(IdleHandler handler) {
4452 mHandler.getLooper().getQueue().addIdleHandler(handler);
4453 }
4454
jackqdyulei29c82ab2017-03-10 14:09:16 -08004455 @VisibleForTesting
4456 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4457 mRestrictBackgroundPowerState = result;
4458
4459 boolean restrictBackground = result.batterySaverEnabled;
4460 boolean shouldInvokeRestrictBackground;
4461 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4462 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4463
4464 if (result.globalBatterySaverEnabled) {
4465 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4466 // turn it on.
4467 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4468 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4469 localRestrictBgChangedInBsm = false;
4470 } else {
4471 // Try to restore the restrictBackground if it doesn't change in bsm
4472 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4473 restrictBackground = mRestrictBackgroundBeforeBsm;
4474 }
4475
4476 if (shouldInvokeRestrictBackground) {
Sudheer Shanka543339f2017-07-28 15:18:07 -07004477 setRestrictBackgroundUL(restrictBackground);
jackqdyulei29c82ab2017-03-10 14:09:16 -08004478 }
4479
4480 // Change it at last so setRestrictBackground() won't affect this variable
4481 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4482 }
4483
Jeff Sharkey1b861272011-05-22 00:34:52 -07004484 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4485 final int size = source.size();
4486 for (int i = 0; i < size; i++) {
4487 target.put(source.keyAt(i), true);
4488 }
4489 }
4490
Stuart Scottf1fb3972015-04-02 18:00:02 -07004491 @Override
4492 public void factoryReset(String subscriber) {
4493 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4494
Stuart Scotte3e314d2015-04-20 14:07:45 -07004495 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4496 return;
4497 }
4498
Stuart Scottf1fb3972015-04-02 18:00:02 -07004499 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004500 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004501 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4502 for (NetworkPolicy policy : policies) {
4503 if (policy.template.equals(template)) {
4504 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4505 policy.inferred = false;
4506 policy.clearSnooze();
4507 }
4508 }
4509 setNetworkPolicies(policies);
4510
4511 // Turn restrict background data off
4512 setRestrictBackground(false);
4513
Stuart Scotte3e314d2015-04-20 14:07:45 -07004514 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4515 // Remove app's "restrict background data" flag
4516 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4517 setUidPolicy(uid, POLICY_NONE);
4518 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004519 }
4520 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004521
Sudheer Shankab8f23162017-08-04 13:30:10 -07004522 @Override
4523 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4524 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4525 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4526 }
4527
4528 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4529 final int uidRules;
4530 final boolean isBackgroundRestricted;
4531 synchronized (mUidRulesFirstLock) {
4532 uidRules = mUidRules.get(uid, RULE_NONE);
4533 isBackgroundRestricted = mRestrictBackground;
4534 }
4535 if (hasRule(uidRules, RULE_REJECT_ALL)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004536 mLogger.networkBlocked(uid, NTWK_BLOCKED_POWER);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004537 return true;
4538 }
4539 if (!isNetworkMetered) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004540 mLogger.networkBlocked(uid, NTWK_ALLOWED_NON_METERED);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004541 return false;
4542 }
4543 if (hasRule(uidRules, RULE_REJECT_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004544 mLogger.networkBlocked(uid, NTWK_BLOCKED_BLACKLIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004545 return true;
4546 }
4547 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004548 mLogger.networkBlocked(uid, NTWK_ALLOWED_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004549 return false;
4550 }
4551 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004552 mLogger.networkBlocked(uid, NTWK_ALLOWED_TMP_WHITELIST);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004553 return false;
4554 }
4555 if (isBackgroundRestricted) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004556 mLogger.networkBlocked(uid, NTWK_BLOCKED_BG_RESTRICT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004557 return true;
4558 }
Sudheer Shanka352dc572017-09-22 17:09:38 -07004559 mLogger.networkBlocked(uid, NTWK_ALLOWED_DEFAULT);
Sudheer Shankab8f23162017-08-04 13:30:10 -07004560 return false;
4561 }
4562
Felipe Lemed17fda42016-04-29 11:12:45 -07004563 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4564
4565 @Override
4566 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004567 synchronized (mUidRulesFirstLock) {
4568 boolean changed = removeUserStateUL(userId, false);
4569 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004570 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004571 synchronized (mNetworkPoliciesSecondLock) {
4572 writePolicyAL();
4573 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004574 }
4575 }
4576 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004577
4578 /**
4579 * @return true if the given uid is restricted from doing networking on metered networks.
4580 */
4581 @Override
4582 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4583 final int uidRules;
4584 final boolean isBackgroundRestricted;
4585 synchronized (mUidRulesFirstLock) {
4586 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4587 isBackgroundRestricted = mRestrictBackground;
4588 }
4589 return isBackgroundRestricted
4590 && !hasRule(uidRules, RULE_ALLOW_METERED)
4591 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4592 }
4593
4594 /**
4595 * @return true if networking is blocked on the given interface for the given uid according
4596 * to current networking policies.
4597 */
4598 @Override
4599 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004600 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004601 synchronized (mNetworkPoliciesSecondLock) {
4602 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004603 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004604 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004605 }
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004606
4607 @Override
4608 public void onTempPowerSaveWhitelistChange(int appId, boolean added) {
4609 synchronized (mUidRulesFirstLock) {
Sudheer Shanka352dc572017-09-22 17:09:38 -07004610 mLogger.tempPowerSaveWlChanged(appId, added);
Sudheer Shankaf34f3ec2017-08-03 11:02:56 -07004611 if (added) {
4612 mPowerSaveTempWhitelistAppIds.put(appId, true);
4613 } else {
4614 mPowerSaveTempWhitelistAppIds.delete(appId);
4615 }
4616 updateRulesForTempWhitelistChangeUL(appId);
4617 }
4618 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004619
4620 @Override
4621 public SubscriptionPlan getSubscriptionPlan(Network network) {
4622 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey2e471452018-01-19 18:02:47 +09004623 final int subId = getSubIdLocked(network);
4624 return getPrimarySubscriptionPlanLocked(subId);
Jeff Sharkey9252b342018-01-19 07:58:35 +09004625 }
4626 }
4627
4628 @Override
4629 public long getSubscriptionOpportunisticQuota(Network network, int quotaType) {
4630 synchronized (mNetworkPoliciesSecondLock) {
4631 // TODO: handle splitting quota between use-cases
4632 return mSubscriptionOpportunisticQuota.get(getSubIdLocked(network));
4633 }
4634 }
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004635
4636 @Override
4637 public void onAdminDataAvailable() {
4638 mAdminDataAvailableLatch.countDown();
4639 }
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004640
4641 @Override
4642 public void setMeteredRestrictedPackages(Set<String> packageNames, int userId) {
4643 setMeteredRestrictedPackagesInternal(packageNames, userId);
4644 }
4645
4646 @Override
4647 public void setMeteredRestrictedPackagesAsync(Set<String> packageNames, int userId) {
4648 mHandler.obtainMessage(MSG_METERED_RESTRICTED_PACKAGES_CHANGED,
4649 userId, 0, packageNames).sendToTarget();
4650 }
4651 }
4652
4653 private void setMeteredRestrictedPackagesInternal(Set<String> packageNames, int userId) {
4654 synchronized (mUidRulesFirstLock) {
4655 final Set<Integer> newRestrictedUids = new ArraySet<>();
4656 for (String packageName : packageNames) {
4657 final int uid = getUidForPackage(packageName, userId);
4658 if (uid >= 0) {
4659 newRestrictedUids.add(uid);
4660 }
4661 }
4662 final Set<Integer> oldRestrictedUids = mMeteredRestrictedUids.get(userId);
4663 mMeteredRestrictedUids.put(userId, newRestrictedUids);
4664 handleRestrictedPackagesChangeUL(oldRestrictedUids, newRestrictedUids);
4665 mLogger.meteredRestrictedPkgsChanged(newRestrictedUids);
4666 }
4667 }
4668
4669 private int getUidForPackage(String packageName, int userId) {
4670 try {
4671 return mContext.getPackageManager().getPackageUidAsUser(packageName,
4672 PackageManager.MATCH_KNOWN_PACKAGES, userId);
4673 } catch (NameNotFoundException e) {
4674 return -1;
4675 }
Jeff Sharkey9252b342018-01-19 07:58:35 +09004676 }
4677
4678 private int parseSubId(NetworkState state) {
4679 // TODO: moved to using a legitimate NetworkSpecifier instead of string parsing
4680 int subId = INVALID_SUBSCRIPTION_ID;
4681 if (state != null && state.networkCapabilities != null
4682 && state.networkCapabilities.hasTransport(TRANSPORT_CELLULAR)) {
4683 NetworkSpecifier spec = state.networkCapabilities.getNetworkSpecifier();
4684 if (spec instanceof StringNetworkSpecifier) {
4685 try {
4686 subId = Integer.parseInt(((StringNetworkSpecifier) spec).specifier);
4687 } catch (NumberFormatException e) {
4688 }
4689 }
4690 }
4691 return subId;
4692 }
4693
4694 private int getSubIdLocked(Network network) {
4695 return mNetIdToSubId.get(network.netId, INVALID_SUBSCRIPTION_ID);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004696 }
4697
Jeff Sharkey2e471452018-01-19 18:02:47 +09004698 private SubscriptionPlan getPrimarySubscriptionPlanLocked(int subId) {
4699 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
4700 return ArrayUtils.isEmpty(plans) ? null : plans[0];
4701 }
4702
Sudheer Shankac53c47f2018-01-16 12:01:00 -08004703 /**
4704 * This will only ever be called once - during device boot.
4705 */
4706 private void waitForAdminData() {
4707 if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_DEVICE_ADMIN)) {
4708 ConcurrentUtils.waitForCountDownNoInterrupt(mAdminDataAvailableLatch,
4709 WAIT_FOR_ADMIN_DATA_TIMEOUT_MS, "Wait for admin data");
4710 }
4711 }
4712
Sudheer Shanka04d61ae2018-01-17 12:16:57 -08004713 private void handleRestrictedPackagesChangeUL(Set<Integer> oldRestrictedUids,
4714 Set<Integer> newRestrictedUids) {
4715 if (oldRestrictedUids == null) {
4716 for (int uid : newRestrictedUids) {
4717 updateRulesForDataUsageRestrictionsUL(uid);
4718 }
4719 return;
4720 }
4721 for (int uid : oldRestrictedUids) {
4722 if (!newRestrictedUids.contains(uid)) {
4723 updateRulesForDataUsageRestrictionsUL(uid);
4724 }
4725 }
4726 for (int uid : newRestrictedUids) {
4727 if (!oldRestrictedUids.contains(uid)) {
4728 updateRulesForDataUsageRestrictionsUL(uid);
4729 }
4730 }
4731 }
4732
4733 private boolean isRestrictedByAdminUL(int uid) {
4734 final Set<Integer> restrictedUids = mMeteredRestrictedUids.get(
4735 UserHandle.getUserId(uid));
4736 return restrictedUids != null && restrictedUids.contains(uid);
4737 }
4738
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004739 private static boolean hasRule(int uidRules, int rule) {
4740 return (uidRules & rule) != 0;
4741 }
4742
Jeff Sharkey2e471452018-01-19 18:02:47 +09004743 private static @NonNull NetworkState[] defeatNullable(@Nullable NetworkState[] val) {
4744 return (val != null) ? val : new NetworkState[0];
4745 }
4746
Chris Wren193ae6b2017-03-31 15:17:11 -04004747 private class NotificationId {
4748 private final String mTag;
4749 private final int mId;
4750
4751 NotificationId(NetworkPolicy policy, int type) {
4752 mTag = buildNotificationTag(policy, type);
4753 mId = type;
4754 }
4755
4756 @Override
4757 public boolean equals(Object o) {
4758 if (this == o) return true;
4759 if (!(o instanceof NotificationId)) return false;
4760 NotificationId that = (NotificationId) o;
4761 return Objects.equals(mTag, that.mTag);
4762 }
4763
4764 @Override
4765 public int hashCode() {
4766 return Objects.hash(mTag);
4767 }
4768
4769 /**
4770 * Build unique tag that identifies an active {@link NetworkPolicy}
4771 * notification of a specific type, like {@link #TYPE_LIMIT}.
4772 */
4773 private String buildNotificationTag(NetworkPolicy policy, int type) {
4774 return TAG + ":" + policy.template.hashCode() + ":" + type;
4775 }
4776
4777 public String getTag() {
4778 return mTag;
4779 }
4780
4781 public int getId() {
4782 return mId;
4783 }
4784 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004785}