blob: 24bb845de4277b1f5d50d78fc4fd97218b7b867b [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 Sharkey3a844fc2011-08-16 14:37:57 -0700243 private static final String TAG_ALLOW_BACKGROUND = TAG + ":allowBackground";
244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800246 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800248 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700249
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700250 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
251
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700252 private static final int MSG_RULES_CHANGED = 1;
253 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800254 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800255 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700256 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700257 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800258 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700259
Jeff Sharkey75279902011-05-24 18:39:45 -0700260 private final Context mContext;
261 private final IActivityManager mActivityManager;
262 private final IPowerManager mPowerManager;
263 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700264 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700265 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700267 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
269 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700270 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700271 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700272 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700273
Dianne Hackborn497175b2014-07-01 12:56:08 -0700274 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700275
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700276 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700277 volatile boolean mScreenOn;
278 volatile boolean mRestrictBackground;
279 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700280 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700281
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700282 private final boolean mSuppressDefaultPolicy;
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800285 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800287 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700288
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700289 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700290 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700291 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700293
Jeff Sharkeydc988062015-09-14 10:09:47 -0700294 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
295 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
296
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700297 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700298 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
299
Jeff Sharkey32566012014-12-02 18:30:14 -0800300 /**
301 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700302 * in power save mode, except device idle (doze) still applies.
303 * TODO: An int array might be sufficient
304 */
305 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
306
307 /**
308 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800309 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700310 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800311 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700312 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700313
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700314 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
315
Felipe Lemeb85a6372016-01-14 16:16:16 -0800316 /**
317 * UIDs that have been white-listed to avoid restricted background.
318 */
319 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
320
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700321 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700323 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800324 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700325
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700327 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700328
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700329 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800330 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700331
Jeff Sharkey32566012014-12-02 18:30:14 -0800332 private final RemoteCallbackList<INetworkPolicyListener>
333 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700334
Dianne Hackborn497175b2014-07-01 12:56:08 -0700335 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700336
337 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700338
Svet Ganov16a16892015-04-16 10:32:04 -0700339 private final AppOpsManager mAppOps;
340
Felipe Lemeb85a6372016-01-14 16:16:16 -0800341 private final MyPackageMonitor mPackageMonitor;
342
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);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700372
Amith Yamasani450a16b2013-09-18 16:28:50 -0700373 HandlerThread thread = new HandlerThread(TAG);
374 thread.start();
375 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700376
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700377 mSuppressDefaultPolicy = suppressDefaultPolicy;
378
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700379 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700380
381 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800382
383 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700384 }
385
386 public void bindConnectivityManager(IConnectivityManager connManager) {
387 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700388 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700389
Jeff Sharkey497e4432011-06-14 17:27:29 -0700390 public void bindNotificationManager(INotificationManager notifManager) {
391 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
392 }
393
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700394 void updatePowerSaveWhitelistLocked() {
395 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700396 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
397 mPowerSaveWhitelistExceptIdleAppIds.clear();
398 if (whitelist != null) {
399 for (int uid : whitelist) {
400 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
401 }
402 }
403 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700404 mPowerSaveWhitelistAppIds.clear();
405 if (whitelist != null) {
406 for (int uid : whitelist) {
407 mPowerSaveWhitelistAppIds.put(uid, true);
408 }
409 }
410 } catch (RemoteException e) {
411 }
412 }
413
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700414 void updatePowerSaveTempWhitelistLocked() {
415 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700416 // Clear the states of the current whitelist
417 final int N = mPowerSaveTempWhitelistAppIds.size();
418 for (int i = 0; i < N; i++) {
419 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
420 }
421 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700422 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700423 if (whitelist != null) {
424 for (int uid : whitelist) {
425 mPowerSaveTempWhitelistAppIds.put(uid, true);
426 }
427 }
428 } catch (RemoteException e) {
429 }
430 }
431
Amith Yamasani06f08062015-06-12 13:23:33 -0700432 /**
433 * Remove unnecessary entries in the temp whitelist
434 */
435 void purgePowerSaveTempWhitelistLocked() {
436 final int N = mPowerSaveTempWhitelistAppIds.size();
437 for (int i = N - 1; i >= 0; i--) {
438 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
439 mPowerSaveTempWhitelistAppIds.removeAt(i);
440 }
441 }
442 }
443
Jeff Sharkeya4620792011-05-20 15:29:23 -0700444 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700445 if (!isBandwidthControlEnabled()) {
446 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
447 return;
448 }
449
Amith Yamasani15e472352015-04-24 19:06:07 -0700450 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
451
Felipe Lemeb85a6372016-01-14 16:16:16 -0800452 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
453
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700454 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700455 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700456 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
457 mPowerManagerInternal.registerLowPowerModeObserver(
458 new PowerManagerInternal.LowPowerModeListener() {
459 @Override
460 public void onLowPowerModeChanged(boolean enabled) {
461 synchronized (mRulesLock) {
462 if (mRestrictPower != enabled) {
463 mRestrictPower = enabled;
464 updateRulesForGlobalChangeLocked(true);
465 }
466 }
467 }
468 });
469 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700470 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700471
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700472 // read policy from disk
473 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700474
Jeff Sharkeydc988062015-09-14 10:09:47 -0700475 updateRulesForGlobalChangeLocked(false);
476 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700477 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700478
Jeff Sharkeya4620792011-05-20 15:29:23 -0700479 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700480
Jeff Sharkeya4620792011-05-20 15:29:23 -0700481 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700482 mActivityManager.registerUidObserver(mUidObserver,
483 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700484 mNetworkManager.registerObserver(mAlertObserver);
485 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700486 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700487 }
488
Jeff Sharkeya4620792011-05-20 15:29:23 -0700489 // TODO: traverse existing processes to know foreground state, or have
490 // activitymanager dispatch current state when new observer attached.
491
492 final IntentFilter screenFilter = new IntentFilter();
493 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
494 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700495 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700496
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700497 // listen for changes to power save whitelist
498 final IntentFilter whitelistFilter = new IntentFilter(
499 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
500 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
501
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700502 DeviceIdleController.LocalService deviceIdleService
503 = LocalServices.getService(DeviceIdleController.LocalService.class);
504 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
505
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900507 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700508 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700510 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700511 final IntentFilter packageFilter = new IntentFilter();
512 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700513 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700514 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700515
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700516 // listen for UID changes to update policy
517 mContext.registerReceiver(
518 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
519
520 // listen for user changes to update policy
521 final IntentFilter userFilter = new IntentFilter();
522 userFilter.addAction(ACTION_USER_ADDED);
523 userFilter.addAction(ACTION_USER_REMOVED);
524 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
525
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700526 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700527 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
528 mContext.registerReceiver(
529 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
530
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700531 // listen for restrict background changes from notifications
532 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
533 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
534
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800535 // listen for snooze warning from notifications
536 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
537 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
538 MANAGE_NETWORK_POLICY, mHandler);
539
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700540 // listen for configured wifi networks to be removed
541 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700542 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700543
544 // listen for wifi state changes to catch metered hint
545 final IntentFilter wifiStateFilter = new IntentFilter(
546 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700547 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700548
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700549 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700550
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700551 }
552
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700553 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700554 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700555 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700556 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700557 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700558 }
559
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700560 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700561 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700562 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700563 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700564 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700565
566 @Override public void onUidActive(int uid) throws RemoteException {
567 }
568
569 @Override public void onUidIdle(int uid) throws RemoteException {
570 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700571 };
572
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700573 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700574 @Override
575 public void onReceive(Context context, Intent intent) {
576 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
577 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700578 updatePowerSaveWhitelistLocked();
579 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700580 }
581 }
582 };
583
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700584 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
585 @Override
586 public void run() {
587 synchronized (mRulesLock) {
588 updatePowerSaveTempWhitelistLocked();
589 updateRulesForTempWhitelistChangeLocked();
590 purgePowerSaveTempWhitelistLocked();
591 }
592 }
593 };
594
595 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700596 @Override
597 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800598 // screen-related broadcasts are protected by system, no need
599 // for permissions check.
600 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700601 }
602 };
603
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700604 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700605 @Override
606 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700607 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700608
609 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700610 final int uid = intent.getIntExtra(EXTRA_UID, -1);
611 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700612
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700613 if (ACTION_PACKAGE_ADDED.equals(action)) {
614 // update rules for UID, since it might be subject to
615 // global background data policy
616 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
617 synchronized (mRulesLock) {
618 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700619 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700620 }
621 }
622 };
623
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700624 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700625 @Override
626 public void onReceive(Context context, Intent intent) {
627 // on background handler thread, and UID_REMOVED is protected
628
629 final int uid = intent.getIntExtra(EXTRA_UID, -1);
630 if (uid == -1) return;
631
632 // remove any policy and update rules to clean up
633 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
634 synchronized (mRulesLock) {
635 mUidPolicy.delete(uid);
636 updateRulesForUidLocked(uid);
637 writePolicyLocked();
638 }
639 }
640 };
641
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700642 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700643 @Override
644 public void onReceive(Context context, Intent intent) {
645 // on background handler thread, and USER_ADDED and USER_REMOVED
646 // broadcasts are protected
647
648 final String action = intent.getAction();
649 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
650 if (userId == -1) return;
651
Amith Yamasani15e472352015-04-24 19:06:07 -0700652 switch (action) {
653 case ACTION_USER_REMOVED:
654 case ACTION_USER_ADDED:
655 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800656 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700657 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800658 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700659 // Update global restrict for new user
660 updateRulesForGlobalChangeLocked(true);
661 }
662 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700663 }
664 }
665 };
666
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700667 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700668 * Receiver that watches for {@link INetworkStatsService} updates, which we
669 * use to check against {@link NetworkPolicy#warningBytes}.
670 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700671 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700672 @Override
673 public void onReceive(Context context, Intent intent) {
674 // on background handler thread, and verified
675 // READ_NETWORK_USAGE_HISTORY permission above.
676
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800677 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700678 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700679 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700680 updateNotificationsLocked();
681 }
682 }
683 };
684
685 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700686 * Receiver that watches for {@link Notification} control of
687 * {@link #mRestrictBackground}.
688 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700689 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700690 @Override
691 public void onReceive(Context context, Intent intent) {
692 // on background handler thread, and verified MANAGE_NETWORK_POLICY
693 // permission above.
694
695 setRestrictBackground(false);
696 }
697 };
698
699 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800700 * Receiver that watches for {@link Notification} control of
701 * {@link NetworkPolicy#lastWarningSnooze}.
702 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700703 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800704 @Override
705 public void onReceive(Context context, Intent intent) {
706 // on background handler thread, and verified MANAGE_NETWORK_POLICY
707 // permission above.
708
709 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
710 performSnooze(template, TYPE_WARNING);
711 }
712 };
713
714 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700715 * Receiver that watches for {@link WifiConfiguration} to be changed.
716 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700717 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700718 @Override
719 public void onReceive(Context context, Intent intent) {
720 // on background handler thread, and verified CONNECTIVITY_INTERNAL
721 // permission above.
722
723 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
724 if (reason == CHANGE_REASON_REMOVED) {
725 final WifiConfiguration config = intent.getParcelableExtra(
726 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700727 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800728 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700729 synchronized (mRulesLock) {
730 if (mNetworkPolicy.containsKey(template)) {
731 mNetworkPolicy.remove(template);
732 writePolicyLocked();
733 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700734 }
735 }
736 }
737 }
738 };
739
740 /**
741 * Receiver that watches {@link WifiInfo} state changes to infer metered
742 * state. Ignores hints when policy is user-defined.
743 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700744 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700745 @Override
746 public void onReceive(Context context, Intent intent) {
747 // on background handler thread, and verified CONNECTIVITY_INTERNAL
748 // permission above.
749
750 // ignore when not connected
751 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
752 if (!netInfo.isConnected()) return;
753
754 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
755 final boolean meteredHint = info.getMeteredHint();
756
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800757 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700758 synchronized (mRulesLock) {
759 NetworkPolicy policy = mNetworkPolicy.get(template);
760 if (policy == null && meteredHint) {
761 // policy doesn't exist, and AP is hinting that it's
762 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800763 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700764 addNetworkPolicyLocked(policy);
765
766 } else if (policy != null && policy.inferred) {
767 // policy exists, and was inferred: update its current
768 // metered state.
769 policy.metered = meteredHint;
770
771 // since this is inferred for each wifi session, just update
772 // rules without persisting.
773 updateNetworkRulesLocked();
774 }
775 }
776 }
777 };
778
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800779 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
780 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
781 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
782 metered, true);
783 }
784
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700785 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700786 * Observer that watches for {@link INetworkManagementService} alerts.
787 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700788 final private INetworkManagementEventObserver mAlertObserver
789 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700790 @Override
791 public void limitReached(String limitName, String iface) {
792 // only someone like NMS should be calling us
793 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
794
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800795 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
796 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700797 }
798 }
799 };
800
801 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
803 * to show visible notifications as needed.
804 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700805 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
807
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700808 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700809 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700810 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700811
812 // TODO: when switching to kernel notifications, compute next future
813 // cycle boundary to recompute notifications.
814
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700815 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800816 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700817 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
818 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700819 // ignore policies that aren't relevant to user
820 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700821 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700822
Jeff Sharkey497e4432011-06-14 17:27:29 -0700823 final long start = computeLastCycleBoundary(currentTime, policy);
824 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700825 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700826
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700827 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800828 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700829 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
830 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700831 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
832 notifyOverLimitLocked(policy.template);
833 }
834
Jeff Sharkey497e4432011-06-14 17:27:29 -0700835 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700836 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700837
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800838 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700839 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700840 }
841 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700842 }
843
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700844 // ongoing notification when restricting background data
845 if (mRestrictBackground) {
846 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700847 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700848
849 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700850 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
851 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700852 if (!mActiveNotifs.contains(tag)) {
853 cancelNotification(tag);
854 }
855 }
856 }
857
858 /**
859 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700860 * current device state, such as when
861 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
862 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700863 */
864 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 if (template.isMatchRuleMobile()) {
866 final TelephonyManager tele = TelephonyManager.from(mContext);
867 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700868
Jeff Sharkey32566012014-12-02 18:30:14 -0800869 // Mobile template is relevant when any active subscriber matches
870 final int[] subIds = sub.getActiveSubscriptionIdList();
871 for (int subId : subIds) {
872 final String subscriberId = tele.getSubscriberId(subId);
873 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
874 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
875 if (template.matches(probeIdent)) {
876 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700877 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800878 }
879 return false;
880 } else {
881 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700882 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700883 }
884
885 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700886 * Notify that given {@link NetworkTemplate} is over
887 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
888 */
889 private void notifyOverLimitLocked(NetworkTemplate template) {
890 if (!mOverLimitNotified.contains(template)) {
891 mContext.startActivity(buildNetworkOverLimitIntent(template));
892 mOverLimitNotified.add(template);
893 }
894 }
895
896 private void notifyUnderLimitLocked(NetworkTemplate template) {
897 mOverLimitNotified.remove(template);
898 }
899
900 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700901 * Build unique tag that identifies an active {@link NetworkPolicy}
902 * notification of a specific type, like {@link #TYPE_LIMIT}.
903 */
904 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700905 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700906 }
907
908 /**
909 * Show notification for combined {@link NetworkPolicy} and specific type,
910 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
911 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700912 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700913 final String tag = buildNotificationTag(policy, type);
914 final Notification.Builder builder = new Notification.Builder(mContext);
915 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800916 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700917 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200918 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700919
920 final Resources res = mContext.getResources();
921 switch (type) {
922 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700923 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700924 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700925
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700926 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 builder.setTicker(title);
928 builder.setContentTitle(title);
929 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700930
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800931 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
932 builder.setDeleteIntent(PendingIntent.getBroadcast(
933 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
934
935 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700936 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800937 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
938
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939 break;
940 }
941 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700942 final CharSequence body = res.getText(R.string.data_usage_limit_body);
943
944 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400945 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700946 switch (policy.template.getMatchRule()) {
947 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700948 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700949 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700950 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700951 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700952 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700953 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700954 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700955 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700956 case MATCH_WIFI:
957 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400958 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700959 break;
960 default:
961 title = null;
962 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 }
964
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800965 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400966 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700967 builder.setTicker(title);
968 builder.setContentTitle(title);
969 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700970
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700971 final Intent intent = buildNetworkOverLimitIntent(policy.template);
972 builder.setContentIntent(PendingIntent.getActivity(
973 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
974 break;
975 }
976 case TYPE_LIMIT_SNOOZED: {
977 final long overBytes = totalBytes - policy.limitBytes;
978 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
979 Formatter.formatFileSize(mContext, overBytes));
980
981 final CharSequence title;
982 switch (policy.template.getMatchRule()) {
983 case MATCH_MOBILE_3G_LOWER:
984 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
985 break;
986 case MATCH_MOBILE_4G:
987 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
988 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700989 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700990 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
991 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700992 case MATCH_WIFI:
993 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
994 break;
995 default:
996 title = null;
997 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 }
999
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001000 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001001 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001002 builder.setTicker(title);
1003 builder.setContentTitle(title);
1004 builder.setContentText(body);
1005
1006 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001007 builder.setContentIntent(PendingIntent.getActivity(
1008 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009 break;
1010 }
1011 }
1012
1013 // TODO: move to NotificationManager once we can mock it
1014 try {
1015 final String packageName = mContext.getPackageName();
1016 final int[] idReceived = new int[1];
1017 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001018 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001019 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001020 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001021 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001022 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 }
1024 }
1025
1026 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001027 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1028 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001030 private void enqueueRestrictedNotification(String tag) {
1031 final Resources res = mContext.getResources();
1032 final Notification.Builder builder = new Notification.Builder(mContext);
1033
1034 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1035 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1036
1037 builder.setOnlyAlertOnce(true);
1038 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001039 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001040 builder.setTicker(title);
1041 builder.setContentTitle(title);
1042 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001043 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001044 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001045
1046 final Intent intent = buildAllowBackgroundDataIntent();
1047 builder.setContentIntent(
1048 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049
1050 // TODO: move to NotificationManager once we can mock it
1051 try {
1052 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001053 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001054 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001055 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001056 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001057 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001058 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001059 }
1060 }
1061
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001062 private void cancelNotification(String tag) {
1063 // TODO: move to NotificationManager once we can mock it
1064 try {
1065 final String packageName = mContext.getPackageName();
1066 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001067 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001068 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001069 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 }
1071 }
1072
1073 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001074 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001075 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001076 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001077 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001078 @Override
1079 public void onReceive(Context context, Intent intent) {
1080 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1081 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001082
1083 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001084 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001085 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001086 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001087 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001088 updateNetworkRulesLocked();
1089 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001090 }
1091 }
1092 };
1093
1094 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001095 * Proactively control network data connections when they exceed
1096 * {@link NetworkPolicy#limitBytes}.
1097 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001098 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1100
1101 // TODO: reset any policy-disabled networks when any policy is removed
1102 // completely, which is currently rare case.
1103
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001104 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001105 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1106 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001107 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001108 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001109 setNetworkTemplateEnabled(policy.template, true);
1110 continue;
1111 }
1112
1113 final long start = computeLastCycleBoundary(currentTime, policy);
1114 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001116
1117 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001118 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1119 && policy.lastLimitSnooze < start;
1120 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001121
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001122 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001123 }
1124 }
1125
1126 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001127 * Proactively disable networks that match the given
1128 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 */
1130 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001131 // TODO: reach into ConnectivityManager to proactively disable bringing
1132 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 }
1134
1135 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136 * Examine all connected {@link NetworkState}, looking for
1137 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1138 * remaining quota based on usage cycle and historical stats.
1139 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001140 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001141 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001142
1143 final NetworkState[] states;
1144 try {
1145 states = mConnManager.getAllNetworkState();
1146 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001147 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001148 return;
1149 }
1150
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 // If we are in restrict power mode, we want to treat all interfaces
1152 // as metered, to restrict access to the network by uid. However, we
1153 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001154 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001155 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001156 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001157
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001158 // First, generate identities of all connected networks so we can
1159 // quickly compare them against all defined policies below.
1160 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001161 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001163 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001164 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001165
1166 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001167 if (baseIface != null) {
1168 connIdents.add(Pair.create(baseIface, ident));
1169 if (powerSave) {
1170 connIfaces.add(baseIface);
1171 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001172 }
1173
1174 // Stacked interfaces are considered to have same identity as
1175 // their parent network.
1176 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1177 for (LinkProperties stackedLink : stackedLinks) {
1178 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001179 if (stackedIface != null) {
1180 connIdents.add(Pair.create(stackedIface, ident));
1181 if (powerSave) {
1182 connIfaces.add(stackedIface);
1183 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001184 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001185 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001186 }
1187 }
1188
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001189 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001190 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001192 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001193 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001194
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001195 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001196 for (int j = connIdents.size() - 1; j >= 0; j--) {
1197 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1198 if (policy.template.matches(ident.second)) {
1199 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001200 }
1201 }
1202
1203 if (ifaceList.size() > 0) {
1204 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001205 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001206 }
1207 }
1208
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001209 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001210 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001211
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 // apply each policy that we found ifaces for; compute remaining data
1213 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001214 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001215 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1216 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1217 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001218
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001219 final long start;
1220 final long totalBytes;
1221 if (policy.hasCycle()) {
1222 start = computeLastCycleBoundary(currentTime, policy);
1223 totalBytes = getTotalBytes(policy.template, start, currentTime);
1224 } else {
1225 start = Long.MAX_VALUE;
1226 totalBytes = 0;
1227 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001228
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001229 if (LOGD) {
1230 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001231 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 }
1233
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001234 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001235 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001236 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001237 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001238 if (!hasLimit) {
1239 // metered network, but no policy limit; we still need to
1240 // restrict apps, so push really high quota.
1241 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001242 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001243 // snoozing past quota, but we still need to restrict apps,
1244 // so push really high quota.
1245 quotaBytes = Long.MAX_VALUE;
1246 } else {
1247 // remaining "quota" bytes are based on total usage in
1248 // current cycle. kernel doesn't like 0-byte rules, so we
1249 // set 1-byte quota and disable the radio later.
1250 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1251 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001252
1253 if (ifaces.length > 1) {
1254 // TODO: switch to shared quota once NMS supports
1255 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001256 }
1257
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001258 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001259 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001260 setInterfaceQuota(iface, quotaBytes);
1261 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001262 if (powerSave) {
1263 connIfaces.remove(iface);
1264 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001265 }
1266 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001267
1268 // keep track of lowest warning or limit of active policies
1269 if (hasWarning && policy.warningBytes < lowestRule) {
1270 lowestRule = policy.warningBytes;
1271 }
1272 if (hasLimit && policy.limitBytes < lowestRule) {
1273 lowestRule = policy.limitBytes;
1274 }
1275 }
1276
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001277 for (int i = connIfaces.size()-1; i >= 0; i--) {
1278 String iface = connIfaces.valueAt(i);
1279 removeInterfaceQuota(iface);
1280 setInterfaceQuota(iface, Long.MAX_VALUE);
1281 newMeteredIfaces.add(iface);
1282 }
1283
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001284 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001285
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001286 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001287 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1288 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001289 if (!newMeteredIfaces.contains(iface)) {
1290 removeInterfaceQuota(iface);
1291 }
1292 }
1293 mMeteredIfaces = newMeteredIfaces;
1294
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001295 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001296 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001297 }
1298
1299 /**
1300 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1301 * have at least a default mobile policy defined.
1302 */
1303 private void ensureActiveMobilePolicyLocked() {
1304 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001305 if (mSuppressDefaultPolicy) return;
1306
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001307 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001308 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001309
Jeff Sharkey32566012014-12-02 18:30:14 -08001310 final int[] subIds = sub.getActiveSubscriptionIdList();
1311 for (int subId : subIds) {
1312 final String subscriberId = tele.getSubscriberId(subId);
1313 ensureActiveMobilePolicyLocked(subscriberId);
1314 }
1315 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001316
Jeff Sharkey32566012014-12-02 18:30:14 -08001317 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1318 // Poke around to see if we already have a policy
1319 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1320 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1321 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1322 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1323 if (template.matches(probeIdent)) {
1324 if (LOGD) {
1325 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1326 + NetworkIdentity.scrubSubscriberId(subscriberId));
1327 }
1328 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001329 }
1330 }
1331
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1333 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001334
Jeff Sharkey32566012014-12-02 18:30:14 -08001335 // Build default mobile policy, and assume usage cycle starts today
1336 final long warningBytes = mContext.getResources().getInteger(
1337 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001338
Jeff Sharkey32566012014-12-02 18:30:14 -08001339 final Time time = new Time();
1340 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001341
Jeff Sharkey32566012014-12-02 18:30:14 -08001342 final int cycleDay = time.monthDay;
1343 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001344
Jeff Sharkey32566012014-12-02 18:30:14 -08001345 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1346 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1347 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1348 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001349 }
1350
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001351 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001352 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353
1354 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001355 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001356 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001357
1358 FileInputStream fis = null;
1359 try {
1360 fis = mPolicyFile.openRead();
1361 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001362 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363
1364 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001365 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001366 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001367 while ((type = in.next()) != END_DOCUMENT) {
1368 final String tag = in.getName();
1369 if (type == START_TAG) {
1370 if (TAG_POLICY_LIST.equals(tag)) {
1371 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001372 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1373 mRestrictBackground = readBooleanAttribute(
1374 in, ATTR_RESTRICT_BACKGROUND);
1375 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001376 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001377 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001378
1379 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1380 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1381 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001382 final String networkId;
1383 if (version >= VERSION_ADDED_NETWORK_ID) {
1384 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1385 } else {
1386 networkId = null;
1387 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001388 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001389 final String cycleTimezone;
1390 if (version >= VERSION_ADDED_TIMEZONE) {
1391 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1392 } else {
1393 cycleTimezone = Time.TIMEZONE_UTC;
1394 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1396 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001397 final long lastLimitSnooze;
1398 if (version >= VERSION_SPLIT_SNOOZE) {
1399 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1400 } else if (version >= VERSION_ADDED_SNOOZE) {
1401 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001402 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001403 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001404 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001405 final boolean metered;
1406 if (version >= VERSION_ADDED_METERED) {
1407 metered = readBooleanAttribute(in, ATTR_METERED);
1408 } else {
1409 switch (networkTemplate) {
1410 case MATCH_MOBILE_3G_LOWER:
1411 case MATCH_MOBILE_4G:
1412 case MATCH_MOBILE_ALL:
1413 metered = true;
1414 break;
1415 default:
1416 metered = false;
1417 }
1418 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001419 final long lastWarningSnooze;
1420 if (version >= VERSION_SPLIT_SNOOZE) {
1421 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1422 } else {
1423 lastWarningSnooze = SNOOZE_NEVER;
1424 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001425 final boolean inferred;
1426 if (version >= VERSION_ADDED_INFERRED) {
1427 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1428 } else {
1429 inferred = false;
1430 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001431
Jeff Sharkey32566012014-12-02 18:30:14 -08001432 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1433 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001434 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001435 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001436 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001438 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001439 final int uid = readIntAttribute(in, ATTR_UID);
1440 final int policy = readIntAttribute(in, ATTR_POLICY);
1441
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001442 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001443 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001444 } else {
1445 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1446 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001447 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001448 final int appId = readIntAttribute(in, ATTR_APP_ID);
1449 final int policy = readIntAttribute(in, ATTR_POLICY);
1450
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001451 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001452 // app policy is deprecated so this is only used in pre system user split.
1453 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001454 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001455 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001456 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001457 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001458 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001459 } else if (TAG_WHITELIST.equals(tag)) {
1460 insideWhitelist = true;
1461 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1462 final int uid = readIntAttribute(in, ATTR_UID);
1463 mRestrictBackgroundWhitelistUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001465 } else if (type == END_TAG) {
1466 if (TAG_WHITELIST.equals(tag)) {
1467 insideWhitelist = false;
1468 }
1469
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001470 }
1471 }
1472
1473 } catch (FileNotFoundException e) {
1474 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001475 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001477 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001479 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480 } finally {
1481 IoUtils.closeQuietly(fis);
1482 }
1483 }
1484
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001485 /**
1486 * Upgrade legacy background data flags, notifying listeners of one last
1487 * change to always-true.
1488 */
1489 private void upgradeLegacyBackgroundData() {
1490 mRestrictBackground = Settings.Secure.getInt(
1491 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1492
1493 // kick off one last broadcast if restricted
1494 if (mRestrictBackground) {
1495 final Intent broadcast = new Intent(
1496 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001497 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001498 }
1499 }
1500
Dianne Hackborn497175b2014-07-01 12:56:08 -07001501 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001502 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001503
1504 FileOutputStream fos = null;
1505 try {
1506 fos = mPolicyFile.startWrite();
1507
1508 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001509 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 out.startDocument(null, true);
1511
1512 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001513 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001514 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001515
1516 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001517 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1518 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001519 final NetworkTemplate template = policy.template;
1520
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001521 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001522 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1523 final String subscriberId = template.getSubscriberId();
1524 if (subscriberId != null) {
1525 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001526 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001527 final String networkId = template.getNetworkId();
1528 if (networkId != null) {
1529 out.attribute(null, ATTR_NETWORK_ID, networkId);
1530 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001532 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001533 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1534 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001535 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1536 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001537 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001538 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001539 out.endTag(null, TAG_NETWORK_POLICY);
1540 }
1541
1542 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001543 for (int i = 0; i < mUidPolicy.size(); i++) {
1544 final int uid = mUidPolicy.keyAt(i);
1545 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001546
Jeff Sharkey497e4432011-06-14 17:27:29 -07001547 // skip writing empty policies
1548 if (policy == POLICY_NONE) continue;
1549
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001550 out.startTag(null, TAG_UID_POLICY);
1551 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001552 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001553 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001554 }
1555
1556 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001557
1558 // write all whitelists
1559 out.startTag(null, TAG_WHITELIST);
1560
1561 // restrict background whitelist
1562 final int size = mRestrictBackgroundWhitelistUids.size();
1563 for (int i = 0; i < size; i++) {
1564 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1565 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1566 writeIntAttribute(out, ATTR_UID, uid);
1567 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1568 }
1569
1570 out.endTag(null, TAG_WHITELIST);
1571
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572 out.endDocument();
1573
1574 mPolicyFile.finishWrite(fos);
1575 } catch (IOException e) {
1576 if (fos != null) {
1577 mPolicyFile.failWrite(fos);
1578 }
1579 }
1580 }
1581
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001582 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001583 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001585
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001586 if (!UserHandle.isApp(uid)) {
1587 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001588 }
1589
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001590 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001591 final long token = Binder.clearCallingIdentity();
1592 try {
1593 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1594 if (oldPolicy != policy) {
1595 setUidPolicyUncheckedLocked(uid, policy, true);
1596 }
1597 } finally {
1598 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001599 }
1600 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001601 }
1602
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001603 @Override
1604 public void addUidPolicy(int uid, int policy) {
1605 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001606
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001607 if (!UserHandle.isApp(uid)) {
1608 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1609 }
1610
1611 synchronized (mRulesLock) {
1612 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1613 policy |= oldPolicy;
1614 if (oldPolicy != policy) {
1615 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001616 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001618 }
1619
1620 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001621 public void removeUidPolicy(int uid, int policy) {
1622 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1623
1624 if (!UserHandle.isApp(uid)) {
1625 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1626 }
1627
1628 synchronized (mRulesLock) {
1629 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1630 policy = oldPolicy & ~policy;
1631 if (oldPolicy != policy) {
1632 setUidPolicyUncheckedLocked(uid, policy, true);
1633 }
1634 }
1635 }
1636
1637 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1638 mUidPolicy.put(uid, policy);
1639
1640 // uid policy changed, recompute rules and persist policy.
1641 updateRulesForUidLocked(uid);
1642 if (persist) {
1643 writePolicyLocked();
1644 }
1645 }
1646
1647 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001648 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1650
Jeff Sharkeya4620792011-05-20 15:29:23 -07001651 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001652 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001653 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001654 }
1655
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001656 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001657 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001658 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1659
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001660 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001661 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001662 for (int i = 0; i < mUidPolicy.size(); i++) {
1663 final int uid = mUidPolicy.keyAt(i);
1664 final int uidPolicy = mUidPolicy.valueAt(i);
1665 if (uidPolicy == policy) {
1666 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001667 }
1668 }
1669 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001670 return uids;
1671 }
1672
1673 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001674 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001675 * if any changes are made.
1676 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001677 void removeUserStateLocked(int userId) {
1678 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1679 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001680
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001681 // Remove entries from restricted background UID whitelist
1682 int[] wlUids = new int[0];
1683 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1684 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1685 if (UserHandle.getUserId(uid) == userId) {
1686 wlUids = appendInt(wlUids, uid);
1687 }
1688 }
1689
1690 if (wlUids.length > 0) {
1691 for (int uid : wlUids) {
1692 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1693 }
1694 writePolicy = true;
1695 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08001696 updateRulesForGlobalChangeLocked(true);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001697
1698 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001699 int[] uids = new int[0];
1700 for (int i = 0; i < mUidPolicy.size(); i++) {
1701 final int uid = mUidPolicy.keyAt(i);
1702 if (UserHandle.getUserId(uid) == userId) {
1703 uids = appendInt(uids, uid);
1704 }
1705 }
1706
1707 if (uids.length > 0) {
1708 for (int uid : uids) {
1709 mUidPolicy.delete(uid);
1710 updateRulesForUidLocked(uid);
1711 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001712 writePolicy = true;
1713 }
1714
1715 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001716 writePolicyLocked();
1717 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001718 }
1719
1720 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001721 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001722 // TODO: create permission for observing network policy
1723 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1724
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001725 mListeners.register(listener);
1726
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001727 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001728 }
1729
1730 @Override
1731 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001732 // TODO: create permission for observing network policy
1733 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1734
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001735 mListeners.unregister(listener);
1736 }
1737
Jeff Sharkey1b861272011-05-22 00:34:52 -07001738 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001739 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001740 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1741
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001742 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001743 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001744 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001745 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001746 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001747 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001748 writePolicyLocked();
1749 }
1750 }
1751
Dianne Hackborn497175b2014-07-01 12:56:08 -07001752 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001753 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001754 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1755 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001756 }
1757
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001758 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001759 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001760 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001761 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001762 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1763 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1764 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001765 } catch (SecurityException e) {
1766 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001767
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001768 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1769 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1770 return new NetworkPolicy[0];
1771 }
Svet Ganov16a16892015-04-16 10:32:04 -07001772 }
1773
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001774 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001775 final int size = mNetworkPolicy.size();
1776 final NetworkPolicy[] policies = new NetworkPolicy[size];
1777 for (int i = 0; i < size; i++) {
1778 policies[i] = mNetworkPolicy.valueAt(i);
1779 }
1780 return policies;
1781 }
1782 }
1783
1784 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001785 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001786 }
1787
1788 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1789 final TelephonyManager tele = TelephonyManager.from(mContext);
1790 final String[] merged = tele.getMergedSubscriberIds();
1791
1792 mNetworkPolicy.clear();
1793 for (NetworkPolicy policy : policies) {
1794 // When two normalized templates conflict, prefer the most
1795 // restrictive policy
1796 policy.template = NetworkTemplate.normalize(policy.template, merged);
1797 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1798 if (existing == null || existing.compareTo(policy) > 0) {
1799 if (existing != null) {
1800 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1801 }
1802 mNetworkPolicy.put(policy.template, policy);
1803 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001804 }
1805 }
1806
1807 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001808 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001809 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001810
1811 final long token = Binder.clearCallingIdentity();
1812 try {
1813 performSnooze(template, TYPE_LIMIT);
1814 } finally {
1815 Binder.restoreCallingIdentity(token);
1816 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001817 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001818
Dianne Hackborn497175b2014-07-01 12:56:08 -07001819 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001820 maybeRefreshTrustedTime();
1821 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001822 synchronized (mRulesLock) {
1823 // find and snooze local policy that matches
1824 final NetworkPolicy policy = mNetworkPolicy.get(template);
1825 if (policy == null) {
1826 throw new IllegalArgumentException("unable to find policy for " + template);
1827 }
1828
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001829 switch (type) {
1830 case TYPE_WARNING:
1831 policy.lastWarningSnooze = currentTime;
1832 break;
1833 case TYPE_LIMIT:
1834 policy.lastLimitSnooze = currentTime;
1835 break;
1836 default:
1837 throw new IllegalArgumentException("unexpected type");
1838 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001839
Jeff Sharkey32566012014-12-02 18:30:14 -08001840 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001841 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001842 updateNetworkRulesLocked();
1843 updateNotificationsLocked();
1844 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001845 }
1846 }
1847
1848 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001849 public void setRestrictBackground(boolean restrictBackground) {
1850 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1851
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001852 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001853 synchronized (mRulesLock) {
1854 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001855 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001856 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001857 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001858 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001859
1860 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1861 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001862 }
1863
1864 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001865 public void addRestrictBackgroundWhitelistedUid(int uid) {
1866 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001867 if (!isUidValidForRules(uid)) return;
1868 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001869 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001870 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1871 if (oldStatus) {
1872 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
1873 return;
1874 }
1875 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08001876 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Leme47585ba2016-02-09 16:56:32 -08001877 changed = mRestrictBackground && !oldStatus;
1878 if (changed && hasInternetPermissions(uid)) {
1879 setUidNetworkRules(uid, false);
1880 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001881 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001882 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001883 if (changed) {
1884 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1885 .sendToTarget();
1886 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001887 }
1888
1889 @Override
1890 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1891 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08001892 if (!isUidValidForRules(uid)) return;
1893 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001894 synchronized (mRulesLock) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001895 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001896 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001897 if (changed) {
1898 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0)
1899 .sendToTarget();
1900 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001901 }
1902
Felipe Leme47585ba2016-02-09 16:56:32 -08001903 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean updateNow) {
1904 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
1905 if (!oldStatus) {
1906 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
1907 return false;
1908 }
1909 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1910 final boolean changed = mRestrictBackground && oldStatus;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001911 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Leme3f52cd52016-02-03 13:36:30 -08001912 if (updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08001913 if (changed && hasInternetPermissions(uid)) {
1914 setUidNetworkRules(uid, true);
1915 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001916 writePolicyLocked();
1917 }
Felipe Leme47585ba2016-02-09 16:56:32 -08001918 return changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001919 }
1920
1921 @Override
1922 public int[] getRestrictBackgroundWhitelistedUids() {
1923 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1924 synchronized (mRulesLock) {
1925 final int size = mRestrictBackgroundWhitelistUids.size();
1926 final int[] whitelist = new int[size];
1927 for (int i = 0; i < size; i++) {
1928 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1929 }
1930 if (LOGV) {
1931 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1932 + mRestrictBackgroundWhitelistUids);
1933 }
1934 return whitelist;
1935 }
1936 }
1937
1938 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08001939 public int getRestrictBackgroundByCaller() {
1940 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1941 final int uid = Binder.getCallingUid();
1942 synchronized (mRulesLock) {
1943 if (!mRestrictBackground) {
1944 return RESTRICT_BACKGROUND_STATUS_DISABLED;
1945 }
1946 return mRestrictBackgroundWhitelistUids.get(uid)
1947 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
1948 : RESTRICT_BACKGROUND_STATUS_ENABLED;
1949 }
1950 }
1951
1952 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001953 public boolean getRestrictBackground() {
1954 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1955
1956 synchronized (mRulesLock) {
1957 return mRestrictBackground;
1958 }
1959 }
1960
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001961 @Override
1962 public void setDeviceIdleMode(boolean enabled) {
1963 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1964
1965 synchronized (mRulesLock) {
1966 if (mDeviceIdleMode != enabled) {
1967 mDeviceIdleMode = enabled;
1968 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001969 // Device idle change means we need to rebuild rules for all
1970 // known apps, so do a global refresh.
1971 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001972 }
1973 if (enabled) {
1974 EventLogTags.writeDeviceIdleOnPhase("net");
1975 } else {
1976 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001977 }
1978 }
1979 }
1980 }
1981
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001982 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001983 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1984 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001985 if (policy.template.matches(ident)) {
1986 return policy;
1987 }
1988 }
1989 return null;
1990 }
1991
1992 @Override
1993 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1994 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1995
1996 // only returns usage summary, so we don't require caller to have
1997 // READ_NETWORK_USAGE_HISTORY.
1998 final long token = Binder.clearCallingIdentity();
1999 try {
2000 return getNetworkQuotaInfoUnchecked(state);
2001 } finally {
2002 Binder.restoreCallingIdentity(token);
2003 }
2004 }
2005
2006 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2007 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2008
2009 final NetworkPolicy policy;
2010 synchronized (mRulesLock) {
2011 policy = findPolicyForNetworkLocked(ident);
2012 }
2013
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002014 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002015 // missing policy means we can't derive useful quota info
2016 return null;
2017 }
2018
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002019 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002020
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002021 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002022 final long start = computeLastCycleBoundary(currentTime, policy);
2023 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002024 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002025
2026 // report soft and hard limits under policy
2027 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2028 : NetworkQuotaInfo.NO_LIMIT;
2029 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2030 : NetworkQuotaInfo.NO_LIMIT;
2031
2032 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2033 }
2034
Jeff Sharkey46645002011-07-27 21:11:21 -07002035 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002036 public boolean isNetworkMetered(NetworkState state) {
2037 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2038
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002039 // roaming networks are always considered metered
2040 if (ident.getRoaming()) {
2041 return true;
2042 }
2043
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002044 final NetworkPolicy policy;
2045 synchronized (mRulesLock) {
2046 policy = findPolicyForNetworkLocked(ident);
2047 }
2048
2049 if (policy != null) {
2050 return policy.metered;
2051 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002052 if (state.networkInfo == null) {
2053 return false;
2054 }
2055
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002056 final int type = state.networkInfo.getType();
2057 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2058 return true;
2059 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002060 return false;
2061 }
2062 }
2063
2064 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002065 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002066 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002067
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002068 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2069
Dianne Hackborn497175b2014-07-01 12:56:08 -07002070 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002071 for (String arg : args) {
2072 argSet.add(arg);
2073 }
2074
Jeff Sharkey1b861272011-05-22 00:34:52 -07002075 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002076 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002077 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2078 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002079 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002080
Jeff Sharkey32566012014-12-02 18:30:14 -08002081 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002082 updateNetworkEnabledLocked();
2083 updateNetworkRulesLocked();
2084 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002085 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002086
2087 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002088 return;
2089 }
2090
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002091 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002092 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002093 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002094 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002095 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002096 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002097 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2098 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002099 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002100 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002101
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002102 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2103
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002104 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002105 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002106 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002107 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002108 final int uid = mUidPolicy.keyAt(i);
2109 final int policy = mUidPolicy.valueAt(i);
2110 fout.print("UID=");
2111 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002112 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002113 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002114 fout.println();
2115 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002116 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002117
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002118 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2119 if (size > 0) {
2120 fout.println("Power save whitelist (except idle) app ids:");
2121 fout.increaseIndent();
2122 for (int i = 0; i < size; i++) {
2123 fout.print("UID=");
2124 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2125 fout.print(": ");
2126 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2127 fout.println();
2128 }
2129 fout.decreaseIndent();
2130 }
2131
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002132 size = mPowerSaveWhitelistAppIds.size();
2133 if (size > 0) {
2134 fout.println("Power save whitelist app ids:");
2135 fout.increaseIndent();
2136 for (int i = 0; i < size; i++) {
2137 fout.print("UID=");
2138 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2139 fout.print(": ");
2140 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2141 fout.println();
2142 }
2143 fout.decreaseIndent();
2144 }
2145
Felipe Lemeb85a6372016-01-14 16:16:16 -08002146 size = mRestrictBackgroundWhitelistUids.size();
2147 if (size > 0) {
2148 fout.println("Restrict background whitelist uids:");
2149 fout.increaseIndent();
2150 for (int i = 0; i < size; i++) {
2151 fout.print("UID=");
2152 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2153 fout.println();
2154 }
2155 fout.decreaseIndent();
2156 }
2157
Jeff Sharkey1b861272011-05-22 00:34:52 -07002158 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002159 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002160 collectKeys(mUidRules, knownUids);
2161
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002162 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002163 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002164 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002165 for (int i = 0; i < size; i++) {
2166 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002167 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002168 fout.print(uid);
2169
Jeff Sharkeydc988062015-09-14 10:09:47 -07002170 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002171 fout.print(" state=");
2172 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002173 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002174
Jeff Sharkeydc988062015-09-14 10:09:47 -07002175 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2176 fout.print(" rule=");
2177 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002178
2179 fout.println();
2180 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002181 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002182 }
2183 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002184
2185 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002186 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2187 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002188 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002189 this, in, out, err, args, resultReceiver);
2190 }
2191
2192 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002193 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002194 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2195
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002196 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002197 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002198 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002199 }
2200
Dianne Hackborn497175b2014-07-01 12:56:08 -07002201 boolean isUidForegroundLocked(int uid) {
2202 // only really in foreground when screen is also on
2203 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002204 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002205 }
2206
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002207 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002208 * Process state of UID changed; if needed, will trigger
2209 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002210 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002211 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002212 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2213 if (oldUidState != uidState) {
2214 // state changed, push updated rules
2215 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002216 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002217 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2218 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002219 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002220 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002221 }
2222 }
2223
2224 void removeUidStateLocked(int uid) {
2225 final int index = mUidState.indexOfKey(uid);
2226 if (index >= 0) {
2227 final int oldUidState = mUidState.valueAt(index);
2228 mUidState.removeAt(index);
2229 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2230 updateRulesForUidStateChangeLocked(uid, oldUidState,
2231 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002232 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002233 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002234 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002235 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002236 }
2237 }
2238
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002239 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002240 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2241 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002242 if (oldForeground != newForeground) {
2243 updateRulesForUidLocked(uid);
2244 }
2245 }
2246
Jeff Sharkeya4620792011-05-20 15:29:23 -07002247 private void updateScreenOn() {
2248 synchronized (mRulesLock) {
2249 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002250 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002251 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002252 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002253 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002254 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002255 }
2256 }
2257
2258 /**
2259 * Update rules that might be changed by {@link #mScreenOn} value.
2260 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002261 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002262 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002263 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002264 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002265 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002266 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002267 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002268 }
2269 }
2270 }
2271
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002272 static boolean isProcStateAllowedWhileIdle(int procState) {
2273 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2274 }
2275
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002276 void updateRulesForDeviceIdleLocked() {
2277 if (mDeviceIdleMode) {
2278 // sync the whitelists before enable dozable chain. We don't care about the rules if
2279 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002280 final SparseIntArray uidRules = mUidFirewallDozableRules;
2281 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002282 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002283 for (int ui = users.size() - 1; ui >= 0; ui--) {
2284 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002285 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002286 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2287 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2288 int uid = UserHandle.getUid(user.id, appId);
2289 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2290 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002291 }
2292 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2293 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2294 int uid = UserHandle.getUid(user.id, appId);
2295 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2296 }
2297 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002298 for (int i = mUidState.size() - 1; i >= 0; i--) {
2299 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2300 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2301 }
2302 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002303 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2304 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002305
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002306 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2307 }
2308
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002309 void updateRuleForDeviceIdleLocked(int uid) {
2310 if (mDeviceIdleMode) {
2311 int appId = UserHandle.getAppId(uid);
2312 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2313 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2314 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2315 } else {
2316 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2317 }
2318 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002319
2320 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002321 }
2322
2323 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002324 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2325 uidRules.clear();
2326
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002327 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002328 final List<UserInfo> users = mUserManager.getUsers();
2329 for (int ui = users.size() - 1; ui >= 0; ui--) {
2330 UserInfo user = users.get(ui);
2331 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2332 for (int uid : idleUids) {
2333 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2334 uidRules.put(uid, FIREWALL_RULE_DENY);
2335 }
2336 }
2337 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002338
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002339 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2340 }
2341
2342 void updateRuleForAppIdleLocked(int uid) {
2343 if (!isUidValidForRules(uid)) return;
2344
2345 int appId = UserHandle.getAppId(uid);
2346 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2347 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2348 } else {
2349 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2350 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002351
2352 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002353 }
2354
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002355 void updateRulesForAppIdleParoleLocked() {
2356 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2357 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002358 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002359 }
2360
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002361 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002362 * Update rules that might be changed by {@link #mRestrictBackground},
2363 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002364 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002365 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002366 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002367
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002368 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002369 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002370
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002371 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002372 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002373 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002374 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2375 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002376
2377 for (UserInfo user : users) {
2378 for (ApplicationInfo app : apps) {
2379 final int uid = UserHandle.getUid(user.id, app.uid);
2380 updateRulesForUidLocked(uid);
2381 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002382 }
2383
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002384 // limit data usage for some internal system services
2385 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2386 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002387
2388 // If the set of restricted networks may have changed, re-evaluate those.
2389 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002390 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002391 updateNetworkRulesLocked();
2392 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002393 }
2394
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002395 void updateRulesForTempWhitelistChangeLocked() {
2396 final List<UserInfo> users = mUserManager.getUsers();
2397 for (UserInfo user : users) {
2398 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2399 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2400 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002401 updateRuleForAppIdleLocked(uid);
2402 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002403 }
2404 }
2405 }
2406
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002407 private static boolean isUidValidForRules(int uid) {
2408 // allow rules on specific system services, and any apps
2409 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002410 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002411 return true;
2412 }
2413
2414 return false;
2415 }
2416
Amith Yamasani15e472352015-04-24 19:06:07 -07002417 private boolean isUidIdle(int uid) {
2418 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2419 final int userId = UserHandle.getUserId(uid);
2420
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002421 if (!ArrayUtils.isEmpty(packages)) {
2422 for (String packageName : packages) {
2423 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2424 return false;
2425 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002426 }
2427 }
2428 return true;
2429 }
2430
Jeff Sharkeydc988062015-09-14 10:09:47 -07002431 void updateRulesForUidsLocked(SparseIntArray uids) {
2432 for (int i = 0; i < uids.size(); i++) {
2433 updateRulesForUidLocked(uids.keyAt(i));
2434 }
2435 }
2436
Amith Yamasani15e472352015-04-24 19:06:07 -07002437 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002438 * Checks if an uid has INTERNET permissions.
2439 * <p>
2440 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002441 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002442 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002443 final IPackageManager ipm = AppGlobals.getPackageManager();
2444 try {
2445 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2446 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002447 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002448 }
2449 } catch (RemoteException e) {
2450 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002451 return true;
2452 }
2453
2454 /**
2455 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2456 * @param uid The uid for which to apply the latest policy
2457 */
2458 void updateRulesForUidLocked(int uid) {
2459 if (!isUidValidForRules(uid) || !hasInternetPermissions(uid)) return;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002460
Dianne Hackborn497175b2014-07-01 12:56:08 -07002461 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2462 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002463
Jeff Sharkeydc988062015-09-14 10:09:47 -07002464 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002465 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002466 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002467 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002468 // uid in background, and policy says to block metered data
2469 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002470 } else if (mRestrictBackground) {
2471 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002472 // uid in background, global background disabled, and this uid is not on the white
2473 // list of those allowed background access while global background is disabled
2474 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2475 uidRules = RULE_REJECT_METERED;
2476 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002477 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002478 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002479 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002480 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002481 if (!whitelisted && !uidForeground
2482 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2483 // uid is in background, restrict power use mode is on (so we want to
2484 // restrict all background network access), and this uid is not on the
2485 // white list of those allowed background access.
2486 uidRules = RULE_REJECT_METERED;
2487 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002488 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002489
Jeff Sharkeydc988062015-09-14 10:09:47 -07002490 // Check dozable state, which is whitelist
2491 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2492 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2493 uidRules = RULE_REJECT_ALL;
2494 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002495
Jeff Sharkeydc988062015-09-14 10:09:47 -07002496 // Check standby state, which is blacklist
2497 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2498 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2499 uidRules = RULE_REJECT_ALL;
2500 }
2501
2502 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002503 if (uidRules == RULE_ALLOW_ALL) {
2504 mUidRules.delete(uid);
2505 } else {
2506 mUidRules.put(uid, uidRules);
2507 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002508
Jeff Sharkeydc988062015-09-14 10:09:47 -07002509 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2510 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002511
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002512 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002513 if (oldRules != uidRules) {
2514 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2515 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002516
2517 try {
2518 // adjust stats accounting based on foreground status
2519 mNetworkStats.setUidForeground(uid, uidForeground);
2520 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002521 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002522 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002523 }
2524
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002525 private class AppIdleStateChangeListener
2526 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2527
2528 @Override
2529 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2530 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002531 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2532 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002533 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002534 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002535 }
2536 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002537 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002538 }
2539
2540 @Override
2541 public void onParoleStateChanged(boolean isParoleOn) {
2542 synchronized (mRulesLock) {
2543 updateRulesForAppIdleParoleLocked();
2544 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002545 }
2546 }
2547
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002548 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002549 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002550 public boolean handleMessage(Message msg) {
2551 switch (msg.what) {
2552 case MSG_RULES_CHANGED: {
2553 final int uid = msg.arg1;
2554 final int uidRules = msg.arg2;
2555 final int length = mListeners.beginBroadcast();
2556 for (int i = 0; i < length; i++) {
2557 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2558 if (listener != null) {
2559 try {
2560 listener.onUidRulesChanged(uid, uidRules);
2561 } catch (RemoteException e) {
2562 }
2563 }
2564 }
2565 mListeners.finishBroadcast();
2566 return true;
2567 }
2568 case MSG_METERED_IFACES_CHANGED: {
2569 final String[] meteredIfaces = (String[]) msg.obj;
2570 final int length = mListeners.beginBroadcast();
2571 for (int i = 0; i < length; i++) {
2572 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2573 if (listener != null) {
2574 try {
2575 listener.onMeteredIfacesChanged(meteredIfaces);
2576 } catch (RemoteException e) {
2577 }
2578 }
2579 }
2580 mListeners.finishBroadcast();
2581 return true;
2582 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002583 case MSG_LIMIT_REACHED: {
2584 final String iface = (String) msg.obj;
2585
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002586 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002587 synchronized (mRulesLock) {
2588 if (mMeteredIfaces.contains(iface)) {
2589 try {
2590 // force stats update to make sure we have
2591 // numbers that caused alert to trigger.
2592 mNetworkStats.forceUpdate();
2593 } catch (RemoteException e) {
2594 // ignored; service lives in system_server
2595 }
2596
2597 updateNetworkEnabledLocked();
2598 updateNotificationsLocked();
2599 }
2600 }
2601 return true;
2602 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002603 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2604 final boolean restrictBackground = msg.arg1 != 0;
2605 final int length = mListeners.beginBroadcast();
2606 for (int i = 0; i < length; i++) {
2607 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2608 if (listener != null) {
2609 try {
2610 listener.onRestrictBackgroundChanged(restrictBackground);
2611 } catch (RemoteException e) {
2612 }
2613 }
2614 }
2615 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002616 final Intent intent =
2617 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2618 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2619 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2620 return true;
2621 }
2622 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2623 final int uid = msg.arg1;
2624 final PackageManager pm = mContext.getPackageManager();
2625 final String[] packages = pm.getPackagesForUid(uid);
2626 final int userId = UserHandle.getUserId(uid);
2627 for (String packageName : packages) {
2628 final Intent intent =
2629 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2630 intent.setPackage(packageName);
2631 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2632 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2633 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002634 return true;
2635 }
2636 case MSG_ADVISE_PERSIST_THRESHOLD: {
2637 final long lowestRule = (Long) msg.obj;
2638 try {
2639 // make sure stats are recorded frequently enough; we aim
2640 // for 2MB threshold for 2GB/month rules.
2641 final long persistThreshold = lowestRule / 1000;
2642 mNetworkStats.advisePersistThreshold(persistThreshold);
2643 } catch (RemoteException e) {
2644 // ignored; service lives in system_server
2645 }
2646 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002647 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002648 case MSG_SCREEN_ON_CHANGED: {
2649 updateScreenOn();
2650 return true;
2651 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002652 default: {
2653 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002654 }
2655 }
2656 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002657 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002658
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002659 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002660 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002661 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002662 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002663 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002664 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002665 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002666 }
2667 }
2668
2669 private void removeInterfaceQuota(String iface) {
2670 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002671 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002672 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002673 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002674 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002675 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002676 }
2677 }
2678
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002679 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2680 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002681 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002682 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002683 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002684 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002685 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002686 }
2687 }
2688
Amith Yamasani15e472352015-04-24 19:06:07 -07002689 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002690 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2691 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2692 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002693 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002694 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002695 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002696 int size = uidRules.size();
2697 int[] uids = new int[size];
2698 int[] rules = new int[size];
2699 for(int index = size - 1; index >= 0; --index) {
2700 uids[index] = uidRules.keyAt(index);
2701 rules[index] = uidRules.valueAt(index);
2702 }
2703 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002704 } catch (IllegalStateException e) {
2705 Log.wtf(TAG, "problem setting firewall uid rules", e);
2706 } catch (RemoteException e) {
2707 // ignored; service lives in system_server
2708 }
2709 }
2710
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002711 /**
2712 * Add or remove a uid to the firewall blacklist for all network ifaces.
2713 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002714 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002715 if (chain == FIREWALL_CHAIN_DOZABLE) {
2716 mUidFirewallDozableRules.put(uid, rule);
2717 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2718 mUidFirewallStandbyRules.put(uid, rule);
2719 }
2720
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002721 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002722 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002723 } catch (IllegalStateException e) {
2724 Log.wtf(TAG, "problem setting firewall uid rules", e);
2725 } catch (RemoteException e) {
2726 // ignored; service lives in system_server
2727 }
2728 }
2729
2730 /**
2731 * Add or remove a uid to the firewall blacklist for all network ifaces.
2732 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002733 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002734 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2735 mFirewallChainStates.get(chain) == enable) {
2736 // All is the same, nothing to do.
2737 return;
2738 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002739 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002740 try {
2741 mNetworkManager.setFirewallChainEnabled(chain, enable);
2742 } catch (IllegalStateException e) {
2743 Log.wtf(TAG, "problem enable firewall chain", e);
2744 } catch (RemoteException e) {
2745 // ignored; service lives in system_server
2746 }
2747 }
2748
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002749 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2750 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002751 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002752 } catch (RuntimeException e) {
2753 Slog.w(TAG, "problem reading network stats: " + e);
2754 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002755 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002756 // ignored; service lives in system_server
2757 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002758 }
2759 }
2760
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002761 private boolean isBandwidthControlEnabled() {
2762 final long token = Binder.clearCallingIdentity();
2763 try {
2764 return mNetworkManager.isBandwidthControlEnabled();
2765 } catch (RemoteException e) {
2766 // ignored; service lives in system_server
2767 return false;
2768 } finally {
2769 Binder.restoreCallingIdentity(token);
2770 }
2771 }
2772
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002773 /**
2774 * Try refreshing {@link #mTime} when stale.
2775 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002776 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002777 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002778 mTime.forceRefresh();
2779 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002780 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002781
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002782 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002783 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2784 }
2785
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002786 private static Intent buildAllowBackgroundDataIntent() {
2787 return new Intent(ACTION_ALLOW_BACKGROUND);
2788 }
2789
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002790 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2791 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2792 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2793 return intent;
2794 }
2795
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002796 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2797 final Intent intent = new Intent();
2798 intent.setComponent(new ComponentName(
2799 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2800 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2801 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2802 return intent;
2803 }
2804
2805 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2806 final Intent intent = new Intent();
2807 intent.setComponent(new ComponentName(
2808 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2809 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2810 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2811 return intent;
2812 }
2813
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002814 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002815 public void addIdleHandler(IdleHandler handler) {
2816 mHandler.getLooper().getQueue().addIdleHandler(handler);
2817 }
2818
Jeff Sharkey1b861272011-05-22 00:34:52 -07002819 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2820 final int size = source.size();
2821 for (int i = 0; i < size; i++) {
2822 target.put(source.keyAt(i), true);
2823 }
2824 }
2825
Stuart Scottf1fb3972015-04-02 18:00:02 -07002826 @Override
2827 public void factoryReset(String subscriber) {
2828 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2829
Stuart Scotte3e314d2015-04-20 14:07:45 -07002830 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2831 return;
2832 }
2833
Stuart Scottf1fb3972015-04-02 18:00:02 -07002834 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002835 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002836 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2837 for (NetworkPolicy policy : policies) {
2838 if (policy.template.equals(template)) {
2839 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2840 policy.inferred = false;
2841 policy.clearSnooze();
2842 }
2843 }
2844 setNetworkPolicies(policies);
2845
2846 // Turn restrict background data off
2847 setRestrictBackground(false);
2848
Stuart Scotte3e314d2015-04-20 14:07:45 -07002849 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2850 // Remove app's "restrict background data" flag
2851 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2852 setUidPolicy(uid, POLICY_NONE);
2853 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002854 }
2855 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002856
2857 private class MyPackageMonitor extends PackageMonitor {
2858
2859 @Override
2860 public void onPackageRemoved(String packageName, int uid) {
2861 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2862 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002863 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002864 }
2865 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002866 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002867}