blob: fc40f9f9a7decef82e04ca8981ab932d1239434f [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;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070032import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070033import static android.net.ConnectivityManager.TYPE_WIMAX;
Felipe Leme1b103232016-01-22 09:44:57 -080034import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
35import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
36import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
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;
44import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
45import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -070048import static android.net.NetworkPolicyManager.POLICY_ALLOW_BACKGROUND_BATTERY_SAVE;
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;
Jeff Sharkeydc988062015-09-14 10:09:47 -070052import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070053import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070054import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070055import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070056import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
57import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070058import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
59import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070060import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080061import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070062import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
63import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
64import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
65import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
66import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
67import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
68import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070069import static android.text.format.DateUtils.DAY_IN_MILLIS;
Jeff Sharkey854b2b12012-04-13 16:03:40 -070070import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070072import static com.android.internal.util.XmlUtils.readBooleanAttribute;
73import static com.android.internal.util.XmlUtils.readIntAttribute;
74import static com.android.internal.util.XmlUtils.readLongAttribute;
75import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
76import static com.android.internal.util.XmlUtils.writeIntAttribute;
77import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070078import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070079import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070080import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080081import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070082import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070083
Dianne Hackborn88e98df2015-03-23 13:29:14 -070084import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070085import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070086import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070087import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070088import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070089import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070090import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.app.Notification;
92import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070093import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070094import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070095import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070096import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.content.Intent;
98import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -070099import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700100import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700101import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700102import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700103import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700104import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700106import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700107import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700108import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700109import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700110import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700112import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700113import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700115import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700116import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700118import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700119import android.net.wifi.WifiConfiguration;
120import android.net.wifi.WifiInfo;
121import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700122import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.os.Environment;
124import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700125import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700126import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700127import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700128import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700129import android.os.Message;
Felipe Leme50a235e2016-01-15 18:37:06 -0800130import android.os.ResultReceiver;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700131import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700132import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700133import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700134import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700135import android.os.RemoteException;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700136import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700137import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700138import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700139import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800140import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700141import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700142import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700143import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700144import android.util.ArrayMap;
145import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700146import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700147import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700148import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700149import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700150import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700151import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700152import android.util.SparseBooleanArray;
153import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700154import android.util.TrustedTime;
155import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700156
Jeff Sharkey32566012014-12-02 18:30:14 -0800157import libcore.io.IoUtils;
158
Jeff Sharkey497e4432011-06-14 17:27:29 -0700159import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800160import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800161import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800162import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700164import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700165import com.android.server.DeviceIdleController;
166import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700167import com.android.server.LocalServices;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700168import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700169
170import org.xmlpull.v1.XmlPullParser;
171import org.xmlpull.v1.XmlPullParserException;
172import org.xmlpull.v1.XmlSerializer;
173
174import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700175import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700176import java.io.FileInputStream;
177import java.io.FileNotFoundException;
178import java.io.FileOutputStream;
179import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700180import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100181import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700182import java.util.ArrayList;
183import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700184import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700186/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700187 * Service that maintains low-level network policy rules, using
188 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700189 * <p>
190 * Derives active rules by combining a given policy with other system status,
191 * and delivers to listeners, such as {@link ConnectivityManager}, for
192 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700193 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700194public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800195 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700196 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700197 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700198
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700199 private static final int VERSION_INIT = 1;
200 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700201 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800202 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800203 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800204 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700205 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700206 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700207 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700208 private static final int VERSION_SWITCH_UID = 10;
209 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700210
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800211 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700212 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800213 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700214 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800215 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700217
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700218 private static final String TAG_POLICY_LIST = "policy-list";
219 private static final String TAG_NETWORK_POLICY = "network-policy";
220 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700221 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800222 private static final String TAG_WHITELIST = "whitelist";
223 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700224
225 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700226 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700227 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
228 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700229 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800231 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232 private static final String ATTR_WARNING_BYTES = "warningBytes";
233 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700234 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800235 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
236 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800237 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700238 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700239 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700240 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700241 private static final String ATTR_POLICY = "policy";
242
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800243 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800244 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800246 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700247
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700248 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
249
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700250 private static final int MSG_RULES_CHANGED = 1;
251 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800252 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800253 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700254 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700255 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800256 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700257
Jeff Sharkey75279902011-05-24 18:39:45 -0700258 private final Context mContext;
259 private final IActivityManager mActivityManager;
260 private final IPowerManager mPowerManager;
261 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700262 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700263 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700265 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266
267 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700268 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700269 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700270 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700271
Dianne Hackborn497175b2014-07-01 12:56:08 -0700272 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700273
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700274 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700275 volatile boolean mScreenOn;
276 volatile boolean mRestrictBackground;
277 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700278 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700279
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700280 private final boolean mSuppressDefaultPolicy;
281
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700282 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800283 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800285 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700286
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700287 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700288 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700289 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700291
Jeff Sharkeydc988062015-09-14 10:09:47 -0700292 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
293 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
294
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700295 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700296 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
297
Jeff Sharkey32566012014-12-02 18:30:14 -0800298 /**
299 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700300 * in power save mode, except device idle (doze) still applies.
301 * TODO: An int array might be sufficient
302 */
303 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
304
305 /**
306 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800307 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700308 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800309 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700310 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700311
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700312 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
313
Felipe Lemeb85a6372016-01-14 16:16:16 -0800314 /**
315 * UIDs that have been white-listed to avoid restricted background.
316 */
317 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
318
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700319 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800320 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700321 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700323
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700324 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700325 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700327 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800328 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700329
Jeff Sharkey32566012014-12-02 18:30:14 -0800330 private final RemoteCallbackList<INetworkPolicyListener>
331 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700332
Dianne Hackborn497175b2014-07-01 12:56:08 -0700333 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700334
335 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700336
Svet Ganov16a16892015-04-16 10:32:04 -0700337 private final AppOpsManager mAppOps;
338
Felipe Lemeb85a6372016-01-14 16:16:16 -0800339 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800340 private final IPackageManager mIPm;
341
Felipe Lemeb85a6372016-01-14 16:16:16 -0800342
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700343 // TODO: keep whitelist of system-critical services that should never have
344 // rules enforced, such as system, phone, and radio UIDs.
345
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 // TODO: migrate notifications to SystemUI
347
Jeff Sharkey75279902011-05-24 18:39:45 -0700348 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700349 IPowerManager powerManager, INetworkStatsService networkStats,
350 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700351 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700352 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353 }
354
355 private static File getSystemDir() {
356 return new File(Environment.getDataDirectory(), "system");
357 }
358
359 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700360 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700361 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
362 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700363 mContext = checkNotNull(context, "missing context");
364 mActivityManager = checkNotNull(activityManager, "missing activityManager");
365 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700366 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700367 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700368 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700369 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700370 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700371 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800372 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700373
Amith Yamasani450a16b2013-09-18 16:28:50 -0700374 HandlerThread thread = new HandlerThread(TAG);
375 thread.start();
376 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700377
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700378 mSuppressDefaultPolicy = suppressDefaultPolicy;
379
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700380 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700381
382 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800383
384 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700385 }
386
387 public void bindConnectivityManager(IConnectivityManager connManager) {
388 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700389 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700390
Jeff Sharkey497e4432011-06-14 17:27:29 -0700391 public void bindNotificationManager(INotificationManager notifManager) {
392 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
393 }
394
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700395 void updatePowerSaveWhitelistLocked() {
396 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700397 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
398 mPowerSaveWhitelistExceptIdleAppIds.clear();
399 if (whitelist != null) {
400 for (int uid : whitelist) {
401 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
402 }
403 }
404 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700405 mPowerSaveWhitelistAppIds.clear();
406 if (whitelist != null) {
407 for (int uid : whitelist) {
408 mPowerSaveWhitelistAppIds.put(uid, true);
409 }
410 }
411 } catch (RemoteException e) {
412 }
413 }
414
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700415 void updatePowerSaveTempWhitelistLocked() {
416 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700417 // Clear the states of the current whitelist
418 final int N = mPowerSaveTempWhitelistAppIds.size();
419 for (int i = 0; i < N; i++) {
420 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
421 }
422 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700423 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700424 if (whitelist != null) {
425 for (int uid : whitelist) {
426 mPowerSaveTempWhitelistAppIds.put(uid, true);
427 }
428 }
429 } catch (RemoteException e) {
430 }
431 }
432
Amith Yamasani06f08062015-06-12 13:23:33 -0700433 /**
434 * Remove unnecessary entries in the temp whitelist
435 */
436 void purgePowerSaveTempWhitelistLocked() {
437 final int N = mPowerSaveTempWhitelistAppIds.size();
438 for (int i = N - 1; i >= 0; i--) {
439 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
440 mPowerSaveTempWhitelistAppIds.removeAt(i);
441 }
442 }
443 }
444
Jeff Sharkeya4620792011-05-20 15:29:23 -0700445 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700446 if (!isBandwidthControlEnabled()) {
447 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
448 return;
449 }
450
Amith Yamasani15e472352015-04-24 19:06:07 -0700451 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
452
Felipe Lemeb85a6372016-01-14 16:16:16 -0800453 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
454
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700455 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700456 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700457 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
458 mPowerManagerInternal.registerLowPowerModeObserver(
459 new PowerManagerInternal.LowPowerModeListener() {
460 @Override
461 public void onLowPowerModeChanged(boolean enabled) {
462 synchronized (mRulesLock) {
463 if (mRestrictPower != enabled) {
464 mRestrictPower = enabled;
465 updateRulesForGlobalChangeLocked(true);
466 }
467 }
468 }
469 });
470 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700471 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700472
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700473 // read policy from disk
474 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700475
Jeff Sharkeydc988062015-09-14 10:09:47 -0700476 updateRulesForGlobalChangeLocked(false);
477 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700478 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700479
Jeff Sharkeya4620792011-05-20 15:29:23 -0700480 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700481
Jeff Sharkeya4620792011-05-20 15:29:23 -0700482 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700483 mActivityManager.registerUidObserver(mUidObserver,
484 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700485 mNetworkManager.registerObserver(mAlertObserver);
486 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700487 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700488 }
489
Jeff Sharkeya4620792011-05-20 15:29:23 -0700490 // TODO: traverse existing processes to know foreground state, or have
491 // activitymanager dispatch current state when new observer attached.
492
493 final IntentFilter screenFilter = new IntentFilter();
494 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
495 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700496 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700497
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700498 // listen for changes to power save whitelist
499 final IntentFilter whitelistFilter = new IntentFilter(
500 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
501 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
502
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700503 DeviceIdleController.LocalService deviceIdleService
504 = LocalServices.getService(DeviceIdleController.LocalService.class);
505 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
506
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700507 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900508 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700509 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
510
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700511 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700512 final IntentFilter packageFilter = new IntentFilter();
513 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700514 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700515 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700516
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700517 // listen for UID changes to update policy
518 mContext.registerReceiver(
519 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
520
521 // listen for user changes to update policy
522 final IntentFilter userFilter = new IntentFilter();
523 userFilter.addAction(ACTION_USER_ADDED);
524 userFilter.addAction(ACTION_USER_REMOVED);
525 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
526
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700527 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700528 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
529 mContext.registerReceiver(
530 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
531
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700532 // listen for restrict background changes from notifications
533 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
534 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
535
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800536 // listen for snooze warning from notifications
537 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
538 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
539 MANAGE_NETWORK_POLICY, mHandler);
540
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700541 // listen for configured wifi networks to be removed
542 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700543 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700544
545 // listen for wifi state changes to catch metered hint
546 final IntentFilter wifiStateFilter = new IntentFilter(
547 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700548 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700549
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700550 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700551
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700552 }
553
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700554 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700555 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700556 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700557 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700558 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700559 }
560
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700561 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700562 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700563 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700564 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700565 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700566
567 @Override public void onUidActive(int uid) throws RemoteException {
568 }
569
570 @Override public void onUidIdle(int uid) throws RemoteException {
571 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572 };
573
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700574 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700575 @Override
576 public void onReceive(Context context, Intent intent) {
577 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
578 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700579 updatePowerSaveWhitelistLocked();
580 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700581 }
582 }
583 };
584
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700585 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
586 @Override
587 public void run() {
588 synchronized (mRulesLock) {
589 updatePowerSaveTempWhitelistLocked();
590 updateRulesForTempWhitelistChangeLocked();
591 purgePowerSaveTempWhitelistLocked();
592 }
593 }
594 };
595
596 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700597 @Override
598 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800599 // screen-related broadcasts are protected by system, no need
600 // for permissions check.
601 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700602 }
603 };
604
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700605 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700606 @Override
607 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700608 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700609
610 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700611 final int uid = intent.getIntExtra(EXTRA_UID, -1);
612 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700613
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700614 if (ACTION_PACKAGE_ADDED.equals(action)) {
615 // update rules for UID, since it might be subject to
616 // global background data policy
617 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
618 synchronized (mRulesLock) {
619 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700620 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700621 }
622 }
623 };
624
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700625 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700626 @Override
627 public void onReceive(Context context, Intent intent) {
628 // on background handler thread, and UID_REMOVED is protected
629
630 final int uid = intent.getIntExtra(EXTRA_UID, -1);
631 if (uid == -1) return;
632
633 // remove any policy and update rules to clean up
634 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
635 synchronized (mRulesLock) {
636 mUidPolicy.delete(uid);
637 updateRulesForUidLocked(uid);
638 writePolicyLocked();
639 }
640 }
641 };
642
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700643 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700644 @Override
645 public void onReceive(Context context, Intent intent) {
646 // on background handler thread, and USER_ADDED and USER_REMOVED
647 // broadcasts are protected
648
649 final String action = intent.getAction();
650 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
651 if (userId == -1) return;
652
Amith Yamasani15e472352015-04-24 19:06:07 -0700653 switch (action) {
654 case ACTION_USER_REMOVED:
655 case ACTION_USER_ADDED:
656 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800657 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700658 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800659 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700660 // Update global restrict for new user
661 updateRulesForGlobalChangeLocked(true);
662 }
663 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700664 }
665 }
666 };
667
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700668 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700669 * Receiver that watches for {@link INetworkStatsService} updates, which we
670 * use to check against {@link NetworkPolicy#warningBytes}.
671 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700672 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700673 @Override
674 public void onReceive(Context context, Intent intent) {
675 // on background handler thread, and verified
676 // READ_NETWORK_USAGE_HISTORY permission above.
677
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800678 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700679 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700680 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700681 updateNotificationsLocked();
682 }
683 }
684 };
685
686 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700687 * Receiver that watches for {@link Notification} control of
688 * {@link #mRestrictBackground}.
689 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700690 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700691 @Override
692 public void onReceive(Context context, Intent intent) {
693 // on background handler thread, and verified MANAGE_NETWORK_POLICY
694 // permission above.
695
696 setRestrictBackground(false);
697 }
698 };
699
700 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800701 * Receiver that watches for {@link Notification} control of
702 * {@link NetworkPolicy#lastWarningSnooze}.
703 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700704 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800705 @Override
706 public void onReceive(Context context, Intent intent) {
707 // on background handler thread, and verified MANAGE_NETWORK_POLICY
708 // permission above.
709
710 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
711 performSnooze(template, TYPE_WARNING);
712 }
713 };
714
715 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700716 * Receiver that watches for {@link WifiConfiguration} to be changed.
717 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700718 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700719 @Override
720 public void onReceive(Context context, Intent intent) {
721 // on background handler thread, and verified CONNECTIVITY_INTERNAL
722 // permission above.
723
724 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
725 if (reason == CHANGE_REASON_REMOVED) {
726 final WifiConfiguration config = intent.getParcelableExtra(
727 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700728 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800729 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700730 synchronized (mRulesLock) {
731 if (mNetworkPolicy.containsKey(template)) {
732 mNetworkPolicy.remove(template);
733 writePolicyLocked();
734 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700735 }
736 }
737 }
738 }
739 };
740
741 /**
742 * Receiver that watches {@link WifiInfo} state changes to infer metered
743 * state. Ignores hints when policy is user-defined.
744 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700745 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700746 @Override
747 public void onReceive(Context context, Intent intent) {
748 // on background handler thread, and verified CONNECTIVITY_INTERNAL
749 // permission above.
750
751 // ignore when not connected
752 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
753 if (!netInfo.isConnected()) return;
754
755 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
756 final boolean meteredHint = info.getMeteredHint();
757
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800758 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700759 synchronized (mRulesLock) {
760 NetworkPolicy policy = mNetworkPolicy.get(template);
761 if (policy == null && meteredHint) {
762 // policy doesn't exist, and AP is hinting that it's
763 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800764 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700765 addNetworkPolicyLocked(policy);
766
767 } else if (policy != null && policy.inferred) {
768 // policy exists, and was inferred: update its current
769 // metered state.
770 policy.metered = meteredHint;
771
772 // since this is inferred for each wifi session, just update
773 // rules without persisting.
774 updateNetworkRulesLocked();
775 }
776 }
777 }
778 };
779
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800780 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
781 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
782 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
783 metered, true);
784 }
785
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700786 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700787 * Observer that watches for {@link INetworkManagementService} alerts.
788 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700789 final private INetworkManagementEventObserver mAlertObserver
790 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700791 @Override
792 public void limitReached(String limitName, String iface) {
793 // only someone like NMS should be calling us
794 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
795
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800796 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
797 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700798 }
799 }
800 };
801
802 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700803 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
804 * to show visible notifications as needed.
805 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700806 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
808
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700809 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700810 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700811 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700812
813 // TODO: when switching to kernel notifications, compute next future
814 // cycle boundary to recompute notifications.
815
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700816 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800817 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700818 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
819 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700820 // ignore policies that aren't relevant to user
821 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700822 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700823
Jeff Sharkey497e4432011-06-14 17:27:29 -0700824 final long start = computeLastCycleBoundary(currentTime, policy);
825 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700826 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700827
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700828 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800829 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700830 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
831 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700832 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
833 notifyOverLimitLocked(policy.template);
834 }
835
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700837 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700838
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800839 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700840 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700841 }
842 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700843 }
844
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700845 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700846 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
847 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700848 if (!mActiveNotifs.contains(tag)) {
849 cancelNotification(tag);
850 }
851 }
852 }
853
854 /**
855 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700856 * current device state, such as when
857 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
858 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700859 */
860 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800861 if (template.isMatchRuleMobile()) {
862 final TelephonyManager tele = TelephonyManager.from(mContext);
863 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700864
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 // Mobile template is relevant when any active subscriber matches
866 final int[] subIds = sub.getActiveSubscriptionIdList();
867 for (int subId : subIds) {
868 final String subscriberId = tele.getSubscriberId(subId);
869 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
870 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
871 if (template.matches(probeIdent)) {
872 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700873 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800874 }
875 return false;
876 } else {
877 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700878 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879 }
880
881 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700882 * Notify that given {@link NetworkTemplate} is over
883 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
884 */
885 private void notifyOverLimitLocked(NetworkTemplate template) {
886 if (!mOverLimitNotified.contains(template)) {
887 mContext.startActivity(buildNetworkOverLimitIntent(template));
888 mOverLimitNotified.add(template);
889 }
890 }
891
892 private void notifyUnderLimitLocked(NetworkTemplate template) {
893 mOverLimitNotified.remove(template);
894 }
895
896 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 * Build unique tag that identifies an active {@link NetworkPolicy}
898 * notification of a specific type, like {@link #TYPE_LIMIT}.
899 */
900 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700901 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902 }
903
904 /**
905 * Show notification for combined {@link NetworkPolicy} and specific type,
906 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
907 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700908 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700909 final String tag = buildNotificationTag(policy, type);
910 final Notification.Builder builder = new Notification.Builder(mContext);
911 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800912 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700913 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200914 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700915
916 final Resources res = mContext.getResources();
917 switch (type) {
918 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700919 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700920 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700921
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700922 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700923 builder.setTicker(title);
924 builder.setContentTitle(title);
925 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700926
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800927 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
928 builder.setDeleteIntent(PendingIntent.getBroadcast(
929 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
930
931 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700932 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800933 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
934
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935 break;
936 }
937 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700938 final CharSequence body = res.getText(R.string.data_usage_limit_body);
939
940 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400941 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700942 switch (policy.template.getMatchRule()) {
943 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700944 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700945 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700946 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700947 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 case MATCH_WIFI:
953 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400954 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700955 break;
956 default:
957 title = null;
958 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700959 }
960
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800961 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400962 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 builder.setTicker(title);
964 builder.setContentTitle(title);
965 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700966
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967 final Intent intent = buildNetworkOverLimitIntent(policy.template);
968 builder.setContentIntent(PendingIntent.getActivity(
969 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
970 break;
971 }
972 case TYPE_LIMIT_SNOOZED: {
973 final long overBytes = totalBytes - policy.limitBytes;
974 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
975 Formatter.formatFileSize(mContext, overBytes));
976
977 final CharSequence title;
978 switch (policy.template.getMatchRule()) {
979 case MATCH_MOBILE_3G_LOWER:
980 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
981 break;
982 case MATCH_MOBILE_4G:
983 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
984 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
987 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700988 case MATCH_WIFI:
989 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
990 break;
991 default:
992 title = null;
993 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 }
995
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800996 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700997 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 builder.setTicker(title);
999 builder.setContentTitle(title);
1000 builder.setContentText(body);
1001
1002 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001003 builder.setContentIntent(PendingIntent.getActivity(
1004 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005 break;
1006 }
1007 }
1008
1009 // TODO: move to NotificationManager once we can mock it
1010 try {
1011 final String packageName = mContext.getPackageName();
1012 final int[] idReceived = new int[1];
1013 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001014 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001015 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001016 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001018 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 }
1020 }
1021
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001022 private void cancelNotification(String tag) {
1023 // TODO: move to NotificationManager once we can mock it
1024 try {
1025 final String packageName = mContext.getPackageName();
1026 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001027 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001029 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 }
1031 }
1032
1033 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001034 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001035 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001036 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001037 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001038 @Override
1039 public void onReceive(Context context, Intent intent) {
1040 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1041 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001042
1043 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001044 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001045 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001046 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001047 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001048 updateNetworkRulesLocked();
1049 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001050 }
1051 }
1052 };
1053
1054 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 * Proactively control network data connections when they exceed
1056 * {@link NetworkPolicy#limitBytes}.
1057 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001058 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001059 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1060
1061 // TODO: reset any policy-disabled networks when any policy is removed
1062 // completely, which is currently rare case.
1063
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001064 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001065 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1066 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001067 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001068 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001069 setNetworkTemplateEnabled(policy.template, true);
1070 continue;
1071 }
1072
1073 final long start = computeLastCycleBoundary(currentTime, policy);
1074 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001075 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076
1077 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001078 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1079 && policy.lastLimitSnooze < start;
1080 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001081
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001082 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 }
1084 }
1085
1086 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001087 * Proactively disable networks that match the given
1088 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001089 */
1090 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001091 // TODO: reach into ConnectivityManager to proactively disable bringing
1092 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001093 }
1094
1095 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001096 * Examine all connected {@link NetworkState}, looking for
1097 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1098 * remaining quota based on usage cycle and historical stats.
1099 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001100 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001101 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001102
1103 final NetworkState[] states;
1104 try {
1105 states = mConnManager.getAllNetworkState();
1106 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001107 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001108 return;
1109 }
1110
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001111 // If we are in restrict power mode, we want to treat all interfaces
1112 // as metered, to restrict access to the network by uid. However, we
1113 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001114 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001115 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001116 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001117
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001118 // First, generate identities of all connected networks so we can
1119 // quickly compare them against all defined policies below.
1120 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001121 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001122 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001123 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001124 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001125
1126 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001127 if (baseIface != null) {
1128 connIdents.add(Pair.create(baseIface, ident));
1129 if (powerSave) {
1130 connIfaces.add(baseIface);
1131 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001132 }
1133
1134 // Stacked interfaces are considered to have same identity as
1135 // their parent network.
1136 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1137 for (LinkProperties stackedLink : stackedLinks) {
1138 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001139 if (stackedIface != null) {
1140 connIdents.add(Pair.create(stackedIface, ident));
1141 if (powerSave) {
1142 connIfaces.add(stackedIface);
1143 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001144 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001145 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001146 }
1147 }
1148
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001149 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001150 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001151 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001152 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001153 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001155 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001156 for (int j = connIdents.size() - 1; j >= 0; j--) {
1157 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1158 if (policy.template.matches(ident.second)) {
1159 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001160 }
1161 }
1162
1163 if (ifaceList.size() > 0) {
1164 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001165 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001166 }
1167 }
1168
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001169 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001170 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001171
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001172 // apply each policy that we found ifaces for; compute remaining data
1173 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001174 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001175 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1176 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1177 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001178
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001179 final long start;
1180 final long totalBytes;
1181 if (policy.hasCycle()) {
1182 start = computeLastCycleBoundary(currentTime, policy);
1183 totalBytes = getTotalBytes(policy.template, start, currentTime);
1184 } else {
1185 start = Long.MAX_VALUE;
1186 totalBytes = 0;
1187 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 if (LOGD) {
1190 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001191 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001192 }
1193
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001194 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001196 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001197 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001198 if (!hasLimit) {
1199 // metered network, but no policy limit; we still need to
1200 // restrict apps, so push really high quota.
1201 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001202 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001203 // snoozing past quota, but we still need to restrict apps,
1204 // so push really high quota.
1205 quotaBytes = Long.MAX_VALUE;
1206 } else {
1207 // remaining "quota" bytes are based on total usage in
1208 // current cycle. kernel doesn't like 0-byte rules, so we
1209 // set 1-byte quota and disable the radio later.
1210 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1211 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001212
1213 if (ifaces.length > 1) {
1214 // TODO: switch to shared quota once NMS supports
1215 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001216 }
1217
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001218 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001219 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001220 setInterfaceQuota(iface, quotaBytes);
1221 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001222 if (powerSave) {
1223 connIfaces.remove(iface);
1224 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001225 }
1226 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001227
1228 // keep track of lowest warning or limit of active policies
1229 if (hasWarning && policy.warningBytes < lowestRule) {
1230 lowestRule = policy.warningBytes;
1231 }
1232 if (hasLimit && policy.limitBytes < lowestRule) {
1233 lowestRule = policy.limitBytes;
1234 }
1235 }
1236
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001237 for (int i = connIfaces.size()-1; i >= 0; i--) {
1238 String iface = connIfaces.valueAt(i);
1239 removeInterfaceQuota(iface);
1240 setInterfaceQuota(iface, Long.MAX_VALUE);
1241 newMeteredIfaces.add(iface);
1242 }
1243
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001244 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001245
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001246 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001247 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1248 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001249 if (!newMeteredIfaces.contains(iface)) {
1250 removeInterfaceQuota(iface);
1251 }
1252 }
1253 mMeteredIfaces = newMeteredIfaces;
1254
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001255 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001256 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001257 }
1258
1259 /**
1260 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1261 * have at least a default mobile policy defined.
1262 */
1263 private void ensureActiveMobilePolicyLocked() {
1264 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001265 if (mSuppressDefaultPolicy) return;
1266
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001267 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001268 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001269
Jeff Sharkey32566012014-12-02 18:30:14 -08001270 final int[] subIds = sub.getActiveSubscriptionIdList();
1271 for (int subId : subIds) {
1272 final String subscriberId = tele.getSubscriberId(subId);
1273 ensureActiveMobilePolicyLocked(subscriberId);
1274 }
1275 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001276
Jeff Sharkey32566012014-12-02 18:30:14 -08001277 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1278 // Poke around to see if we already have a policy
1279 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1280 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1281 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1282 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1283 if (template.matches(probeIdent)) {
1284 if (LOGD) {
1285 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1286 + NetworkIdentity.scrubSubscriberId(subscriberId));
1287 }
1288 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001289 }
1290 }
1291
Jeff Sharkey32566012014-12-02 18:30:14 -08001292 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1293 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001294
Jeff Sharkey32566012014-12-02 18:30:14 -08001295 // Build default mobile policy, and assume usage cycle starts today
1296 final long warningBytes = mContext.getResources().getInteger(
1297 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001298
Jeff Sharkey32566012014-12-02 18:30:14 -08001299 final Time time = new Time();
1300 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001301
Jeff Sharkey32566012014-12-02 18:30:14 -08001302 final int cycleDay = time.monthDay;
1303 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001304
Jeff Sharkey32566012014-12-02 18:30:14 -08001305 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1306 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1307 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1308 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001309 }
1310
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001311 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001312 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001313
1314 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001315 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001316 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001317
1318 FileInputStream fis = null;
1319 try {
1320 fis = mPolicyFile.openRead();
1321 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001322 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001323
1324 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001325 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001326 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 while ((type = in.next()) != END_DOCUMENT) {
1328 final String tag = in.getName();
1329 if (type == START_TAG) {
1330 if (TAG_POLICY_LIST.equals(tag)) {
1331 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001332 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1333 mRestrictBackground = readBooleanAttribute(
1334 in, ATTR_RESTRICT_BACKGROUND);
1335 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001336 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001337 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001338
1339 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1340 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1341 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001342 final String networkId;
1343 if (version >= VERSION_ADDED_NETWORK_ID) {
1344 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1345 } else {
1346 networkId = null;
1347 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001349 final String cycleTimezone;
1350 if (version >= VERSION_ADDED_TIMEZONE) {
1351 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1352 } else {
1353 cycleTimezone = Time.TIMEZONE_UTC;
1354 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001355 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1356 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001357 final long lastLimitSnooze;
1358 if (version >= VERSION_SPLIT_SNOOZE) {
1359 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1360 } else if (version >= VERSION_ADDED_SNOOZE) {
1361 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001362 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001363 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001364 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001365 final boolean metered;
1366 if (version >= VERSION_ADDED_METERED) {
1367 metered = readBooleanAttribute(in, ATTR_METERED);
1368 } else {
1369 switch (networkTemplate) {
1370 case MATCH_MOBILE_3G_LOWER:
1371 case MATCH_MOBILE_4G:
1372 case MATCH_MOBILE_ALL:
1373 metered = true;
1374 break;
1375 default:
1376 metered = false;
1377 }
1378 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001379 final long lastWarningSnooze;
1380 if (version >= VERSION_SPLIT_SNOOZE) {
1381 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1382 } else {
1383 lastWarningSnooze = SNOOZE_NEVER;
1384 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001385 final boolean inferred;
1386 if (version >= VERSION_ADDED_INFERRED) {
1387 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1388 } else {
1389 inferred = false;
1390 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001391
Jeff Sharkey32566012014-12-02 18:30:14 -08001392 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1393 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001394 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001395 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001396 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001398 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399 final int uid = readIntAttribute(in, ATTR_UID);
1400 final int policy = readIntAttribute(in, ATTR_POLICY);
1401
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001402 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001403 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001404 } else {
1405 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1406 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001407 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001408 final int appId = readIntAttribute(in, ATTR_APP_ID);
1409 final int policy = readIntAttribute(in, ATTR_POLICY);
1410
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001411 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001412 // app policy is deprecated so this is only used in pre system user split.
1413 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001414 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001415 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001416 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001417 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001418 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001419 } else if (TAG_WHITELIST.equals(tag)) {
1420 insideWhitelist = true;
1421 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1422 final int uid = readIntAttribute(in, ATTR_UID);
1423 mRestrictBackgroundWhitelistUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001425 } else if (type == END_TAG) {
1426 if (TAG_WHITELIST.equals(tag)) {
1427 insideWhitelist = false;
1428 }
1429
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001430 }
1431 }
1432
1433 } catch (FileNotFoundException e) {
1434 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001435 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001436 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001437 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001438 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001439 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001440 } finally {
1441 IoUtils.closeQuietly(fis);
1442 }
1443 }
1444
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001445 /**
1446 * Upgrade legacy background data flags, notifying listeners of one last
1447 * change to always-true.
1448 */
1449 private void upgradeLegacyBackgroundData() {
1450 mRestrictBackground = Settings.Secure.getInt(
1451 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1452
1453 // kick off one last broadcast if restricted
1454 if (mRestrictBackground) {
1455 final Intent broadcast = new Intent(
1456 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001457 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001458 }
1459 }
1460
Dianne Hackborn497175b2014-07-01 12:56:08 -07001461 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001462 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463
1464 FileOutputStream fos = null;
1465 try {
1466 fos = mPolicyFile.startWrite();
1467
1468 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001469 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001470 out.startDocument(null, true);
1471
1472 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001473 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001474 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475
1476 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001477 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1478 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001479 final NetworkTemplate template = policy.template;
1480
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001481 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001482 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1483 final String subscriberId = template.getSubscriberId();
1484 if (subscriberId != null) {
1485 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001487 final String networkId = template.getNetworkId();
1488 if (networkId != null) {
1489 out.attribute(null, ATTR_NETWORK_ID, networkId);
1490 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001491 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001492 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1494 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001495 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1496 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001497 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001498 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 out.endTag(null, TAG_NETWORK_POLICY);
1500 }
1501
1502 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001503 for (int i = 0; i < mUidPolicy.size(); i++) {
1504 final int uid = mUidPolicy.keyAt(i);
1505 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506
Jeff Sharkey497e4432011-06-14 17:27:29 -07001507 // skip writing empty policies
1508 if (policy == POLICY_NONE) continue;
1509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001510 out.startTag(null, TAG_UID_POLICY);
1511 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001513 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001514 }
1515
1516 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001517
1518 // write all whitelists
1519 out.startTag(null, TAG_WHITELIST);
1520
1521 // restrict background whitelist
1522 final int size = mRestrictBackgroundWhitelistUids.size();
1523 for (int i = 0; i < size; i++) {
1524 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1525 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1526 writeIntAttribute(out, ATTR_UID, uid);
1527 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1528 }
1529
1530 out.endTag(null, TAG_WHITELIST);
1531
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532 out.endDocument();
1533
1534 mPolicyFile.finishWrite(fos);
1535 } catch (IOException e) {
1536 if (fos != null) {
1537 mPolicyFile.failWrite(fos);
1538 }
1539 }
1540 }
1541
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001542 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001543 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001545
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001546 if (!UserHandle.isApp(uid)) {
1547 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001548 }
1549
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001550 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001551 final long token = Binder.clearCallingIdentity();
1552 try {
1553 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1554 if (oldPolicy != policy) {
1555 setUidPolicyUncheckedLocked(uid, policy, true);
1556 }
1557 } finally {
1558 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001559 }
1560 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001561 }
1562
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001563 @Override
1564 public void addUidPolicy(int uid, int policy) {
1565 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001566
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001567 if (!UserHandle.isApp(uid)) {
1568 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1569 }
1570
1571 synchronized (mRulesLock) {
1572 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1573 policy |= oldPolicy;
1574 if (oldPolicy != policy) {
1575 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001576 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001578 }
1579
1580 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001581 public void removeUidPolicy(int uid, int policy) {
1582 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1583
1584 if (!UserHandle.isApp(uid)) {
1585 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1586 }
1587
1588 synchronized (mRulesLock) {
1589 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1590 policy = oldPolicy & ~policy;
1591 if (oldPolicy != policy) {
1592 setUidPolicyUncheckedLocked(uid, policy, true);
1593 }
1594 }
1595 }
1596
1597 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1598 mUidPolicy.put(uid, policy);
1599
1600 // uid policy changed, recompute rules and persist policy.
1601 updateRulesForUidLocked(uid);
1602 if (persist) {
1603 writePolicyLocked();
1604 }
1605 }
1606
1607 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001608 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1610
Jeff Sharkeya4620792011-05-20 15:29:23 -07001611 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001612 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001613 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001614 }
1615
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001616 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001617 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001618 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1619
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001620 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001621 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001622 for (int i = 0; i < mUidPolicy.size(); i++) {
1623 final int uid = mUidPolicy.keyAt(i);
1624 final int uidPolicy = mUidPolicy.valueAt(i);
1625 if (uidPolicy == policy) {
1626 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001627 }
1628 }
1629 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001630 return uids;
1631 }
1632
1633 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001634 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001635 * if any changes are made.
1636 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001637 void removeUserStateLocked(int userId) {
1638 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1639 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001640
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001641 // Remove entries from restricted background UID whitelist
1642 int[] wlUids = new int[0];
1643 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1644 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1645 if (UserHandle.getUserId(uid) == userId) {
1646 wlUids = appendInt(wlUids, uid);
1647 }
1648 }
1649
1650 if (wlUids.length > 0) {
1651 for (int uid : wlUids) {
1652 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1653 }
1654 writePolicy = true;
1655 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08001656 updateRulesForGlobalChangeLocked(true);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001657
1658 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001659 int[] uids = new int[0];
1660 for (int i = 0; i < mUidPolicy.size(); i++) {
1661 final int uid = mUidPolicy.keyAt(i);
1662 if (UserHandle.getUserId(uid) == userId) {
1663 uids = appendInt(uids, uid);
1664 }
1665 }
1666
1667 if (uids.length > 0) {
1668 for (int uid : uids) {
1669 mUidPolicy.delete(uid);
1670 updateRulesForUidLocked(uid);
1671 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001672 writePolicy = true;
1673 }
1674
1675 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001676 writePolicyLocked();
1677 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001678 }
1679
1680 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001681 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001682 // TODO: create permission for observing network policy
1683 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1684
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001685 mListeners.register(listener);
1686
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001687 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001688 }
1689
1690 @Override
1691 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001692 // TODO: create permission for observing network policy
1693 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1694
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001695 mListeners.unregister(listener);
1696 }
1697
Jeff Sharkey1b861272011-05-22 00:34:52 -07001698 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001699 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001700 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1701
Felipe Leme6a05eee2016-02-19 14:43:51 -08001702 final long token = Binder.clearCallingIdentity();
1703 try {
1704 maybeRefreshTrustedTime();
1705 synchronized (mRulesLock) {
1706 normalizePoliciesLocked(policies);
1707 updateNetworkEnabledLocked();
1708 updateNetworkRulesLocked();
1709 updateNotificationsLocked();
1710 writePolicyLocked();
1711 }
1712 } finally {
1713 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001714 }
1715 }
1716
Dianne Hackborn497175b2014-07-01 12:56:08 -07001717 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001718 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001719 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1720 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001721 }
1722
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001723 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001724 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001725 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001726 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001727 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1728 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1729 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001730 } catch (SecurityException e) {
1731 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001732
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001733 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1734 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1735 return new NetworkPolicy[0];
1736 }
Svet Ganov16a16892015-04-16 10:32:04 -07001737 }
1738
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001739 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001740 final int size = mNetworkPolicy.size();
1741 final NetworkPolicy[] policies = new NetworkPolicy[size];
1742 for (int i = 0; i < size; i++) {
1743 policies[i] = mNetworkPolicy.valueAt(i);
1744 }
1745 return policies;
1746 }
1747 }
1748
1749 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001750 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001751 }
1752
1753 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1754 final TelephonyManager tele = TelephonyManager.from(mContext);
1755 final String[] merged = tele.getMergedSubscriberIds();
1756
1757 mNetworkPolicy.clear();
1758 for (NetworkPolicy policy : policies) {
1759 // When two normalized templates conflict, prefer the most
1760 // restrictive policy
1761 policy.template = NetworkTemplate.normalize(policy.template, merged);
1762 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1763 if (existing == null || existing.compareTo(policy) > 0) {
1764 if (existing != null) {
1765 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1766 }
1767 mNetworkPolicy.put(policy.template, policy);
1768 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001769 }
1770 }
1771
1772 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001773 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001774 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001775
1776 final long token = Binder.clearCallingIdentity();
1777 try {
1778 performSnooze(template, TYPE_LIMIT);
1779 } finally {
1780 Binder.restoreCallingIdentity(token);
1781 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001782 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001783
Dianne Hackborn497175b2014-07-01 12:56:08 -07001784 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001785 maybeRefreshTrustedTime();
1786 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001787 synchronized (mRulesLock) {
1788 // find and snooze local policy that matches
1789 final NetworkPolicy policy = mNetworkPolicy.get(template);
1790 if (policy == null) {
1791 throw new IllegalArgumentException("unable to find policy for " + template);
1792 }
1793
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001794 switch (type) {
1795 case TYPE_WARNING:
1796 policy.lastWarningSnooze = currentTime;
1797 break;
1798 case TYPE_LIMIT:
1799 policy.lastLimitSnooze = currentTime;
1800 break;
1801 default:
1802 throw new IllegalArgumentException("unexpected type");
1803 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001804
Jeff Sharkey32566012014-12-02 18:30:14 -08001805 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001806 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001807 updateNetworkRulesLocked();
1808 updateNotificationsLocked();
1809 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001810 }
1811 }
1812
1813 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001814 public void setRestrictBackground(boolean restrictBackground) {
1815 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001816 final long token = Binder.clearCallingIdentity();
1817 try {
1818 maybeRefreshTrustedTime();
1819 synchronized (mRulesLock) {
1820 mRestrictBackground = restrictBackground;
1821 updateRulesForGlobalChangeLocked(true);
1822 updateNotificationsLocked();
1823 writePolicyLocked();
1824 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001825
Felipe Leme6a05eee2016-02-19 14:43:51 -08001826 } finally {
1827 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001828 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001829
1830 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1831 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001832 }
1833
1834 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001835 public void addRestrictBackgroundWhitelistedUid(int uid) {
1836 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001837 if (!isUidValidForRules(uid)) return;
1838 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001839 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001840 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1841 if (oldStatus) {
1842 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
1843 return;
1844 }
1845 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08001846 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Leme47585ba2016-02-09 16:56:32 -08001847 changed = mRestrictBackground && !oldStatus;
1848 if (changed && hasInternetPermissions(uid)) {
1849 setUidNetworkRules(uid, false);
1850 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001851 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001852 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001853 if (changed) {
1854 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1855 .sendToTarget();
1856 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001857 }
1858
1859 @Override
1860 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1861 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001862 if (!isUidValidForRules(uid)) return;
1863 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001864 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001865 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001866 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001867 if (changed) {
1868 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1869 .sendToTarget();
1870 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001871 }
1872
Felipe Leme47585ba2016-02-09 16:56:32 -08001873 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean updateNow) {
1874 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1875 if (!oldStatus) {
1876 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
1877 return false;
1878 }
1879 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1880 final boolean changed = mRestrictBackground && oldStatus;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001881 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Leme3f52cd52016-02-03 13:36:30 -08001882 if (updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001883 if (changed && hasInternetPermissions(uid)) {
1884 setUidNetworkRules(uid, true);
1885 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001886 writePolicyLocked();
1887 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001888 return changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001889 }
1890
1891 @Override
1892 public int[] getRestrictBackgroundWhitelistedUids() {
1893 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1894 synchronized (mRulesLock) {
1895 final int size = mRestrictBackgroundWhitelistUids.size();
1896 final int[] whitelist = new int[size];
1897 for (int i = 0; i < size; i++) {
1898 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1899 }
1900 if (LOGV) {
1901 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1902 + mRestrictBackgroundWhitelistUids);
1903 }
1904 return whitelist;
1905 }
1906 }
1907
1908 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08001909 public int getRestrictBackgroundByCaller() {
1910 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1911 final int uid = Binder.getCallingUid();
1912 synchronized (mRulesLock) {
1913 if (!mRestrictBackground) {
1914 return RESTRICT_BACKGROUND_STATUS_DISABLED;
1915 }
1916 return mRestrictBackgroundWhitelistUids.get(uid)
1917 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
1918 : RESTRICT_BACKGROUND_STATUS_ENABLED;
1919 }
1920 }
1921
1922 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001923 public boolean getRestrictBackground() {
1924 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1925
1926 synchronized (mRulesLock) {
1927 return mRestrictBackground;
1928 }
1929 }
1930
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001931 @Override
1932 public void setDeviceIdleMode(boolean enabled) {
1933 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1934
1935 synchronized (mRulesLock) {
1936 if (mDeviceIdleMode != enabled) {
1937 mDeviceIdleMode = enabled;
1938 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001939 // Device idle change means we need to rebuild rules for all
1940 // known apps, so do a global refresh.
1941 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001942 }
1943 if (enabled) {
1944 EventLogTags.writeDeviceIdleOnPhase("net");
1945 } else {
1946 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001947 }
1948 }
1949 }
1950 }
1951
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001952 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001953 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1954 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001955 if (policy.template.matches(ident)) {
1956 return policy;
1957 }
1958 }
1959 return null;
1960 }
1961
1962 @Override
1963 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1964 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1965
1966 // only returns usage summary, so we don't require caller to have
1967 // READ_NETWORK_USAGE_HISTORY.
1968 final long token = Binder.clearCallingIdentity();
1969 try {
1970 return getNetworkQuotaInfoUnchecked(state);
1971 } finally {
1972 Binder.restoreCallingIdentity(token);
1973 }
1974 }
1975
1976 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1977 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1978
1979 final NetworkPolicy policy;
1980 synchronized (mRulesLock) {
1981 policy = findPolicyForNetworkLocked(ident);
1982 }
1983
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001984 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001985 // missing policy means we can't derive useful quota info
1986 return null;
1987 }
1988
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001989 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001990
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001991 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001992 final long start = computeLastCycleBoundary(currentTime, policy);
1993 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001994 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001995
1996 // report soft and hard limits under policy
1997 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1998 : NetworkQuotaInfo.NO_LIMIT;
1999 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2000 : NetworkQuotaInfo.NO_LIMIT;
2001
2002 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2003 }
2004
Jeff Sharkey46645002011-07-27 21:11:21 -07002005 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002006 public boolean isNetworkMetered(NetworkState state) {
2007 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2008
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002009 // roaming networks are always considered metered
2010 if (ident.getRoaming()) {
2011 return true;
2012 }
2013
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002014 final NetworkPolicy policy;
2015 synchronized (mRulesLock) {
2016 policy = findPolicyForNetworkLocked(ident);
2017 }
2018
2019 if (policy != null) {
2020 return policy.metered;
2021 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002022 if (state.networkInfo == null) {
2023 return false;
2024 }
2025
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002026 final int type = state.networkInfo.getType();
2027 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2028 return true;
2029 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002030 return false;
2031 }
2032 }
2033
2034 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002035 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002036 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002037
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002038 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2039
Dianne Hackborn497175b2014-07-01 12:56:08 -07002040 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002041 for (String arg : args) {
2042 argSet.add(arg);
2043 }
2044
Jeff Sharkey1b861272011-05-22 00:34:52 -07002045 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002046 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002047 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2048 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002049 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002050
Jeff Sharkey32566012014-12-02 18:30:14 -08002051 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002052 updateNetworkEnabledLocked();
2053 updateNetworkRulesLocked();
2054 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002055 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002056
2057 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002058 return;
2059 }
2060
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002061 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002062 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002063 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002064 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002065 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002066 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002067 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2068 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002069 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002070 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002071
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002072 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2073
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002074 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002075 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002076 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002077 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002078 final int uid = mUidPolicy.keyAt(i);
2079 final int policy = mUidPolicy.valueAt(i);
2080 fout.print("UID=");
2081 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002082 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002083 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002084 fout.println();
2085 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002086 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002087
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002088 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2089 if (size > 0) {
2090 fout.println("Power save whitelist (except idle) app ids:");
2091 fout.increaseIndent();
2092 for (int i = 0; i < size; i++) {
2093 fout.print("UID=");
2094 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2095 fout.print(": ");
2096 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2097 fout.println();
2098 }
2099 fout.decreaseIndent();
2100 }
2101
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002102 size = mPowerSaveWhitelistAppIds.size();
2103 if (size > 0) {
2104 fout.println("Power save whitelist app ids:");
2105 fout.increaseIndent();
2106 for (int i = 0; i < size; i++) {
2107 fout.print("UID=");
2108 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2109 fout.print(": ");
2110 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2111 fout.println();
2112 }
2113 fout.decreaseIndent();
2114 }
2115
Felipe Lemeb85a6372016-01-14 16:16:16 -08002116 size = mRestrictBackgroundWhitelistUids.size();
2117 if (size > 0) {
2118 fout.println("Restrict background whitelist uids:");
2119 fout.increaseIndent();
2120 for (int i = 0; i < size; i++) {
2121 fout.print("UID=");
2122 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2123 fout.println();
2124 }
2125 fout.decreaseIndent();
2126 }
2127
Jeff Sharkey1b861272011-05-22 00:34:52 -07002128 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002129 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002130 collectKeys(mUidRules, knownUids);
2131
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002132 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002133 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002134 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002135 for (int i = 0; i < size; i++) {
2136 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002137 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002138 fout.print(uid);
2139
Jeff Sharkeydc988062015-09-14 10:09:47 -07002140 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002141 fout.print(" state=");
2142 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002143 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002144
Jeff Sharkeydc988062015-09-14 10:09:47 -07002145 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2146 fout.print(" rule=");
2147 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002148
2149 fout.println();
2150 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002151 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002152 }
2153 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002154
2155 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002156 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2157 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002158 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002159 this, in, out, err, args, resultReceiver);
2160 }
2161
2162 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002163 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002164 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2165
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002166 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002167 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002168 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002169 }
2170
Dianne Hackborn497175b2014-07-01 12:56:08 -07002171 boolean isUidForegroundLocked(int uid) {
2172 // only really in foreground when screen is also on
2173 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002174 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002175 }
2176
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002177 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002178 * Process state of UID changed; if needed, will trigger
2179 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002180 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002181 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002182 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2183 if (oldUidState != uidState) {
2184 // state changed, push updated rules
2185 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002186 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002187 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2188 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002189 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002190 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002191 }
2192 }
2193
2194 void removeUidStateLocked(int uid) {
2195 final int index = mUidState.indexOfKey(uid);
2196 if (index >= 0) {
2197 final int oldUidState = mUidState.valueAt(index);
2198 mUidState.removeAt(index);
2199 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2200 updateRulesForUidStateChangeLocked(uid, oldUidState,
2201 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002202 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002203 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002204 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002205 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002206 }
2207 }
2208
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002209 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002210 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2211 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002212 if (oldForeground != newForeground) {
2213 updateRulesForUidLocked(uid);
2214 }
2215 }
2216
Jeff Sharkeya4620792011-05-20 15:29:23 -07002217 private void updateScreenOn() {
2218 synchronized (mRulesLock) {
2219 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002220 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002221 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002222 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002223 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002224 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002225 }
2226 }
2227
2228 /**
2229 * Update rules that might be changed by {@link #mScreenOn} value.
2230 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002231 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002232 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002233 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002234 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002235 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002236 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002237 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002238 }
2239 }
2240 }
2241
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002242 static boolean isProcStateAllowedWhileIdle(int procState) {
2243 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2244 }
2245
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002246 void updateRulesForDeviceIdleLocked() {
2247 if (mDeviceIdleMode) {
2248 // sync the whitelists before enable dozable chain. We don't care about the rules if
2249 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002250 final SparseIntArray uidRules = mUidFirewallDozableRules;
2251 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002252 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002253 for (int ui = users.size() - 1; ui >= 0; ui--) {
2254 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002255 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002256 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2257 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2258 int uid = UserHandle.getUid(user.id, appId);
2259 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2260 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002261 }
2262 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2263 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2264 int uid = UserHandle.getUid(user.id, appId);
2265 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2266 }
2267 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002268 for (int i = mUidState.size() - 1; i >= 0; i--) {
2269 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2270 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2271 }
2272 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002273 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2274 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002275
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002276 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2277 }
2278
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002279 void updateRuleForDeviceIdleLocked(int uid) {
2280 if (mDeviceIdleMode) {
2281 int appId = UserHandle.getAppId(uid);
2282 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2283 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2284 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2285 } else {
2286 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2287 }
2288 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002289
2290 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002291 }
2292
2293 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002294 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2295 uidRules.clear();
2296
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002297 // Fully update the app idle firewall chain.
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002298 final IPackageManager ipm = AppGlobals.getPackageManager();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002299 final List<UserInfo> users = mUserManager.getUsers();
2300 for (int ui = users.size() - 1; ui >= 0; ui--) {
2301 UserInfo user = users.get(ui);
2302 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2303 for (int uid : idleUids) {
2304 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002305 // quick check: if this uid doesn't have INTERNET permission, it
2306 // doesn't have network access anyway, so it is a waste to mess
2307 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002308 if (hasInternetPermissions(uid)) {
2309 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002310 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002311 }
2312 }
2313 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002314
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002315 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2316 }
2317
2318 void updateRuleForAppIdleLocked(int uid) {
2319 if (!isUidValidForRules(uid)) return;
2320
2321 int appId = UserHandle.getAppId(uid);
2322 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2323 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2324 } else {
2325 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2326 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002327
2328 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002329 }
2330
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002331 void updateRulesForAppIdleParoleLocked() {
2332 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2333 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002334 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002335 }
2336
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002337 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002338 * Update rules that might be changed by {@link #mRestrictBackground},
2339 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002340 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002341 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002342 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002343
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002344 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002345 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002346
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002347 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002348 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002349 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002350 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2351 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002352
2353 for (UserInfo user : users) {
2354 for (ApplicationInfo app : apps) {
2355 final int uid = UserHandle.getUid(user.id, app.uid);
2356 updateRulesForUidLocked(uid);
2357 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002358 }
2359
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002360 // limit data usage for some internal system services
2361 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2362 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002363
2364 // If the set of restricted networks may have changed, re-evaluate those.
2365 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002366 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002367 updateNetworkRulesLocked();
2368 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002369 }
2370
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002371 void updateRulesForTempWhitelistChangeLocked() {
2372 final List<UserInfo> users = mUserManager.getUsers();
2373 for (UserInfo user : users) {
2374 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2375 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2376 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002377 updateRuleForAppIdleLocked(uid);
2378 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002379 }
2380 }
2381 }
2382
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002383 private static boolean isUidValidForRules(int uid) {
2384 // allow rules on specific system services, and any apps
2385 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002386 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002387 return true;
2388 }
2389
2390 return false;
2391 }
2392
Amith Yamasani15e472352015-04-24 19:06:07 -07002393 private boolean isUidIdle(int uid) {
2394 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2395 final int userId = UserHandle.getUserId(uid);
2396
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002397 if (!ArrayUtils.isEmpty(packages)) {
2398 for (String packageName : packages) {
2399 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2400 return false;
2401 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002402 }
2403 }
2404 return true;
2405 }
2406
Jeff Sharkeydc988062015-09-14 10:09:47 -07002407 void updateRulesForUidsLocked(SparseIntArray uids) {
2408 for (int i = 0; i < uids.size(); i++) {
2409 updateRulesForUidLocked(uids.keyAt(i));
2410 }
2411 }
2412
Amith Yamasani15e472352015-04-24 19:06:07 -07002413 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002414 * Checks if an uid has INTERNET permissions.
2415 * <p>
2416 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002417 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002418 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002419 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002420 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002421 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002422 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002423 }
2424 } catch (RemoteException e) {
2425 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002426 return true;
2427 }
2428
2429 /**
2430 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2431 * @param uid The uid for which to apply the latest policy
2432 */
2433 void updateRulesForUidLocked(int uid) {
2434 if (!isUidValidForRules(uid) || !hasInternetPermissions(uid)) return;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002435
Dianne Hackborn497175b2014-07-01 12:56:08 -07002436 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2437 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002438
Jeff Sharkeydc988062015-09-14 10:09:47 -07002439 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002440 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002441 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002442 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002443 // uid in background, and policy says to block metered data
2444 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002445 } else if (mRestrictBackground) {
2446 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002447 // uid in background, global background disabled, and this uid is not on the white
2448 // list of those allowed background access while global background is disabled
2449 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2450 uidRules = RULE_REJECT_METERED;
2451 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002452 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002453 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002454 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002455 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002456 if (!whitelisted && !uidForeground
2457 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2458 // uid is in background, restrict power use mode is on (so we want to
2459 // restrict all background network access), and this uid is not on the
2460 // white list of those allowed background access.
2461 uidRules = RULE_REJECT_METERED;
2462 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002463 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002464
Jeff Sharkeydc988062015-09-14 10:09:47 -07002465 // Check dozable state, which is whitelist
2466 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2467 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2468 uidRules = RULE_REJECT_ALL;
2469 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002470
Jeff Sharkeydc988062015-09-14 10:09:47 -07002471 // Check standby state, which is blacklist
2472 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2473 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2474 uidRules = RULE_REJECT_ALL;
2475 }
2476
2477 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002478 if (uidRules == RULE_ALLOW_ALL) {
2479 mUidRules.delete(uid);
2480 } else {
2481 mUidRules.put(uid, uidRules);
2482 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002483
Jeff Sharkeydc988062015-09-14 10:09:47 -07002484 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2485 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002486
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002487 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002488 if (oldRules != uidRules) {
2489 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2490 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002491
2492 try {
2493 // adjust stats accounting based on foreground status
2494 mNetworkStats.setUidForeground(uid, uidForeground);
2495 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002496 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002497 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002498 }
2499
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002500 private class AppIdleStateChangeListener
2501 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2502
2503 @Override
2504 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2505 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002506 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2507 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002508 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002509 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002510 }
2511 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002512 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002513 }
2514
2515 @Override
2516 public void onParoleStateChanged(boolean isParoleOn) {
2517 synchronized (mRulesLock) {
2518 updateRulesForAppIdleParoleLocked();
2519 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002520 }
2521 }
2522
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002523 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002524 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002525 public boolean handleMessage(Message msg) {
2526 switch (msg.what) {
2527 case MSG_RULES_CHANGED: {
2528 final int uid = msg.arg1;
2529 final int uidRules = msg.arg2;
2530 final int length = mListeners.beginBroadcast();
2531 for (int i = 0; i < length; i++) {
2532 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2533 if (listener != null) {
2534 try {
2535 listener.onUidRulesChanged(uid, uidRules);
2536 } catch (RemoteException e) {
2537 }
2538 }
2539 }
2540 mListeners.finishBroadcast();
2541 return true;
2542 }
2543 case MSG_METERED_IFACES_CHANGED: {
2544 final String[] meteredIfaces = (String[]) msg.obj;
2545 final int length = mListeners.beginBroadcast();
2546 for (int i = 0; i < length; i++) {
2547 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2548 if (listener != null) {
2549 try {
2550 listener.onMeteredIfacesChanged(meteredIfaces);
2551 } catch (RemoteException e) {
2552 }
2553 }
2554 }
2555 mListeners.finishBroadcast();
2556 return true;
2557 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002558 case MSG_LIMIT_REACHED: {
2559 final String iface = (String) msg.obj;
2560
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002561 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002562 synchronized (mRulesLock) {
2563 if (mMeteredIfaces.contains(iface)) {
2564 try {
2565 // force stats update to make sure we have
2566 // numbers that caused alert to trigger.
2567 mNetworkStats.forceUpdate();
2568 } catch (RemoteException e) {
2569 // ignored; service lives in system_server
2570 }
2571
2572 updateNetworkEnabledLocked();
2573 updateNotificationsLocked();
2574 }
2575 }
2576 return true;
2577 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002578 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2579 final boolean restrictBackground = msg.arg1 != 0;
2580 final int length = mListeners.beginBroadcast();
2581 for (int i = 0; i < length; i++) {
2582 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2583 if (listener != null) {
2584 try {
2585 listener.onRestrictBackgroundChanged(restrictBackground);
2586 } catch (RemoteException e) {
2587 }
2588 }
2589 }
2590 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002591 final Intent intent =
2592 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2593 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2594 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2595 return true;
2596 }
2597 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2598 final int uid = msg.arg1;
2599 final PackageManager pm = mContext.getPackageManager();
2600 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme86e5a012016-02-16 16:26:05 -08002601 if (packages != null) {
2602 final int userId = UserHandle.getUserId(uid);
2603 for (String packageName : packages) {
2604 final Intent intent = new Intent(
2605 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2606 intent.setPackage(packageName);
2607 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2608 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2609 }
2610 } else {
2611 Slog.w(TAG, "no packages for uid " + uid);
Felipe Leme9778f762016-01-27 14:46:39 -08002612 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002613 return true;
2614 }
2615 case MSG_ADVISE_PERSIST_THRESHOLD: {
2616 final long lowestRule = (Long) msg.obj;
2617 try {
2618 // make sure stats are recorded frequently enough; we aim
2619 // for 2MB threshold for 2GB/month rules.
2620 final long persistThreshold = lowestRule / 1000;
2621 mNetworkStats.advisePersistThreshold(persistThreshold);
2622 } catch (RemoteException e) {
2623 // ignored; service lives in system_server
2624 }
2625 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002626 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002627 case MSG_SCREEN_ON_CHANGED: {
2628 updateScreenOn();
2629 return true;
2630 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002631 default: {
2632 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002633 }
2634 }
2635 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002636 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002637
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002638 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002639 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002640 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002641 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002642 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002643 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002644 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002645 }
2646 }
2647
2648 private void removeInterfaceQuota(String iface) {
2649 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002650 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002651 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002652 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002653 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002654 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002655 }
2656 }
2657
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002658 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2659 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002660 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002661 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002662 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002663 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002664 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002665 }
2666 }
2667
Amith Yamasani15e472352015-04-24 19:06:07 -07002668 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002669 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2670 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2671 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002672 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002673 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002674 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002675 int size = uidRules.size();
2676 int[] uids = new int[size];
2677 int[] rules = new int[size];
2678 for(int index = size - 1; index >= 0; --index) {
2679 uids[index] = uidRules.keyAt(index);
2680 rules[index] = uidRules.valueAt(index);
2681 }
2682 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002683 } catch (IllegalStateException e) {
2684 Log.wtf(TAG, "problem setting firewall uid rules", e);
2685 } catch (RemoteException e) {
2686 // ignored; service lives in system_server
2687 }
2688 }
2689
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002690 /**
2691 * Add or remove a uid to the firewall blacklist for all network ifaces.
2692 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002693 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002694 if (chain == FIREWALL_CHAIN_DOZABLE) {
2695 mUidFirewallDozableRules.put(uid, rule);
2696 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2697 mUidFirewallStandbyRules.put(uid, rule);
2698 }
2699
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002700 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002701 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002702 } catch (IllegalStateException e) {
2703 Log.wtf(TAG, "problem setting firewall uid rules", e);
2704 } catch (RemoteException e) {
2705 // ignored; service lives in system_server
2706 }
2707 }
2708
2709 /**
2710 * Add or remove a uid to the firewall blacklist for all network ifaces.
2711 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002712 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002713 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2714 mFirewallChainStates.get(chain) == enable) {
2715 // All is the same, nothing to do.
2716 return;
2717 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002718 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002719 try {
2720 mNetworkManager.setFirewallChainEnabled(chain, enable);
2721 } catch (IllegalStateException e) {
2722 Log.wtf(TAG, "problem enable firewall chain", e);
2723 } catch (RemoteException e) {
2724 // ignored; service lives in system_server
2725 }
2726 }
2727
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002728 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2729 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002730 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002731 } catch (RuntimeException e) {
2732 Slog.w(TAG, "problem reading network stats: " + e);
2733 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002734 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002735 // ignored; service lives in system_server
2736 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002737 }
2738 }
2739
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002740 private boolean isBandwidthControlEnabled() {
2741 final long token = Binder.clearCallingIdentity();
2742 try {
2743 return mNetworkManager.isBandwidthControlEnabled();
2744 } catch (RemoteException e) {
2745 // ignored; service lives in system_server
2746 return false;
2747 } finally {
2748 Binder.restoreCallingIdentity(token);
2749 }
2750 }
2751
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002752 /**
2753 * Try refreshing {@link #mTime} when stale.
2754 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002755 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002756 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002757 mTime.forceRefresh();
2758 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002759 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002760
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002761 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002762 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2763 }
2764
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002765 private static Intent buildAllowBackgroundDataIntent() {
2766 return new Intent(ACTION_ALLOW_BACKGROUND);
2767 }
2768
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002769 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2770 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2771 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2772 return intent;
2773 }
2774
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002775 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2776 final Intent intent = new Intent();
2777 intent.setComponent(new ComponentName(
2778 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2779 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2780 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2781 return intent;
2782 }
2783
2784 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2785 final Intent intent = new Intent();
2786 intent.setComponent(new ComponentName(
2787 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2788 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2789 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2790 return intent;
2791 }
2792
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002793 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002794 public void addIdleHandler(IdleHandler handler) {
2795 mHandler.getLooper().getQueue().addIdleHandler(handler);
2796 }
2797
Jeff Sharkey1b861272011-05-22 00:34:52 -07002798 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2799 final int size = source.size();
2800 for (int i = 0; i < size; i++) {
2801 target.put(source.keyAt(i), true);
2802 }
2803 }
2804
Stuart Scottf1fb3972015-04-02 18:00:02 -07002805 @Override
2806 public void factoryReset(String subscriber) {
2807 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2808
Stuart Scotte3e314d2015-04-20 14:07:45 -07002809 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2810 return;
2811 }
2812
Stuart Scottf1fb3972015-04-02 18:00:02 -07002813 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002814 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002815 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2816 for (NetworkPolicy policy : policies) {
2817 if (policy.template.equals(template)) {
2818 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2819 policy.inferred = false;
2820 policy.clearSnooze();
2821 }
2822 }
2823 setNetworkPolicies(policies);
2824
2825 // Turn restrict background data off
2826 setRestrictBackground(false);
2827
Stuart Scotte3e314d2015-04-20 14:07:45 -07002828 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2829 // Remove app's "restrict background data" flag
2830 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2831 setUidPolicy(uid, POLICY_NONE);
2832 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002833 }
2834 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002835
2836 private class MyPackageMonitor extends PackageMonitor {
2837
2838 @Override
2839 public void onPackageRemoved(String packageName, int uid) {
2840 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2841 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002842 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002843 }
2844 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002845 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002846}