blob: 0b1ece5ab2dd1ce52f395786018eea2a784dc89a [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 Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
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;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070053import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070054import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070055import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070056import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070057import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
58import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070059import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
60import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070061import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080062import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070063import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
64import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
65import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
66import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
67import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
68import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
69import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070070import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080071
Jeff Sharkey854b2b12012-04-13 16:03:40 -070072import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070073import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070074import static com.android.internal.util.XmlUtils.readBooleanAttribute;
75import static com.android.internal.util.XmlUtils.readIntAttribute;
76import static com.android.internal.util.XmlUtils.readLongAttribute;
77import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
78import static com.android.internal.util.XmlUtils.writeIntAttribute;
79import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070080import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070081import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060082
Jeff Sharkey21c9c452011-06-07 12:26:43 -070083import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080084import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070086
Dianne Hackborn88e98df2015-03-23 13:29:14 -070087import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070088import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070090import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070091import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070093import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070094import android.app.Notification;
95import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070096import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070098import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070099import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700100import android.content.Intent;
101import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700102import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700103import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700104import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700105import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700106import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700107import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700108import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700109import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700110import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700111import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700112import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700113import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700114import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700115import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700116import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700118import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700119import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700120import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700122import android.net.wifi.WifiConfiguration;
123import android.net.wifi.WifiInfo;
124import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700125import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.os.Environment;
127import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700128import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700129import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700130import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700131import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700132import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700133import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700135import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700136import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700137import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600138import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700140import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700141import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700142import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800143import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700144import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700145import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700146import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700147import android.util.ArrayMap;
148import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700149import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700150import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700151import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700152import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700153import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700154import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700155import android.util.SparseBooleanArray;
156import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import android.util.TrustedTime;
158import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700159
Jeff Sharkey497e4432011-06-14 17:27:29 -0700160import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800161import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800162import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800163import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700165import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700166import com.android.server.DeviceIdleController;
167import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700168import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800169import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600170
171import libcore.io.IoUtils;
172
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700174
175import org.xmlpull.v1.XmlPullParser;
176import org.xmlpull.v1.XmlPullParserException;
177import org.xmlpull.v1.XmlSerializer;
178
179import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700180import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181import java.io.FileInputStream;
182import java.io.FileNotFoundException;
183import java.io.FileOutputStream;
184import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700185import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100186import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187import java.util.ArrayList;
188import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700189import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700190
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700191/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700192 * Service that maintains low-level network policy rules, using
193 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700194 * <p>
195 * Derives active rules by combining a given policy with other system status,
196 * and delivers to listeners, such as {@link ConnectivityManager}, for
197 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700198 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700199public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800200 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700201 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700202 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700203
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700204 private static final int VERSION_INIT = 1;
205 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700206 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800207 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800208 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800209 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700210 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700211 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700212 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700213 private static final int VERSION_SWITCH_UID = 10;
214 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800216 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700217 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800218 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700219 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700221 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700222
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700223 private static final String TAG_POLICY_LIST = "policy-list";
224 private static final String TAG_NETWORK_POLICY = "network-policy";
225 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700226 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800227 private static final String TAG_WHITELIST = "whitelist";
228 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800229 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230
231 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700232 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700233 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
234 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700235 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700236 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800237 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238 private static final String ATTR_WARNING_BYTES = "warningBytes";
239 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700240 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800241 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
242 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800243 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700244 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700246 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700247 private static final String ATTR_POLICY = "policy";
248
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800250 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800251 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800252 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700253
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
255
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700256 private static final int MSG_RULES_CHANGED = 1;
257 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800258 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800259 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700260 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700261 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800262 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700263 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
264 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700265
Jeff Sharkey75279902011-05-24 18:39:45 -0700266 private final Context mContext;
267 private final IActivityManager mActivityManager;
268 private final IPowerManager mPowerManager;
269 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700270 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700271 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700272 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700273 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274
275 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700276 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700277 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700278 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700279
Dianne Hackborn497175b2014-07-01 12:56:08 -0700280 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700281
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700282 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700283 volatile boolean mScreenOn;
284 volatile boolean mRestrictBackground;
285 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700286 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700287
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700288 private final boolean mSuppressDefaultPolicy;
289
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700290 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800291 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700292 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800293 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700294
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700295 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700296 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800298 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700299
Jeff Sharkeydc988062015-09-14 10:09:47 -0700300 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
301 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800302 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700303
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700304 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700305 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
306
Jeff Sharkey32566012014-12-02 18:30:14 -0800307 /**
308 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700309 * in power save mode, except device idle (doze) still applies.
310 * TODO: An int array might be sufficient
311 */
312 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
313
314 /**
315 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800316 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700317 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800318 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700319 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700320
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700321 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
322
Felipe Lemeb85a6372016-01-14 16:16:16 -0800323 /**
324 * UIDs that have been white-listed to avoid restricted background.
325 */
326 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
327
Felipe Lemea9505cc2016-02-26 10:28:41 -0800328 /**
329 * UIDs that have been initially white-listed by system to avoid restricted background.
330 */
331 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
332 new SparseBooleanArray();
333
334 /**
335 * UIDs that have been initially white-listed by system to avoid restricted background,
336 * but later revoked by user.
337 */
338 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
339 new SparseBooleanArray();
340
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700341 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800342 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800344 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700345
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700346 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700347 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700348
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700349 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800350 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700351
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 private final RemoteCallbackList<INetworkPolicyListener>
353 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700354
Dianne Hackborn497175b2014-07-01 12:56:08 -0700355 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700356
357 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700358
Svet Ganov16a16892015-04-16 10:32:04 -0700359 private final AppOpsManager mAppOps;
360
Felipe Lemeb85a6372016-01-14 16:16:16 -0800361 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800362 private final IPackageManager mIPm;
363
Felipe Lemeb85a6372016-01-14 16:16:16 -0800364
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700365 // TODO: keep whitelist of system-critical services that should never have
366 // rules enforced, such as system, phone, and radio UIDs.
367
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700368 // TODO: migrate notifications to SystemUI
369
Jeff Sharkey75279902011-05-24 18:39:45 -0700370 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700371 IPowerManager powerManager, INetworkStatsService networkStats,
372 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700373 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700374 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700375 }
376
377 private static File getSystemDir() {
378 return new File(Environment.getDataDirectory(), "system");
379 }
380
381 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700382 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700383 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
384 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700385 mContext = checkNotNull(context, "missing context");
386 mActivityManager = checkNotNull(activityManager, "missing activityManager");
387 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700388 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700389 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700390 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700391 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700392 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700393 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800394 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700395
Amith Yamasani450a16b2013-09-18 16:28:50 -0700396 HandlerThread thread = new HandlerThread(TAG);
397 thread.start();
398 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700400 mSuppressDefaultPolicy = suppressDefaultPolicy;
401
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700403
404 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800405
406 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407 }
408
409 public void bindConnectivityManager(IConnectivityManager connManager) {
410 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700411 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700412
Jeff Sharkey497e4432011-06-14 17:27:29 -0700413 public void bindNotificationManager(INotificationManager notifManager) {
414 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
415 }
416
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700417 void updatePowerSaveWhitelistLocked() {
418 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700419 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
420 mPowerSaveWhitelistExceptIdleAppIds.clear();
421 if (whitelist != null) {
422 for (int uid : whitelist) {
423 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
424 }
425 }
426 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700427 mPowerSaveWhitelistAppIds.clear();
428 if (whitelist != null) {
429 for (int uid : whitelist) {
430 mPowerSaveWhitelistAppIds.put(uid, true);
431 }
432 }
433 } catch (RemoteException e) {
434 }
435 }
436
Felipe Lemea9505cc2016-02-26 10:28:41 -0800437 /**
438 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
439 * revoke the whitelist.
440 *
441 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
442 */
443 boolean addDefaultRestrictBackgroundWhitelistUids() {
444 final SystemConfig sysConfig = SystemConfig.getInstance();
445 final PackageManager pm = mContext.getPackageManager();
446 final List<UserInfo> users = mUserManager.getUsers();
447 final int numberUsers = users.size();
448
449 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
450 boolean changed = false;
451 for (int i = 0; i < allowDataUsage.size(); i++) {
452 final String pkg = allowDataUsage.valueAt(i);
453 if (LOGD)
454 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg);
455 final ApplicationInfo app;
456 try {
457 app = pm.getApplicationInfo(pkg, PackageManager.MATCH_SYSTEM_ONLY);
458 } catch (PackageManager.NameNotFoundException e) {
459 // Should not happen
460 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
461 continue;
462 }
463 if (!app.isPrivilegedApp()) {
464 Slog.w(TAG, "getAllowInDataUsageSave() returned non-privileged app: " + pkg);
465 continue;
466 }
467 for (int j = 0; j < numberUsers; j++) {
468 final UserInfo user = users.get(i);
469 final int uid = UserHandle.getUid(user.id, app.uid);
470 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
471 if (LOGD) Slog.d(TAG, "revoked whistelist status for uid " + uid + ": "
472 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
473 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
474 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
475 + user.id + ") to restrict background whitelist");
476 mRestrictBackgroundWhitelistUids.append(uid, true);
477 changed = true;
478 }
479 }
480 }
481 return changed;
482 }
483
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700484 void updatePowerSaveTempWhitelistLocked() {
485 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700486 // Clear the states of the current whitelist
487 final int N = mPowerSaveTempWhitelistAppIds.size();
488 for (int i = 0; i < N; i++) {
489 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
490 }
491 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700492 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700493 if (whitelist != null) {
494 for (int uid : whitelist) {
495 mPowerSaveTempWhitelistAppIds.put(uid, true);
496 }
497 }
498 } catch (RemoteException e) {
499 }
500 }
501
Amith Yamasani06f08062015-06-12 13:23:33 -0700502 /**
503 * Remove unnecessary entries in the temp whitelist
504 */
505 void purgePowerSaveTempWhitelistLocked() {
506 final int N = mPowerSaveTempWhitelistAppIds.size();
507 for (int i = N - 1; i >= 0; i--) {
508 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
509 mPowerSaveTempWhitelistAppIds.removeAt(i);
510 }
511 }
512 }
513
Jeff Sharkeya4620792011-05-20 15:29:23 -0700514 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700515 if (!isBandwidthControlEnabled()) {
516 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
517 return;
518 }
519
Amith Yamasani15e472352015-04-24 19:06:07 -0700520 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
521
Felipe Lemeb85a6372016-01-14 16:16:16 -0800522 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
523
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700524 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700525 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700526 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
527 mPowerManagerInternal.registerLowPowerModeObserver(
528 new PowerManagerInternal.LowPowerModeListener() {
529 @Override
530 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800531 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700532 synchronized (mRulesLock) {
533 if (mRestrictPower != enabled) {
534 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800535 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700536 updateRulesForGlobalChangeLocked(true);
537 }
538 }
539 }
540 });
541 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700542 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700543
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700544 // read policy from disk
545 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700546
Felipe Lemea9505cc2016-02-26 10:28:41 -0800547 if (addDefaultRestrictBackgroundWhitelistUids()) {
548 writePolicyLocked();
549 }
550
Jeff Sharkeydc988062015-09-14 10:09:47 -0700551 updateRulesForGlobalChangeLocked(false);
552 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700553 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700554
Jeff Sharkeya4620792011-05-20 15:29:23 -0700555 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700556
Jeff Sharkeya4620792011-05-20 15:29:23 -0700557 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700558 mActivityManager.registerUidObserver(mUidObserver,
559 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700560 mNetworkManager.registerObserver(mAlertObserver);
561 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700562 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700563 }
564
Jeff Sharkeya4620792011-05-20 15:29:23 -0700565 // TODO: traverse existing processes to know foreground state, or have
566 // activitymanager dispatch current state when new observer attached.
567
568 final IntentFilter screenFilter = new IntentFilter();
569 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
570 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700571 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700573 // listen for changes to power save whitelist
574 final IntentFilter whitelistFilter = new IntentFilter(
575 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
576 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
577
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700578 DeviceIdleController.LocalService deviceIdleService
579 = LocalServices.getService(DeviceIdleController.LocalService.class);
580 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
581
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700582 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900583 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700584 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
585
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700586 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700587 final IntentFilter packageFilter = new IntentFilter();
588 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700589 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700590 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700591
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700592 // listen for UID changes to update policy
593 mContext.registerReceiver(
594 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
595
596 // listen for user changes to update policy
597 final IntentFilter userFilter = new IntentFilter();
598 userFilter.addAction(ACTION_USER_ADDED);
599 userFilter.addAction(ACTION_USER_REMOVED);
600 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
601
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700602 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700603 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
604 mContext.registerReceiver(
605 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
606
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700607 // listen for restrict background changes from notifications
608 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
609 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
610
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800611 // listen for snooze warning from notifications
612 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
613 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
614 MANAGE_NETWORK_POLICY, mHandler);
615
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700616 // listen for configured wifi networks to be removed
617 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700618 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700619
620 // listen for wifi state changes to catch metered hint
621 final IntentFilter wifiStateFilter = new IntentFilter(
622 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700623 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700624
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700625 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700626
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700627 }
628
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700629 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700630 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700631 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700632 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700633 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700634 }
635
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700636 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700637 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700638 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700639 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700640 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700641
642 @Override public void onUidActive(int uid) throws RemoteException {
643 }
644
645 @Override public void onUidIdle(int uid) throws RemoteException {
646 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700647 };
648
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700649 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700650 @Override
651 public void onReceive(Context context, Intent intent) {
652 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
653 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700654 updatePowerSaveWhitelistLocked();
655 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700656 }
657 }
658 };
659
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700660 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
661 @Override
662 public void run() {
663 synchronized (mRulesLock) {
664 updatePowerSaveTempWhitelistLocked();
665 updateRulesForTempWhitelistChangeLocked();
666 purgePowerSaveTempWhitelistLocked();
667 }
668 }
669 };
670
671 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700672 @Override
673 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800674 // screen-related broadcasts are protected by system, no need
675 // for permissions check.
676 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700677 }
678 };
679
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700680 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700681 @Override
682 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700683 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700684
685 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700686 final int uid = intent.getIntExtra(EXTRA_UID, -1);
687 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700688
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700689 if (ACTION_PACKAGE_ADDED.equals(action)) {
690 // update rules for UID, since it might be subject to
691 // global background data policy
692 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
693 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700694 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700695 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700696 }
697 }
698 };
699
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700700 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700701 @Override
702 public void onReceive(Context context, Intent intent) {
703 // on background handler thread, and UID_REMOVED is protected
704
705 final int uid = intent.getIntExtra(EXTRA_UID, -1);
706 if (uid == -1) return;
707
708 // remove any policy and update rules to clean up
709 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
710 synchronized (mRulesLock) {
711 mUidPolicy.delete(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -0700712 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700713 writePolicyLocked();
714 }
715 }
716 };
717
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700718 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700719 @Override
720 public void onReceive(Context context, Intent intent) {
721 // on background handler thread, and USER_ADDED and USER_REMOVED
722 // broadcasts are protected
723
724 final String action = intent.getAction();
725 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
726 if (userId == -1) return;
727
Amith Yamasani15e472352015-04-24 19:06:07 -0700728 switch (action) {
729 case ACTION_USER_REMOVED:
730 case ACTION_USER_ADDED:
731 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800732 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700733 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800734 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700735 // Update global restrict for new user
736 updateRulesForGlobalChangeLocked(true);
737 }
738 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700739 }
740 }
741 };
742
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700743 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700744 * Receiver that watches for {@link INetworkStatsService} updates, which we
745 * use to check against {@link NetworkPolicy#warningBytes}.
746 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700747 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700748 @Override
749 public void onReceive(Context context, Intent intent) {
750 // on background handler thread, and verified
751 // READ_NETWORK_USAGE_HISTORY permission above.
752
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800753 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700754 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700755 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700756 updateNotificationsLocked();
757 }
758 }
759 };
760
761 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700762 * Receiver that watches for {@link Notification} control of
763 * {@link #mRestrictBackground}.
764 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700765 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700766 @Override
767 public void onReceive(Context context, Intent intent) {
768 // on background handler thread, and verified MANAGE_NETWORK_POLICY
769 // permission above.
770
771 setRestrictBackground(false);
772 }
773 };
774
775 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800776 * Receiver that watches for {@link Notification} control of
777 * {@link NetworkPolicy#lastWarningSnooze}.
778 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700779 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800780 @Override
781 public void onReceive(Context context, Intent intent) {
782 // on background handler thread, and verified MANAGE_NETWORK_POLICY
783 // permission above.
784
785 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
786 performSnooze(template, TYPE_WARNING);
787 }
788 };
789
790 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700791 * Receiver that watches for {@link WifiConfiguration} to be changed.
792 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700793 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700794 @Override
795 public void onReceive(Context context, Intent intent) {
796 // on background handler thread, and verified CONNECTIVITY_INTERNAL
797 // permission above.
798
799 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
800 if (reason == CHANGE_REASON_REMOVED) {
801 final WifiConfiguration config = intent.getParcelableExtra(
802 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700803 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800804 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700805 synchronized (mRulesLock) {
806 if (mNetworkPolicy.containsKey(template)) {
807 mNetworkPolicy.remove(template);
808 writePolicyLocked();
809 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700810 }
811 }
812 }
813 }
814 };
815
816 /**
817 * Receiver that watches {@link WifiInfo} state changes to infer metered
818 * state. Ignores hints when policy is user-defined.
819 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700820 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700821 @Override
822 public void onReceive(Context context, Intent intent) {
823 // on background handler thread, and verified CONNECTIVITY_INTERNAL
824 // permission above.
825
826 // ignore when not connected
827 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
828 if (!netInfo.isConnected()) return;
829
830 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
831 final boolean meteredHint = info.getMeteredHint();
832
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800833 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700834 synchronized (mRulesLock) {
835 NetworkPolicy policy = mNetworkPolicy.get(template);
836 if (policy == null && meteredHint) {
837 // policy doesn't exist, and AP is hinting that it's
838 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800839 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700840 addNetworkPolicyLocked(policy);
841
842 } else if (policy != null && policy.inferred) {
843 // policy exists, and was inferred: update its current
844 // metered state.
845 policy.metered = meteredHint;
846
847 // since this is inferred for each wifi session, just update
848 // rules without persisting.
849 updateNetworkRulesLocked();
850 }
851 }
852 }
853 };
854
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800855 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
856 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
857 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
858 metered, true);
859 }
860
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700861 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700862 * Observer that watches for {@link INetworkManagementService} alerts.
863 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700864 final private INetworkManagementEventObserver mAlertObserver
865 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700866 @Override
867 public void limitReached(String limitName, String iface) {
868 // only someone like NMS should be calling us
869 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
870
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800871 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
872 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700873 }
874 }
875 };
876
877 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
879 * to show visible notifications as needed.
880 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700881 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700882 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
883
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700884 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700885 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700886 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700887
888 // TODO: when switching to kernel notifications, compute next future
889 // cycle boundary to recompute notifications.
890
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700891 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800892 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700893 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
894 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700895 // ignore policies that aren't relevant to user
896 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700897 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700898
Jeff Sharkey497e4432011-06-14 17:27:29 -0700899 final long start = computeLastCycleBoundary(currentTime, policy);
900 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700901 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700903 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800904 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700905 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
906 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700907 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
908 notifyOverLimitLocked(policy.template);
909 }
910
Jeff Sharkey497e4432011-06-14 17:27:29 -0700911 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700912 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700913
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800914 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700915 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700916 }
917 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700918 }
919
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700921 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
922 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700923 if (!mActiveNotifs.contains(tag)) {
924 cancelNotification(tag);
925 }
926 }
927 }
928
929 /**
930 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700931 * current device state, such as when
932 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
933 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700934 */
935 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800936 if (template.isMatchRuleMobile()) {
937 final TelephonyManager tele = TelephonyManager.from(mContext);
938 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700939
Jeff Sharkey32566012014-12-02 18:30:14 -0800940 // Mobile template is relevant when any active subscriber matches
941 final int[] subIds = sub.getActiveSubscriptionIdList();
942 for (int subId : subIds) {
943 final String subscriberId = tele.getSubscriberId(subId);
944 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700945 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800946 if (template.matches(probeIdent)) {
947 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700948 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800949 }
950 return false;
951 } else {
952 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700953 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954 }
955
956 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700957 * Notify that given {@link NetworkTemplate} is over
958 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
959 */
960 private void notifyOverLimitLocked(NetworkTemplate template) {
961 if (!mOverLimitNotified.contains(template)) {
962 mContext.startActivity(buildNetworkOverLimitIntent(template));
963 mOverLimitNotified.add(template);
964 }
965 }
966
967 private void notifyUnderLimitLocked(NetworkTemplate template) {
968 mOverLimitNotified.remove(template);
969 }
970
971 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700972 * Build unique tag that identifies an active {@link NetworkPolicy}
973 * notification of a specific type, like {@link #TYPE_LIMIT}.
974 */
975 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700976 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700977 }
978
979 /**
980 * Show notification for combined {@link NetworkPolicy} and specific type,
981 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
982 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700983 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700984 final String tag = buildNotificationTag(policy, type);
985 final Notification.Builder builder = new Notification.Builder(mContext);
986 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800987 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700988 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200989 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700990
991 final Resources res = mContext.getResources();
992 switch (type) {
993 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700995 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700997 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700998 builder.setTicker(title);
999 builder.setContentTitle(title);
1000 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001001
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001002 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1003 builder.setDeleteIntent(PendingIntent.getBroadcast(
1004 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1005
1006 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001007 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001008 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1009
Jeff Sharkey497e4432011-06-14 17:27:29 -07001010 break;
1011 }
1012 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1014
1015 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001016 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001017 switch (policy.template.getMatchRule()) {
1018 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001021 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001024 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001026 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001027 case MATCH_WIFI:
1028 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001029 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001030 break;
1031 default:
1032 title = null;
1033 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001034 }
1035
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001036 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001037 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 builder.setTicker(title);
1039 builder.setContentTitle(title);
1040 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001041
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1043 builder.setContentIntent(PendingIntent.getActivity(
1044 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1045 break;
1046 }
1047 case TYPE_LIMIT_SNOOZED: {
1048 final long overBytes = totalBytes - policy.limitBytes;
1049 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1050 Formatter.formatFileSize(mContext, overBytes));
1051
1052 final CharSequence title;
1053 switch (policy.template.getMatchRule()) {
1054 case MATCH_MOBILE_3G_LOWER:
1055 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1056 break;
1057 case MATCH_MOBILE_4G:
1058 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1059 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001061 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1062 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 case MATCH_WIFI:
1064 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1065 break;
1066 default:
1067 title = null;
1068 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 }
1070
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001071 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001072 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 builder.setTicker(title);
1074 builder.setContentTitle(title);
1075 builder.setContentText(body);
1076
1077 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001078 builder.setContentIntent(PendingIntent.getActivity(
1079 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001080 break;
1081 }
1082 }
1083
1084 // TODO: move to NotificationManager once we can mock it
1085 try {
1086 final String packageName = mContext.getPackageName();
1087 final int[] idReceived = new int[1];
1088 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001089 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001090 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001091 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001092 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001093 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001094 }
1095 }
1096
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001097 private void cancelNotification(String tag) {
1098 // TODO: move to NotificationManager once we can mock it
1099 try {
1100 final String packageName = mContext.getPackageName();
1101 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001102 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001103 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001104 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001105 }
1106 }
1107
1108 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001109 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001110 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001111 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001112 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001113 @Override
1114 public void onReceive(Context context, Intent intent) {
1115 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1116 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001117
1118 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001119 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001120 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001121 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001123 updateNetworkRulesLocked();
1124 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001125 }
1126 }
1127 };
1128
1129 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001130 * Proactively control network data connections when they exceed
1131 * {@link NetworkPolicy#limitBytes}.
1132 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001133 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001134 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1135
1136 // TODO: reset any policy-disabled networks when any policy is removed
1137 // completely, which is currently rare case.
1138
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001139 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001140 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1141 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001142 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001143 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 setNetworkTemplateEnabled(policy.template, true);
1145 continue;
1146 }
1147
1148 final long start = computeLastCycleBoundary(currentTime, policy);
1149 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151
1152 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001153 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1154 && policy.lastLimitSnooze < start;
1155 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001156
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001157 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001158 }
1159 }
1160
1161 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001162 * Proactively disable networks that match the given
1163 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001164 */
1165 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001166 // TODO: reach into ConnectivityManager to proactively disable bringing
1167 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001168 }
1169
1170 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001171 * Examine all connected {@link NetworkState}, looking for
1172 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1173 * remaining quota based on usage cycle and historical stats.
1174 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001175 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001176 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001177
1178 final NetworkState[] states;
1179 try {
1180 states = mConnManager.getAllNetworkState();
1181 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001182 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001183 return;
1184 }
1185
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001186 // First, generate identities of all connected networks so we can
1187 // quickly compare them against all defined policies below.
1188 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001189 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001190 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001191 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001192 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001193
1194 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001195 if (baseIface != null) {
1196 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001197 }
1198
1199 // Stacked interfaces are considered to have same identity as
1200 // their parent network.
1201 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1202 for (LinkProperties stackedLink : stackedLinks) {
1203 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001204 if (stackedIface != null) {
1205 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001206 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001207 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001208 }
1209 }
1210
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001211 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001212 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001214 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001215 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001216
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001217 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001218 for (int j = connIdents.size() - 1; j >= 0; j--) {
1219 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1220 if (policy.template.matches(ident.second)) {
1221 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001222 }
1223 }
1224
1225 if (ifaceList.size() > 0) {
1226 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001227 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001228 }
1229 }
1230
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001231 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001232 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001233
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001234 // apply each policy that we found ifaces for; compute remaining data
1235 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001236 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001237 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1238 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1239 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001240
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001241 final long start;
1242 final long totalBytes;
1243 if (policy.hasCycle()) {
1244 start = computeLastCycleBoundary(currentTime, policy);
1245 totalBytes = getTotalBytes(policy.template, start, currentTime);
1246 } else {
1247 start = Long.MAX_VALUE;
1248 totalBytes = 0;
1249 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001250
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001252 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 }
1254
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001255 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001256 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001257 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001258 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001259 if (!hasLimit) {
1260 // metered network, but no policy limit; we still need to
1261 // restrict apps, so push really high quota.
1262 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001263 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001264 // snoozing past quota, but we still need to restrict apps,
1265 // so push really high quota.
1266 quotaBytes = Long.MAX_VALUE;
1267 } else {
1268 // remaining "quota" bytes are based on total usage in
1269 // current cycle. kernel doesn't like 0-byte rules, so we
1270 // set 1-byte quota and disable the radio later.
1271 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1272 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001273
1274 if (ifaces.length > 1) {
1275 // TODO: switch to shared quota once NMS supports
1276 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001277 }
1278
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001279 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001280 // long quotaBytes split up into two ints to fit in message
1281 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1282 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1283 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001284 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001285 }
1286 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001287
1288 // keep track of lowest warning or limit of active policies
1289 if (hasWarning && policy.warningBytes < lowestRule) {
1290 lowestRule = policy.warningBytes;
1291 }
1292 if (hasLimit && policy.limitBytes < lowestRule) {
1293 lowestRule = policy.limitBytes;
1294 }
1295 }
1296
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001297 for (int i = connIfaces.size()-1; i >= 0; i--) {
1298 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001299 // long quotaBytes split up into two ints to fit in message
1300 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1301 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1302 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001303 newMeteredIfaces.add(iface);
1304 }
1305
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001306 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001307
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001308 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001309 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1310 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001311 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001312 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1313 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001314 }
1315 }
1316 mMeteredIfaces = newMeteredIfaces;
1317
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001318 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001319 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001320 }
1321
1322 /**
1323 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1324 * have at least a default mobile policy defined.
1325 */
1326 private void ensureActiveMobilePolicyLocked() {
1327 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001328 if (mSuppressDefaultPolicy) return;
1329
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001330 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001331 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001332
Jeff Sharkey32566012014-12-02 18:30:14 -08001333 final int[] subIds = sub.getActiveSubscriptionIdList();
1334 for (int subId : subIds) {
1335 final String subscriberId = tele.getSubscriberId(subId);
1336 ensureActiveMobilePolicyLocked(subscriberId);
1337 }
1338 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001339
Jeff Sharkey32566012014-12-02 18:30:14 -08001340 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1341 // Poke around to see if we already have a policy
1342 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001343 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001344 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1345 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1346 if (template.matches(probeIdent)) {
1347 if (LOGD) {
1348 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1349 + NetworkIdentity.scrubSubscriberId(subscriberId));
1350 }
1351 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001352 }
1353 }
1354
Jeff Sharkey32566012014-12-02 18:30:14 -08001355 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1356 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001357
Jeff Sharkey32566012014-12-02 18:30:14 -08001358 // Build default mobile policy, and assume usage cycle starts today
1359 final long warningBytes = mContext.getResources().getInteger(
1360 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001361
Jeff Sharkey32566012014-12-02 18:30:14 -08001362 final Time time = new Time();
1363 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001364
Jeff Sharkey32566012014-12-02 18:30:14 -08001365 final int cycleDay = time.monthDay;
1366 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001367
Jeff Sharkey32566012014-12-02 18:30:14 -08001368 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1369 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1370 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1371 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001372 }
1373
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001374 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001375 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001376
1377 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001378 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001379 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001380
1381 FileInputStream fis = null;
1382 try {
1383 fis = mPolicyFile.openRead();
1384 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001385 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001386
1387 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001388 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001389 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001390 while ((type = in.next()) != END_DOCUMENT) {
1391 final String tag = in.getName();
1392 if (type == START_TAG) {
1393 if (TAG_POLICY_LIST.equals(tag)) {
1394 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001395 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1396 mRestrictBackground = readBooleanAttribute(
1397 in, ATTR_RESTRICT_BACKGROUND);
1398 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001399 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001400 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001401
1402 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1403 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1404 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001405 final String networkId;
1406 if (version >= VERSION_ADDED_NETWORK_ID) {
1407 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1408 } else {
1409 networkId = null;
1410 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001411 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001412 final String cycleTimezone;
1413 if (version >= VERSION_ADDED_TIMEZONE) {
1414 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1415 } else {
1416 cycleTimezone = Time.TIMEZONE_UTC;
1417 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001418 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1419 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001420 final long lastLimitSnooze;
1421 if (version >= VERSION_SPLIT_SNOOZE) {
1422 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1423 } else if (version >= VERSION_ADDED_SNOOZE) {
1424 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001425 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001426 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001427 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001428 final boolean metered;
1429 if (version >= VERSION_ADDED_METERED) {
1430 metered = readBooleanAttribute(in, ATTR_METERED);
1431 } else {
1432 switch (networkTemplate) {
1433 case MATCH_MOBILE_3G_LOWER:
1434 case MATCH_MOBILE_4G:
1435 case MATCH_MOBILE_ALL:
1436 metered = true;
1437 break;
1438 default:
1439 metered = false;
1440 }
1441 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001442 final long lastWarningSnooze;
1443 if (version >= VERSION_SPLIT_SNOOZE) {
1444 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1445 } else {
1446 lastWarningSnooze = SNOOZE_NEVER;
1447 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001448 final boolean inferred;
1449 if (version >= VERSION_ADDED_INFERRED) {
1450 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1451 } else {
1452 inferred = false;
1453 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1456 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001457 if (template.isPersistable()) {
1458 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1459 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1460 lastLimitSnooze, metered, inferred));
1461 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001462
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001463 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 final int uid = readIntAttribute(in, ATTR_UID);
1465 final int policy = readIntAttribute(in, ATTR_POLICY);
1466
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001467 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001468 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001469 } else {
1470 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1471 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001472 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001473 final int appId = readIntAttribute(in, ATTR_APP_ID);
1474 final int policy = readIntAttribute(in, ATTR_POLICY);
1475
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001476 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001477 // app policy is deprecated so this is only used in pre system user split.
1478 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001479 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001480 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001481 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001482 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001483 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001484 } else if (TAG_WHITELIST.equals(tag)) {
1485 insideWhitelist = true;
1486 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1487 final int uid = readIntAttribute(in, ATTR_UID);
1488 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001489 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1490 final int uid = readIntAttribute(in, ATTR_UID);
1491 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001492 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001493 } else if (type == END_TAG) {
1494 if (TAG_WHITELIST.equals(tag)) {
1495 insideWhitelist = false;
1496 }
1497
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498 }
1499 }
1500
1501 } catch (FileNotFoundException e) {
1502 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001503 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001504 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001505 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001507 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508 } finally {
1509 IoUtils.closeQuietly(fis);
1510 }
1511 }
1512
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001513 /**
1514 * Upgrade legacy background data flags, notifying listeners of one last
1515 * change to always-true.
1516 */
1517 private void upgradeLegacyBackgroundData() {
1518 mRestrictBackground = Settings.Secure.getInt(
1519 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1520
1521 // kick off one last broadcast if restricted
1522 if (mRestrictBackground) {
1523 final Intent broadcast = new Intent(
1524 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001525 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001526 }
1527 }
1528
Dianne Hackborn497175b2014-07-01 12:56:08 -07001529 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001530 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531
1532 FileOutputStream fos = null;
1533 try {
1534 fos = mPolicyFile.startWrite();
1535
1536 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001537 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001538 out.startDocument(null, true);
1539
1540 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001541 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001542 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001543
1544 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001545 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1546 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001547 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001548 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001549
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001550 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001551 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1552 final String subscriberId = template.getSubscriberId();
1553 if (subscriberId != null) {
1554 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001556 final String networkId = template.getNetworkId();
1557 if (networkId != null) {
1558 out.attribute(null, ATTR_NETWORK_ID, networkId);
1559 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001561 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001562 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1563 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001564 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1565 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001566 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001567 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001568 out.endTag(null, TAG_NETWORK_POLICY);
1569 }
1570
1571 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001572 for (int i = 0; i < mUidPolicy.size(); i++) {
1573 final int uid = mUidPolicy.keyAt(i);
1574 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001575
Jeff Sharkey497e4432011-06-14 17:27:29 -07001576 // skip writing empty policies
1577 if (policy == POLICY_NONE) continue;
1578
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001579 out.startTag(null, TAG_UID_POLICY);
1580 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001582 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 }
1584
1585 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001586
1587 // write all whitelists
1588 out.startTag(null, TAG_WHITELIST);
1589
1590 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001591 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001592 for (int i = 0; i < size; i++) {
1593 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1594 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1595 writeIntAttribute(out, ATTR_UID, uid);
1596 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1597 }
1598
Felipe Lemea9505cc2016-02-26 10:28:41 -08001599 // revoked restrict background whitelist
1600 size = mRestrictBackgroundWhitelistRevokedUids.size();
1601 for (int i = 0; i < size; i++) {
1602 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1603 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1604 writeIntAttribute(out, ATTR_UID, uid);
1605 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1606 }
1607
Felipe Lemeb85a6372016-01-14 16:16:16 -08001608 out.endTag(null, TAG_WHITELIST);
1609
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 out.endDocument();
1611
1612 mPolicyFile.finishWrite(fos);
1613 } catch (IOException e) {
1614 if (fos != null) {
1615 mPolicyFile.failWrite(fos);
1616 }
1617 }
1618 }
1619
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001620 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001621 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001622 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001623
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001624 if (!UserHandle.isApp(uid)) {
1625 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001626 }
1627
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001628 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001629 final long token = Binder.clearCallingIdentity();
1630 try {
1631 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1632 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001633 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001634 }
1635 } finally {
1636 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001637 }
1638 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001639 }
1640
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001641 @Override
1642 public void addUidPolicy(int uid, int policy) {
1643 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001644
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001645 if (!UserHandle.isApp(uid)) {
1646 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1647 }
1648
1649 synchronized (mRulesLock) {
1650 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1651 policy |= oldPolicy;
1652 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001653 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001654 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001656 }
1657
1658 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001659 public void removeUidPolicy(int uid, int policy) {
1660 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1661
1662 if (!UserHandle.isApp(uid)) {
1663 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1664 }
1665
1666 synchronized (mRulesLock) {
1667 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1668 policy = oldPolicy & ~policy;
1669 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001670 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001671 }
1672 }
1673 }
1674
Felipe Leme923845f2016-03-02 13:42:48 -08001675 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1676 setUidPolicyUncheckedLocked(uid, policy, persist);
1677
1678 // Checks if app was added or removed to the blacklist.
1679 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1680 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001681 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001682 .sendToTarget();
1683 }
1684 }
1685
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001686 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1687 mUidPolicy.put(uid, policy);
1688
1689 // uid policy changed, recompute rules and persist policy.
Felipe Lemef28983d2016-03-25 12:18:23 -07001690 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001691 if (persist) {
1692 writePolicyLocked();
1693 }
1694 }
1695
1696 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001697 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001698 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1699
Jeff Sharkeya4620792011-05-20 15:29:23 -07001700 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001701 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001702 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001703 }
1704
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001705 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001706 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001707 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1708
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001709 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001710 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001711 for (int i = 0; i < mUidPolicy.size(); i++) {
1712 final int uid = mUidPolicy.keyAt(i);
1713 final int uidPolicy = mUidPolicy.valueAt(i);
1714 if (uidPolicy == policy) {
1715 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001716 }
1717 }
1718 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001719 return uids;
1720 }
1721
1722 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001723 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001724 * if any changes are made.
1725 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001726 void removeUserStateLocked(int userId) {
1727 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1728 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001729
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001730 // Remove entries from restricted background UID whitelist
1731 int[] wlUids = new int[0];
1732 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1733 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1734 if (UserHandle.getUserId(uid) == userId) {
1735 wlUids = appendInt(wlUids, uid);
1736 }
1737 }
1738
1739 if (wlUids.length > 0) {
1740 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001741 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001742 }
1743 writePolicy = true;
1744 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001745 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001746 int[] uids = new int[0];
1747 for (int i = 0; i < mUidPolicy.size(); i++) {
1748 final int uid = mUidPolicy.keyAt(i);
1749 if (UserHandle.getUserId(uid) == userId) {
1750 uids = appendInt(uids, uid);
1751 }
1752 }
1753
1754 if (uids.length > 0) {
1755 for (int uid : uids) {
1756 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001757 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001758 writePolicy = true;
1759 }
1760
Felipe Leme76010a32016-03-17 13:03:11 -07001761 updateRulesForGlobalChangeLocked(true);
1762
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001763 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001764 writePolicyLocked();
1765 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001766 }
1767
1768 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001769 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001770 // TODO: create permission for observing network policy
1771 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1772
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001773 mListeners.register(listener);
1774
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001775 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001776 }
1777
1778 @Override
1779 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001780 // TODO: create permission for observing network policy
1781 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1782
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001783 mListeners.unregister(listener);
1784 }
1785
Jeff Sharkey1b861272011-05-22 00:34:52 -07001786 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001787 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001788 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1789
Felipe Leme6a05eee2016-02-19 14:43:51 -08001790 final long token = Binder.clearCallingIdentity();
1791 try {
1792 maybeRefreshTrustedTime();
1793 synchronized (mRulesLock) {
1794 normalizePoliciesLocked(policies);
1795 updateNetworkEnabledLocked();
1796 updateNetworkRulesLocked();
1797 updateNotificationsLocked();
1798 writePolicyLocked();
1799 }
1800 } finally {
1801 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802 }
1803 }
1804
Dianne Hackborn497175b2014-07-01 12:56:08 -07001805 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001806 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001807 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1808 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001809 }
1810
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001812 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001813 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001814 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001815 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1816 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1817 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001818 } catch (SecurityException e) {
1819 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001820
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001821 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1822 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1823 return new NetworkPolicy[0];
1824 }
Svet Ganov16a16892015-04-16 10:32:04 -07001825 }
1826
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001827 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001828 final int size = mNetworkPolicy.size();
1829 final NetworkPolicy[] policies = new NetworkPolicy[size];
1830 for (int i = 0; i < size; i++) {
1831 policies[i] = mNetworkPolicy.valueAt(i);
1832 }
1833 return policies;
1834 }
1835 }
1836
1837 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001838 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001839 }
1840
1841 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1842 final TelephonyManager tele = TelephonyManager.from(mContext);
1843 final String[] merged = tele.getMergedSubscriberIds();
1844
1845 mNetworkPolicy.clear();
1846 for (NetworkPolicy policy : policies) {
1847 // When two normalized templates conflict, prefer the most
1848 // restrictive policy
1849 policy.template = NetworkTemplate.normalize(policy.template, merged);
1850 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1851 if (existing == null || existing.compareTo(policy) > 0) {
1852 if (existing != null) {
1853 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1854 }
1855 mNetworkPolicy.put(policy.template, policy);
1856 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001857 }
1858 }
1859
1860 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001861 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001862 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001863
1864 final long token = Binder.clearCallingIdentity();
1865 try {
1866 performSnooze(template, TYPE_LIMIT);
1867 } finally {
1868 Binder.restoreCallingIdentity(token);
1869 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001870 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001871
Dianne Hackborn497175b2014-07-01 12:56:08 -07001872 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001873 maybeRefreshTrustedTime();
1874 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001875 synchronized (mRulesLock) {
1876 // find and snooze local policy that matches
1877 final NetworkPolicy policy = mNetworkPolicy.get(template);
1878 if (policy == null) {
1879 throw new IllegalArgumentException("unable to find policy for " + template);
1880 }
1881
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001882 switch (type) {
1883 case TYPE_WARNING:
1884 policy.lastWarningSnooze = currentTime;
1885 break;
1886 case TYPE_LIMIT:
1887 policy.lastLimitSnooze = currentTime;
1888 break;
1889 default:
1890 throw new IllegalArgumentException("unexpected type");
1891 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001892
Jeff Sharkey32566012014-12-02 18:30:14 -08001893 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001894 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001895 updateNetworkRulesLocked();
1896 updateNotificationsLocked();
1897 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001898 }
1899 }
1900
1901 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001902 public void onTetheringChanged(String iface, boolean tethering) {
1903 // No need to enforce permission because setRestrictBackground() will do it.
1904 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1905 synchronized (mRulesLock) {
1906 if (mRestrictBackground && tethering) {
1907 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1908 setRestrictBackground(false);
1909 }
1910 }
1911 }
1912
1913 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001914 public void setRestrictBackground(boolean restrictBackground) {
1915 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001916 final long token = Binder.clearCallingIdentity();
1917 try {
1918 maybeRefreshTrustedTime();
1919 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001920 if (restrictBackground == mRestrictBackground) {
1921 // Ideally, UI should never allow this scenario...
1922 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1923 return;
1924 }
1925 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001926 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001927
Felipe Leme6a05eee2016-02-19 14:43:51 -08001928 } finally {
1929 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001930 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001931
1932 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1933 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001934 }
1935
Felipe Leme70c57c22016-03-29 10:45:13 -07001936 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1937 final boolean oldRestrictBackground = mRestrictBackground;
1938 mRestrictBackground = restrictBackground;
1939 // Must whitelist foreground apps before turning data saver mode on.
1940 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1941 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
1942 updateRulesForRestrictBackgroundLocked();
1943 try {
1944 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
1945 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
1946 mRestrictBackground = oldRestrictBackground;
1947 // TODO: if it knew the foreground apps (see TODO above), it could call
1948 // updateRulesForRestrictBackgroundLocked() again to restore state.
1949 return;
1950 }
1951 } catch (RemoteException e) {
1952 // ignored; service lives in system_server
1953 }
1954 updateNotificationsLocked();
1955 writePolicyLocked();
1956 }
1957
Jeff Sharkey46645002011-07-27 21:11:21 -07001958 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001959 public void addRestrictBackgroundWhitelistedUid(int uid) {
1960 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07001961 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07001962 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001963 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001964 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08001965 if (oldStatus) {
1966 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
1967 return;
1968 }
Felipe Leme01e05e72016-03-31 10:09:24 -07001969 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08001970 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08001971 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001972 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
1973 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1974 if (LOGD) Slog.d(TAG, "Removing uid " + uid
1975 + " from revoked restrict background whitelist");
1976 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
1977 }
Felipe Leme01e05e72016-03-31 10:09:24 -07001978 if (needFirewallRules) {
1979 // Only update firewall rules if necessary...
1980 updateRuleForRestrictBackgroundLocked(uid);
1981 }
1982 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08001983 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001984 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001985 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
1986 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
1987 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001988 }
1989
1990 @Override
1991 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1992 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001993 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001994 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001995 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001996 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001997 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
1998 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001999 }
2000
Felipe Leme70c57c22016-03-29 10:45:13 -07002001 /**
2002 * Removes a uid from the restricted background whitelist, returning whether its current
2003 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2004 */
2005 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2006 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002007 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
2008 if (!oldStatus) {
2009 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2010 return false;
2011 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002012 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002013 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002014 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002015 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2016 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2017 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2018 + " to revoked restrict background whitelist");
2019 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2020 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002021 if (needFirewallRules) {
2022 // Only update firewall rules if necessary...
2023 updateRuleForRestrictBackgroundLocked(uid, uidDeleted);
2024 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002025 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002026 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002027 writePolicyLocked();
2028 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002029 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2030 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002031 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002032 }
2033
2034 @Override
2035 public int[] getRestrictBackgroundWhitelistedUids() {
2036 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2037 synchronized (mRulesLock) {
2038 final int size = mRestrictBackgroundWhitelistUids.size();
2039 final int[] whitelist = new int[size];
2040 for (int i = 0; i < size; i++) {
2041 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2042 }
2043 if (LOGV) {
2044 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2045 + mRestrictBackgroundWhitelistUids);
2046 }
2047 return whitelist;
2048 }
2049 }
2050
2051 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002052 public int getRestrictBackgroundByCaller() {
2053 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2054 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002055
Felipe Leme1b103232016-01-22 09:44:57 -08002056 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002057 // Must clear identity because getUidPolicy() is restricted to system.
2058 final long token = Binder.clearCallingIdentity();
2059 final int policy;
2060 try {
2061 policy = getUidPolicy(uid);
2062 } finally {
2063 Binder.restoreCallingIdentity(token);
2064 }
2065 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2066 // App is blacklisted.
2067 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2068 }
Felipe Leme1b103232016-01-22 09:44:57 -08002069 if (!mRestrictBackground) {
2070 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2071 }
2072 return mRestrictBackgroundWhitelistUids.get(uid)
2073 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2074 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2075 }
2076 }
2077
2078 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002079 public boolean getRestrictBackground() {
2080 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2081
2082 synchronized (mRulesLock) {
2083 return mRestrictBackground;
2084 }
2085 }
2086
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002087 @Override
2088 public void setDeviceIdleMode(boolean enabled) {
2089 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2090
2091 synchronized (mRulesLock) {
2092 if (mDeviceIdleMode != enabled) {
2093 mDeviceIdleMode = enabled;
2094 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002095 // Device idle change means we need to rebuild rules for all
2096 // known apps, so do a global refresh.
2097 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002098 }
2099 if (enabled) {
2100 EventLogTags.writeDeviceIdleOnPhase("net");
2101 } else {
2102 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002103 }
2104 }
2105 }
2106 }
2107
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002108 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002109 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2110 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002111 if (policy.template.matches(ident)) {
2112 return policy;
2113 }
2114 }
2115 return null;
2116 }
2117
2118 @Override
2119 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2120 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2121
2122 // only returns usage summary, so we don't require caller to have
2123 // READ_NETWORK_USAGE_HISTORY.
2124 final long token = Binder.clearCallingIdentity();
2125 try {
2126 return getNetworkQuotaInfoUnchecked(state);
2127 } finally {
2128 Binder.restoreCallingIdentity(token);
2129 }
2130 }
2131
2132 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2133 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2134
2135 final NetworkPolicy policy;
2136 synchronized (mRulesLock) {
2137 policy = findPolicyForNetworkLocked(ident);
2138 }
2139
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002140 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002141 // missing policy means we can't derive useful quota info
2142 return null;
2143 }
2144
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002145 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002146
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002147 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002148 final long start = computeLastCycleBoundary(currentTime, policy);
2149 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002150 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002151
2152 // report soft and hard limits under policy
2153 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2154 : NetworkQuotaInfo.NO_LIMIT;
2155 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2156 : NetworkQuotaInfo.NO_LIMIT;
2157
2158 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2159 }
2160
Jeff Sharkey46645002011-07-27 21:11:21 -07002161 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002162 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002163 if (state.networkInfo == null) {
2164 return false;
2165 }
2166
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002167 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2168
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002169 // roaming networks are always considered metered
2170 if (ident.getRoaming()) {
2171 return true;
2172 }
2173
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002174 final NetworkPolicy policy;
2175 synchronized (mRulesLock) {
2176 policy = findPolicyForNetworkLocked(ident);
2177 }
2178
2179 if (policy != null) {
2180 return policy.metered;
2181 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002182 final int type = state.networkInfo.getType();
2183 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2184 return true;
2185 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002186 return false;
2187 }
2188 }
2189
2190 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002191 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002192 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002193
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002194 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2195
Dianne Hackborn497175b2014-07-01 12:56:08 -07002196 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002197 for (String arg : args) {
2198 argSet.add(arg);
2199 }
2200
Jeff Sharkey1b861272011-05-22 00:34:52 -07002201 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002202 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002203 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2204 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002205 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002206
Jeff Sharkey32566012014-12-02 18:30:14 -08002207 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002208 updateNetworkEnabledLocked();
2209 updateNetworkRulesLocked();
2210 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002211 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002212
2213 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002214 return;
2215 }
2216
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002217 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002218 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002219 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002220 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002221 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002222 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002223 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2224 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002225 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002226 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002227
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002228 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2229
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002230 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002231 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002232 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002233 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002234 final int uid = mUidPolicy.keyAt(i);
2235 final int policy = mUidPolicy.valueAt(i);
2236 fout.print("UID=");
2237 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002238 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002239 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002240 fout.println();
2241 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002242 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002243
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002244 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2245 if (size > 0) {
2246 fout.println("Power save whitelist (except idle) app ids:");
2247 fout.increaseIndent();
2248 for (int i = 0; i < size; i++) {
2249 fout.print("UID=");
2250 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2251 fout.print(": ");
2252 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2253 fout.println();
2254 }
2255 fout.decreaseIndent();
2256 }
2257
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002258 size = mPowerSaveWhitelistAppIds.size();
2259 if (size > 0) {
2260 fout.println("Power save whitelist app ids:");
2261 fout.increaseIndent();
2262 for (int i = 0; i < size; i++) {
2263 fout.print("UID=");
2264 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2265 fout.print(": ");
2266 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2267 fout.println();
2268 }
2269 fout.decreaseIndent();
2270 }
2271
Felipe Lemeb85a6372016-01-14 16:16:16 -08002272 size = mRestrictBackgroundWhitelistUids.size();
2273 if (size > 0) {
2274 fout.println("Restrict background whitelist uids:");
2275 fout.increaseIndent();
2276 for (int i = 0; i < size; i++) {
2277 fout.print("UID=");
2278 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2279 fout.println();
2280 }
2281 fout.decreaseIndent();
2282 }
2283
Felipe Lemea9505cc2016-02-26 10:28:41 -08002284 size = mDefaultRestrictBackgroundWhitelistUids.size();
2285 if (size > 0) {
2286 fout.println("Default restrict background whitelist uids:");
2287 fout.increaseIndent();
2288 for (int i = 0; i < size; i++) {
2289 fout.print("UID=");
2290 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2291 fout.println();
2292 }
2293 fout.decreaseIndent();
2294 }
2295
2296 size = mRestrictBackgroundWhitelistRevokedUids.size();
2297 if (size > 0) {
2298 fout.println("Default restrict background whitelist uids revoked by users:");
2299 fout.increaseIndent();
2300 for (int i = 0; i < size; i++) {
2301 fout.print("UID=");
2302 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2303 fout.println();
2304 }
2305 fout.decreaseIndent();
2306 }
2307
Jeff Sharkey1b861272011-05-22 00:34:52 -07002308 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002309 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002310 collectKeys(mUidRules, knownUids);
2311
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002312 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002313 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002314 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002315 for (int i = 0; i < size; i++) {
2316 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002317 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002318 fout.print(uid);
2319
Jeff Sharkeydc988062015-09-14 10:09:47 -07002320 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002321 fout.print(" state=");
2322 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002323 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2324 fout.print(" (fg)");
2325 } else {
2326 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2327 ? " (fg svc)" : " (bg)");
2328 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002329
Jeff Sharkeydc988062015-09-14 10:09:47 -07002330 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2331 fout.print(" rule=");
Felipe Lemef28983d2016-03-25 12:18:23 -07002332 fout.print(ruleToString(rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002333
2334 fout.println();
2335 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002336 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002337 }
2338 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002339
Felipe Lemef28983d2016-03-25 12:18:23 -07002340 private String ruleToString(int rule) {
2341 return DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule);
2342 }
2343
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002344 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002345 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2346 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002347 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002348 this, in, out, err, args, resultReceiver);
2349 }
2350
2351 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002352 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002353 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2354
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002355 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002356 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002357 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002358 }
2359
Felipe Lemef28983d2016-03-25 12:18:23 -07002360 private boolean isUidForegroundLocked(int uid) {
2361 return isUidStateForegroundLocked(
2362 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2363 }
2364
Felipe Lemeef89c902016-03-30 15:11:31 -07002365 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2366 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2367 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2368 }
2369
Felipe Lemef28983d2016-03-25 12:18:23 -07002370 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002371 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002372 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002373 }
2374
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002375 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002376 * Process state of UID changed; if needed, will trigger
Felipe Leme70c57c22016-03-29 10:45:13 -07002377 * {@link #updateRuleForRestrictBackgroundLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002378 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002379 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002380 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2381 if (oldUidState != uidState) {
2382 // state changed, push updated rules
2383 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002384 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002385 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2386 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2387 if (mDeviceIdleMode) {
2388 updateRuleForDeviceIdleLocked(uid);
2389 }
2390 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002391 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002392 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002393 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002394 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002395 }
2396 }
2397
Felipe Lemef28983d2016-03-25 12:18:23 -07002398 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002399 final int index = mUidState.indexOfKey(uid);
2400 if (index >= 0) {
2401 final int oldUidState = mUidState.valueAt(index);
2402 mUidState.removeAt(index);
2403 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002404 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002405 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002406 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002407 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002408 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002409 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002410 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002411 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002412 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002413 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002414 }
2415 }
2416
Felipe Lemef28983d2016-03-25 12:18:23 -07002417 // adjust stats accounting based on foreground status
2418 private void updateNetworkStats(int uid, boolean uidForeground) {
2419 try {
2420 mNetworkStats.setUidForeground(uid, uidForeground);
2421 } catch (RemoteException e) {
2422 // ignored; service lives in system_server
2423 }
2424 }
2425
2426 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2427 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002428 final boolean oldForeground =
2429 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2430 final boolean newForeground =
2431 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002432 if (oldForeground != newForeground) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002433 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002434 }
2435 }
2436
Jeff Sharkeya4620792011-05-20 15:29:23 -07002437 private void updateScreenOn() {
2438 synchronized (mRulesLock) {
2439 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002440 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002441 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002442 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002443 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002444 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002445 }
2446 }
2447
2448 /**
2449 * Update rules that might be changed by {@link #mScreenOn} value.
2450 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002451 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002452 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002453 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002454 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002455 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002456 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002457 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002458 }
2459 }
2460 }
2461
Felipe Leme011b98f2016-02-10 17:28:31 -08002462 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002463 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2464 }
2465
Felipe Lemeef89c902016-03-30 15:11:31 -07002466 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2467 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2468 }
2469
Felipe Leme011b98f2016-02-10 17:28:31 -08002470 void updateRulesForRestrictPowerLocked() {
2471 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2472 mUidFirewallPowerSaveRules);
2473 }
2474
Felipe Lemef28983d2016-03-25 12:18:23 -07002475 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002476 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2477 }
2478
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002479 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002480 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2481 mUidFirewallDozableRules);
2482 }
2483
2484 void updateRuleForDeviceIdleLocked(int uid) {
2485 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2486 }
2487
Felipe Lemef28983d2016-03-25 12:18:23 -07002488 // NOTE: since both fw_dozable and fw_powersave uses the same map
2489 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002490 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2491 SparseIntArray rules) {
2492 if (enabled) {
2493 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002494 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002495 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002496 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002497 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002498 for (int ui = users.size() - 1; ui >= 0; ui--) {
2499 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002500 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002501 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2502 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2503 int uid = UserHandle.getUid(user.id, appId);
2504 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2505 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002506 }
2507 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2508 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2509 int uid = UserHandle.getUid(user.id, appId);
2510 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2511 }
2512 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002513 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002514 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002515 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2516 }
2517 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002518 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002519 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002520
Felipe Leme011b98f2016-02-10 17:28:31 -08002521 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002522 }
2523
Felipe Lemef28983d2016-03-25 12:18:23 -07002524 // NOTE: since both fw_dozable and fw_powersave uses the same map
2525 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002526 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2527 if (enabled) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002528 int appId = UserHandle.getAppId(uid);
2529 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
Felipe Leme011b98f2016-02-10 17:28:31 -08002530 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2531 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002532 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002533 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002534 }
2535 }
2536 }
2537
2538 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002539 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2540 uidRules.clear();
2541
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002542 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002543 final List<UserInfo> users = mUserManager.getUsers();
2544 for (int ui = users.size() - 1; ui >= 0; ui--) {
2545 UserInfo user = users.get(ui);
2546 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2547 for (int uid : idleUids) {
2548 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002549 // quick check: if this uid doesn't have INTERNET permission, it
2550 // doesn't have network access anyway, so it is a waste to mess
2551 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002552 if (hasInternetPermissions(uid)) {
2553 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002554 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002555 }
2556 }
2557 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002558
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002559 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2560 }
2561
2562 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002563 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002564
2565 int appId = UserHandle.getAppId(uid);
2566 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2567 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2568 } else {
2569 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2570 }
2571 }
2572
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002573 void updateRulesForAppIdleParoleLocked() {
2574 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2575 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002576 }
2577
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002578 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002579 * Update rules that might be changed by {@link #mRestrictBackground},
2580 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002581 */
Felipe Leme76010a32016-03-17 13:03:11 -07002582 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002583 long start;
2584 if (LOGD) start = System.currentTimeMillis();
2585
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002586 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002587 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002588 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002589 updateRulesForRestrictBackgroundLocked();
Felipe Leme70c57c22016-03-29 10:45:13 -07002590 setRestrictBackgroundLocked(mRestrictBackground);
Felipe Leme76010a32016-03-17 13:03:11 -07002591
2592 // If the set of restricted networks may have changed, re-evaluate those.
2593 if (restrictedNetworksChanged) {
2594 normalizePoliciesLocked();
2595 updateNetworkRulesLocked();
2596 }
2597 if (LOGD) {
2598 final long delta = System.currentTimeMillis() - start;
2599 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2600 + delta + "ms");
2601 }
2602 }
2603
Felipe Lemef28983d2016-03-25 12:18:23 -07002604 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002605 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002606
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002607 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002608 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002609 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002610 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2611 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2612 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002613
Felipe Leme03e689d2016-03-02 16:17:38 -08002614 final int usersSize = users.size();
2615 final int appsSize = apps.size();
2616 for (int i = 0; i < usersSize; i++) {
2617 final UserInfo user = users.get(i);
2618 for (int j = 0; j < appsSize; j++) {
2619 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002620 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002621 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002622 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002623 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002624 }
2625
Felipe Leme76010a32016-03-17 13:03:11 -07002626 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002627 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002628 for (int i = 0; i < users.size(); i++) {
2629 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002630 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002631 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002632 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002633 updateRuleForAppIdleLocked(uid);
2634 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002635 updateRuleForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002636 }
2637 }
2638 }
2639
Felipe Leme70c57c22016-03-29 10:45:13 -07002640 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2641 // methods below could be merged into a isUidValidForRules() method.
2642 private boolean isUidValidForBlacklistRules(int uid) {
2643 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002644 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002645 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002646 return true;
2647 }
2648
2649 return false;
2650 }
2651
Felipe Leme70c57c22016-03-29 10:45:13 -07002652 private boolean isUidValidForWhitelistRules(int uid) {
2653 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2654 }
2655
Amith Yamasani15e472352015-04-24 19:06:07 -07002656 private boolean isUidIdle(int uid) {
2657 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2658 final int userId = UserHandle.getUserId(uid);
2659
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002660 if (!ArrayUtils.isEmpty(packages)) {
2661 for (String packageName : packages) {
2662 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2663 return false;
2664 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002665 }
2666 }
2667 return true;
2668 }
2669
2670 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002671 * Checks if an uid has INTERNET permissions.
2672 * <p>
2673 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002674 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002675 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002676 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002677 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002678 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002679 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002680 }
2681 } catch (RemoteException e) {
2682 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002683 return true;
2684 }
2685
2686 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002687 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002688 *
Felipe Lemef28983d2016-03-25 12:18:23 -07002689 * <p>There are currently 2 types of restriction rules:
2690 * <ul>
2691 * <li>Battery Saver Mode (also referred as power save).
2692 * <li>Data Saver Mode (formerly known as restrict background data).
2693 * </ul>
Felipe Leme47585ba2016-02-09 16:56:32 -08002694 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002695 private void updateRestrictionRulesForUidLocked(int uid) {
2696 updateRuleForRestrictPowerLocked(uid);
2697 updateRuleForRestrictBackgroundLocked(uid);
2698 }
2699
Felipe Leme70c57c22016-03-29 10:45:13 -07002700 /**
2701 * Applies network rules to bandwidth controllers based on process state and user-defined
2702 * restrictions (blacklist / whitelist).
2703 *
2704 * <p>
2705 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2706 * networks:
2707 * <ul>
2708 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2709 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2710 * also blacklisted.
2711 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2712 * no UIDs other those whitelisted will have access.
2713 * <ul>
2714 *
2715 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2716 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2717 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2718 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
2719 * this ({@link #updateRuleForRestrictBackgroundLocked(int)}) to propagate the rules to
2720 * {@link INetworkManagementService}, but this method should also be called in events (like
2721 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2722 * following rules should also be applied:
2723 *
2724 * <ul>
2725 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2726 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2727 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2728 * {@code bw_penalty_box}.
2729 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2730 * </ul>
2731 *
2732 * <p>For optimization, the rules are only applied on user apps that have internet access
2733 * permission, since there is no need to change the {@code iptables} rule if the app does not
2734 * have permission to use the internet.
2735 *
2736 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
2737 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002738 private void updateRuleForRestrictBackgroundLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002739 updateRuleForRestrictBackgroundLocked(uid, false);
2740 }
2741
2742 /**
2743 * Overloaded version of {@link #updateRuleForRestrictBackgroundLocked(int)} called when an
2744 * app is removed - it ignores the UID validity check.
2745 */
2746 private void updateRuleForRestrictBackgroundLocked(int uid, boolean uidDeleted) {
2747 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2748 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2749 return;
2750 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002751
Dianne Hackborn497175b2014-07-01 12:56:08 -07002752 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002753 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Felipe Leme70c57c22016-03-29 10:45:13 -07002754 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2755 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002756
Felipe Leme76010a32016-03-17 13:03:11 -07002757 int newRule = RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -07002758 final int oldRule = mUidRules.get(uid);
Felipe Leme76010a32016-03-17 13:03:11 -07002759
Felipe Leme70c57c22016-03-29 10:45:13 -07002760 // First step: define the new rule based on user restrictions and foreground state.
2761 if (isForeground) {
2762 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2763 newRule = RULE_TEMPORARY_ALLOW_METERED;
2764 }
2765 } else {
2766 if (isBlacklisted) {
Felipe Leme76010a32016-03-17 13:03:11 -07002767 newRule = RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -07002768 } else if (isWhitelisted) {
2769 newRule = RULE_ALLOW_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002770 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002771 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002772
Felipe Lemef28983d2016-03-25 12:18:23 -07002773 if (LOGV) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002774 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + "):"
2775 + " isForeground=" +isForeground + ", isBlacklisted: " + isBlacklisted
2776 + ", isWhitelisted: " + isWhitelisted + ", newRule: " + ruleToString(newRule)
2777 + ", oldRule: " + ruleToString(oldRule));
Felipe Lemef28983d2016-03-25 12:18:23 -07002778 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002779
Felipe Leme70c57c22016-03-29 10:45:13 -07002780
Felipe Leme76010a32016-03-17 13:03:11 -07002781 if (newRule == RULE_ALLOW_ALL) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002782 mUidRules.delete(uid);
2783 } else {
Felipe Leme76010a32016-03-17 13:03:11 -07002784 mUidRules.put(uid, newRule);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002785 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002786
Felipe Leme70c57c22016-03-29 10:45:13 -07002787 // Second step: apply bw changes based on change of state.
2788 if (newRule != oldRule) {
2789 if (newRule == RULE_TEMPORARY_ALLOW_METERED) {
2790 // Temporarily whitelist foreground app, removing from blacklist if necessary
2791 // (since bw_penalty_box prevails over bw_happy_box).
2792
2793 setMeteredNetworkWhitelist(uid, true);
2794 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2795 // but ideally it should be just:
2796 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2797 if (isBlacklisted) {
2798 setMeteredNetworkBlacklist(uid, false);
2799 }
2800 } else if (oldRule == RULE_TEMPORARY_ALLOW_METERED) {
2801 // Remove temporary whitelist from app that is not on foreground anymore.
2802
2803 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2804 // but ideally they should be just:
2805 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2806 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2807 if (!isWhitelisted) {
2808 setMeteredNetworkWhitelist(uid, false);
2809 }
2810 if (isBlacklisted) {
2811 setMeteredNetworkBlacklist(uid, true);
2812 }
2813 } else if (newRule == RULE_REJECT_METERED || oldRule == RULE_REJECT_METERED) {
2814 // Flip state because app was explicitly added or removed to blacklist.
2815 setMeteredNetworkBlacklist(uid, isBlacklisted);
2816 if (oldRule == RULE_REJECT_METERED && isWhitelisted) {
2817 // Since blacklist prevails over whitelist, we need to handle the special case
2818 // where app is whitelisted and blacklisted at the same time (although such
2819 // scenario should be blocked by the UI), then blacklist is removed.
2820 setMeteredNetworkWhitelist(uid, isWhitelisted);
2821 }
2822 } else if (newRule == RULE_ALLOW_METERED || oldRule == RULE_ALLOW_METERED) {
2823 // Flip state because app was explicitly added or removed to whitelist.
2824 setMeteredNetworkWhitelist(uid, isWhitelisted);
2825 } else {
2826 // All scenarios should have been covered above
2827 Log.wtf(TAG, "Unexpected change of state for " + uid
2828 + ": foreground=" + isForeground + ", whitelisted=" + isWhitelisted
2829 + ", blacklisted=" + isBlacklisted + ", newRule="
2830 + ruleToString(newRule) + ", oldRule=" + ruleToString(oldRule));
2831 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002832
2833 // dispatch changed rule to existing listeners
Felipe Leme76010a32016-03-17 13:03:11 -07002834 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newRule).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002835 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002836 }
2837
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002838 private class AppIdleStateChangeListener
2839 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2840
2841 @Override
2842 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2843 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002844 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2845 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002846 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002847 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002848 }
2849 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002850 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002851 }
2852
2853 @Override
2854 public void onParoleStateChanged(boolean isParoleOn) {
2855 synchronized (mRulesLock) {
2856 updateRulesForAppIdleParoleLocked();
2857 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002858 }
2859 }
2860
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002861 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002862 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002863 public boolean handleMessage(Message msg) {
2864 switch (msg.what) {
2865 case MSG_RULES_CHANGED: {
2866 final int uid = msg.arg1;
2867 final int uidRules = msg.arg2;
2868 final int length = mListeners.beginBroadcast();
2869 for (int i = 0; i < length; i++) {
2870 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2871 if (listener != null) {
2872 try {
2873 listener.onUidRulesChanged(uid, uidRules);
2874 } catch (RemoteException e) {
2875 }
2876 }
2877 }
2878 mListeners.finishBroadcast();
2879 return true;
2880 }
2881 case MSG_METERED_IFACES_CHANGED: {
2882 final String[] meteredIfaces = (String[]) msg.obj;
2883 final int length = mListeners.beginBroadcast();
2884 for (int i = 0; i < length; i++) {
2885 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2886 if (listener != null) {
2887 try {
2888 listener.onMeteredIfacesChanged(meteredIfaces);
2889 } catch (RemoteException e) {
2890 }
2891 }
2892 }
2893 mListeners.finishBroadcast();
2894 return true;
2895 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002896 case MSG_LIMIT_REACHED: {
2897 final String iface = (String) msg.obj;
2898
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002899 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002900 synchronized (mRulesLock) {
2901 if (mMeteredIfaces.contains(iface)) {
2902 try {
2903 // force stats update to make sure we have
2904 // numbers that caused alert to trigger.
2905 mNetworkStats.forceUpdate();
2906 } catch (RemoteException e) {
2907 // ignored; service lives in system_server
2908 }
2909
2910 updateNetworkEnabledLocked();
2911 updateNotificationsLocked();
2912 }
2913 }
2914 return true;
2915 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002916 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2917 final boolean restrictBackground = msg.arg1 != 0;
2918 final int length = mListeners.beginBroadcast();
2919 for (int i = 0; i < length; i++) {
2920 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2921 if (listener != null) {
2922 try {
2923 listener.onRestrictBackgroundChanged(restrictBackground);
2924 } catch (RemoteException e) {
2925 }
2926 }
2927 }
2928 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002929 final Intent intent =
2930 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2931 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2932 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2933 return true;
2934 }
2935 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07002936 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
2937 // - when an app is whitelisted
2938 // - when an app is blacklisted
2939 //
2940 // Whether the internal listeners (INetworkPolicyListener implementations) or
2941 // app broadcast receivers are notified depend on the following rules:
2942 //
2943 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
2944 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
2945 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08002946 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07002947 final boolean changed = msg.arg2 == 1;
2948 final Boolean whitelisted = (Boolean) msg.obj;
2949
2950 if (whitelisted != null) {
2951 final int length = mListeners.beginBroadcast();
2952 for (int i = 0; i < length; i++) {
2953 // First notify internal listeners...
2954 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2955 if (listener != null) {
2956 try {
2957 listener.onRestrictBackgroundWhitelistChanged(uid,
2958 whitelisted.booleanValue());
2959 } catch (RemoteException e) {
2960 }
2961 }
2962 }
2963 mListeners.finishBroadcast();
2964 }
2965
Felipe Leme9778f762016-01-27 14:46:39 -08002966 final PackageManager pm = mContext.getPackageManager();
2967 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07002968 if (changed && packages != null) {
2969 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08002970 final int userId = UserHandle.getUserId(uid);
2971 for (String packageName : packages) {
2972 final Intent intent = new Intent(
2973 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2974 intent.setPackage(packageName);
2975 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2976 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2977 }
Felipe Leme9778f762016-01-27 14:46:39 -08002978 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002979 return true;
2980 }
2981 case MSG_ADVISE_PERSIST_THRESHOLD: {
2982 final long lowestRule = (Long) msg.obj;
2983 try {
2984 // make sure stats are recorded frequently enough; we aim
2985 // for 2MB threshold for 2GB/month rules.
2986 final long persistThreshold = lowestRule / 1000;
2987 mNetworkStats.advisePersistThreshold(persistThreshold);
2988 } catch (RemoteException e) {
2989 // ignored; service lives in system_server
2990 }
2991 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002992 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002993 case MSG_SCREEN_ON_CHANGED: {
2994 updateScreenOn();
2995 return true;
2996 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07002997 case MSG_UPDATE_INTERFACE_QUOTA: {
2998 removeInterfaceQuota((String) msg.obj);
2999 // int params need to be stitched back into a long
3000 setInterfaceQuota((String) msg.obj,
3001 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3002 return true;
3003 }
3004 case MSG_REMOVE_INTERFACE_QUOTA: {
3005 removeInterfaceQuota((String) msg.obj);
3006 return true;
3007 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003008 default: {
3009 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003010 }
3011 }
3012 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003013 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003014
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003015 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003016 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003017 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003018 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003019 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003020 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003021 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003022 }
3023 }
3024
3025 private void removeInterfaceQuota(String iface) {
3026 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003027 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003028 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003029 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003030 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003031 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003032 }
3033 }
3034
Felipe Leme70c57c22016-03-29 10:45:13 -07003035 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3036 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003037 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003038 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003039 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003040 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3041 } catch (RemoteException e) {
3042 // ignored; service lives in system_server
3043 }
3044 }
3045
3046 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3047 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3048 try {
3049 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3050 } catch (IllegalStateException e) {
3051 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003052 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003053 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003054 }
3055 }
3056
Amith Yamasani15e472352015-04-24 19:06:07 -07003057 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003058 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3059 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3060 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003061 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003062 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003063 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003064 int size = uidRules.size();
3065 int[] uids = new int[size];
3066 int[] rules = new int[size];
3067 for(int index = size - 1; index >= 0; --index) {
3068 uids[index] = uidRules.keyAt(index);
3069 rules[index] = uidRules.valueAt(index);
3070 }
3071 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003072 } catch (IllegalStateException e) {
3073 Log.wtf(TAG, "problem setting firewall uid rules", e);
3074 } catch (RemoteException e) {
3075 // ignored; service lives in system_server
3076 }
3077 }
3078
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003079 /**
3080 * Add or remove a uid to the firewall blacklist for all network ifaces.
3081 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003082 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003083 if (chain == FIREWALL_CHAIN_DOZABLE) {
3084 mUidFirewallDozableRules.put(uid, rule);
3085 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3086 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003087 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3088 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003089 }
3090
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003091 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003092 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003093 } catch (IllegalStateException e) {
3094 Log.wtf(TAG, "problem setting firewall uid rules", e);
3095 } catch (RemoteException e) {
3096 // ignored; service lives in system_server
3097 }
3098 }
3099
3100 /**
3101 * Add or remove a uid to the firewall blacklist for all network ifaces.
3102 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003103 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003104 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3105 mFirewallChainStates.get(chain) == enable) {
3106 // All is the same, nothing to do.
3107 return;
3108 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003109 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003110 try {
3111 mNetworkManager.setFirewallChainEnabled(chain, enable);
3112 } catch (IllegalStateException e) {
3113 Log.wtf(TAG, "problem enable firewall chain", e);
3114 } catch (RemoteException e) {
3115 // ignored; service lives in system_server
3116 }
3117 }
3118
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003119 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3120 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003121 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003122 } catch (RuntimeException e) {
3123 Slog.w(TAG, "problem reading network stats: " + e);
3124 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003125 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003126 // ignored; service lives in system_server
3127 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003128 }
3129 }
3130
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003131 private boolean isBandwidthControlEnabled() {
3132 final long token = Binder.clearCallingIdentity();
3133 try {
3134 return mNetworkManager.isBandwidthControlEnabled();
3135 } catch (RemoteException e) {
3136 // ignored; service lives in system_server
3137 return false;
3138 } finally {
3139 Binder.restoreCallingIdentity(token);
3140 }
3141 }
3142
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003143 /**
3144 * Try refreshing {@link #mTime} when stale.
3145 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003146 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003147 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003148 mTime.forceRefresh();
3149 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003150 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003151
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003152 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003153 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3154 }
3155
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003156 private static Intent buildAllowBackgroundDataIntent() {
3157 return new Intent(ACTION_ALLOW_BACKGROUND);
3158 }
3159
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003160 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3161 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3162 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3163 return intent;
3164 }
3165
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003166 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3167 final Intent intent = new Intent();
3168 intent.setComponent(new ComponentName(
3169 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3170 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3171 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3172 return intent;
3173 }
3174
3175 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3176 final Intent intent = new Intent();
3177 intent.setComponent(new ComponentName(
3178 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3179 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3180 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3181 return intent;
3182 }
3183
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003184 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003185 public void addIdleHandler(IdleHandler handler) {
3186 mHandler.getLooper().getQueue().addIdleHandler(handler);
3187 }
3188
Jeff Sharkey1b861272011-05-22 00:34:52 -07003189 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3190 final int size = source.size();
3191 for (int i = 0; i < size; i++) {
3192 target.put(source.keyAt(i), true);
3193 }
3194 }
3195
Stuart Scottf1fb3972015-04-02 18:00:02 -07003196 @Override
3197 public void factoryReset(String subscriber) {
3198 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3199
Stuart Scotte3e314d2015-04-20 14:07:45 -07003200 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3201 return;
3202 }
3203
Stuart Scottf1fb3972015-04-02 18:00:02 -07003204 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003205 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003206 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3207 for (NetworkPolicy policy : policies) {
3208 if (policy.template.equals(template)) {
3209 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3210 policy.inferred = false;
3211 policy.clearSnooze();
3212 }
3213 }
3214 setNetworkPolicies(policies);
3215
3216 // Turn restrict background data off
3217 setRestrictBackground(false);
3218
Stuart Scotte3e314d2015-04-20 14:07:45 -07003219 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3220 // Remove app's "restrict background data" flag
3221 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3222 setUidPolicy(uid, POLICY_NONE);
3223 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003224 }
3225 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003226
3227 private class MyPackageMonitor extends PackageMonitor {
3228
3229 @Override
3230 public void onPackageRemoved(String packageName, int uid) {
3231 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3232 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003233 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003234 }
3235 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003236 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003237}