blob: 5c7707968a460511953e635580ce9337284cfcfa [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 {
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195 private 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;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700258
Jeff Sharkey75279902011-05-24 18:39:45 -0700259 private final Context mContext;
260 private final IActivityManager mActivityManager;
261 private final IPowerManager mPowerManager;
262 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700263 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700264 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700266 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267
268 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700269 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700270 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700271 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700272
Dianne Hackborn497175b2014-07-01 12:56:08 -0700273 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700274
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700275 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700276 volatile boolean mScreenOn;
277 volatile boolean mRestrictBackground;
278 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700279 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700280
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700281 private final boolean mSuppressDefaultPolicy;
282
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700283 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800284 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700285 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800286 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700287
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700288 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700289 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700290 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800291 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700292
Jeff Sharkeydc988062015-09-14 10:09:47 -0700293 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
294 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
295
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700296 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700297 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
298
Jeff Sharkey32566012014-12-02 18:30:14 -0800299 /**
300 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700301 * in power save mode, except device idle (doze) still applies.
302 * TODO: An int array might be sufficient
303 */
304 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
305
306 /**
307 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800308 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700309 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800310 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700311 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700312
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700313 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
314
Felipe Lemeb85a6372016-01-14 16:16:16 -0800315 /**
316 * UIDs that have been white-listed to avoid restricted background.
317 */
318 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
319
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700320 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800321 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700322 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800323 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700324
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700325 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700326 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700327
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700328 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800329 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700330
Jeff Sharkey32566012014-12-02 18:30:14 -0800331 private final RemoteCallbackList<INetworkPolicyListener>
332 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700333
Dianne Hackborn497175b2014-07-01 12:56:08 -0700334 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335
336 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700337
Svet Ganov16a16892015-04-16 10:32:04 -0700338 private final AppOpsManager mAppOps;
339
Felipe Lemeb85a6372016-01-14 16:16:16 -0800340 private final MyPackageMonitor mPackageMonitor;
341
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700342 // TODO: keep whitelist of system-critical services that should never have
343 // rules enforced, such as system, phone, and radio UIDs.
344
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700345 // TODO: migrate notifications to SystemUI
346
Jeff Sharkey75279902011-05-24 18:39:45 -0700347 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700348 IPowerManager powerManager, INetworkStatsService networkStats,
349 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700350 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700351 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700352 }
353
354 private static File getSystemDir() {
355 return new File(Environment.getDataDirectory(), "system");
356 }
357
358 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700359 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700360 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
361 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700362 mContext = checkNotNull(context, "missing context");
363 mActivityManager = checkNotNull(activityManager, "missing activityManager");
364 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700365 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700366 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700367 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700368 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700369 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700370 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700371
Amith Yamasani450a16b2013-09-18 16:28:50 -0700372 HandlerThread thread = new HandlerThread(TAG);
373 thread.start();
374 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700375
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700376 mSuppressDefaultPolicy = suppressDefaultPolicy;
377
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700378 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700379
380 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800381
382 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700383 }
384
385 public void bindConnectivityManager(IConnectivityManager connManager) {
386 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700387 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700388
Jeff Sharkey497e4432011-06-14 17:27:29 -0700389 public void bindNotificationManager(INotificationManager notifManager) {
390 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
391 }
392
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700393 void updatePowerSaveWhitelistLocked() {
394 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700395 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
396 mPowerSaveWhitelistExceptIdleAppIds.clear();
397 if (whitelist != null) {
398 for (int uid : whitelist) {
399 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
400 }
401 }
402 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700403 mPowerSaveWhitelistAppIds.clear();
404 if (whitelist != null) {
405 for (int uid : whitelist) {
406 mPowerSaveWhitelistAppIds.put(uid, true);
407 }
408 }
409 } catch (RemoteException e) {
410 }
411 }
412
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700413 void updatePowerSaveTempWhitelistLocked() {
414 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700415 // Clear the states of the current whitelist
416 final int N = mPowerSaveTempWhitelistAppIds.size();
417 for (int i = 0; i < N; i++) {
418 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
419 }
420 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700421 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700422 if (whitelist != null) {
423 for (int uid : whitelist) {
424 mPowerSaveTempWhitelistAppIds.put(uid, true);
425 }
426 }
427 } catch (RemoteException e) {
428 }
429 }
430
Amith Yamasani06f08062015-06-12 13:23:33 -0700431 /**
432 * Remove unnecessary entries in the temp whitelist
433 */
434 void purgePowerSaveTempWhitelistLocked() {
435 final int N = mPowerSaveTempWhitelistAppIds.size();
436 for (int i = N - 1; i >= 0; i--) {
437 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
438 mPowerSaveTempWhitelistAppIds.removeAt(i);
439 }
440 }
441 }
442
Jeff Sharkeya4620792011-05-20 15:29:23 -0700443 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700444 if (!isBandwidthControlEnabled()) {
445 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
446 return;
447 }
448
Amith Yamasani15e472352015-04-24 19:06:07 -0700449 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
450
Felipe Lemeb85a6372016-01-14 16:16:16 -0800451 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
452
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700453 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700454 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700455 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
456 mPowerManagerInternal.registerLowPowerModeObserver(
457 new PowerManagerInternal.LowPowerModeListener() {
458 @Override
459 public void onLowPowerModeChanged(boolean enabled) {
460 synchronized (mRulesLock) {
461 if (mRestrictPower != enabled) {
462 mRestrictPower = enabled;
463 updateRulesForGlobalChangeLocked(true);
464 }
465 }
466 }
467 });
468 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700469 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700470
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700471 // read policy from disk
472 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700473
Jeff Sharkeydc988062015-09-14 10:09:47 -0700474 updateRulesForGlobalChangeLocked(false);
475 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700476 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700477
Jeff Sharkeya4620792011-05-20 15:29:23 -0700478 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700479
Jeff Sharkeya4620792011-05-20 15:29:23 -0700480 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700481 mActivityManager.registerUidObserver(mUidObserver,
482 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700483 mNetworkManager.registerObserver(mAlertObserver);
484 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700485 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700486 }
487
Jeff Sharkeya4620792011-05-20 15:29:23 -0700488 // TODO: traverse existing processes to know foreground state, or have
489 // activitymanager dispatch current state when new observer attached.
490
491 final IntentFilter screenFilter = new IntentFilter();
492 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
493 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700494 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700495
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700496 // listen for changes to power save whitelist
497 final IntentFilter whitelistFilter = new IntentFilter(
498 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
499 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
500
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700501 DeviceIdleController.LocalService deviceIdleService
502 = LocalServices.getService(DeviceIdleController.LocalService.class);
503 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
504
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700505 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900506 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700507 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
508
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700509 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700510 final IntentFilter packageFilter = new IntentFilter();
511 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700512 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700513 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700514
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700515 // listen for UID changes to update policy
516 mContext.registerReceiver(
517 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
518
519 // listen for user changes to update policy
520 final IntentFilter userFilter = new IntentFilter();
521 userFilter.addAction(ACTION_USER_ADDED);
522 userFilter.addAction(ACTION_USER_REMOVED);
523 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
524
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700525 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700526 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
527 mContext.registerReceiver(
528 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
529
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700530 // listen for restrict background changes from notifications
531 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
532 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
533
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800534 // listen for snooze warning from notifications
535 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
536 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
537 MANAGE_NETWORK_POLICY, mHandler);
538
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700539 // listen for configured wifi networks to be removed
540 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700541 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700542
543 // listen for wifi state changes to catch metered hint
544 final IntentFilter wifiStateFilter = new IntentFilter(
545 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700546 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700547
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700548 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700549
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700550 }
551
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700552 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700553 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700554 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700555 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700556 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700557 }
558
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700559 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700560 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700561 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700562 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700563 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700564
565 @Override public void onUidActive(int uid) throws RemoteException {
566 }
567
568 @Override public void onUidIdle(int uid) throws RemoteException {
569 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700570 };
571
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700572 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700573 @Override
574 public void onReceive(Context context, Intent intent) {
575 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
576 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700577 updatePowerSaveWhitelistLocked();
578 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700579 }
580 }
581 };
582
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700583 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
584 @Override
585 public void run() {
586 synchronized (mRulesLock) {
587 updatePowerSaveTempWhitelistLocked();
588 updateRulesForTempWhitelistChangeLocked();
589 purgePowerSaveTempWhitelistLocked();
590 }
591 }
592 };
593
594 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700595 @Override
596 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800597 // screen-related broadcasts are protected by system, no need
598 // for permissions check.
599 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700600 }
601 };
602
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700603 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700604 @Override
605 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700606 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700607
608 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700609 final int uid = intent.getIntExtra(EXTRA_UID, -1);
610 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700611
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700612 if (ACTION_PACKAGE_ADDED.equals(action)) {
613 // update rules for UID, since it might be subject to
614 // global background data policy
615 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
616 synchronized (mRulesLock) {
617 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700618 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700619 }
620 }
621 };
622
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700623 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700624 @Override
625 public void onReceive(Context context, Intent intent) {
626 // on background handler thread, and UID_REMOVED is protected
627
628 final int uid = intent.getIntExtra(EXTRA_UID, -1);
629 if (uid == -1) return;
630
631 // remove any policy and update rules to clean up
632 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
633 synchronized (mRulesLock) {
634 mUidPolicy.delete(uid);
635 updateRulesForUidLocked(uid);
636 writePolicyLocked();
637 }
638 }
639 };
640
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700641 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700642 @Override
643 public void onReceive(Context context, Intent intent) {
644 // on background handler thread, and USER_ADDED and USER_REMOVED
645 // broadcasts are protected
646
647 final String action = intent.getAction();
648 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
649 if (userId == -1) return;
650
Amith Yamasani15e472352015-04-24 19:06:07 -0700651 switch (action) {
652 case ACTION_USER_REMOVED:
653 case ACTION_USER_ADDED:
654 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800655 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700656 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800657 removeUserStateLocked(userId);
Amith Yamasani15e472352015-04-24 19:06:07 -0700658 // Update global restrict for new user
659 updateRulesForGlobalChangeLocked(true);
660 }
661 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700662 }
663 }
664 };
665
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700666 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700667 * Receiver that watches for {@link INetworkStatsService} updates, which we
668 * use to check against {@link NetworkPolicy#warningBytes}.
669 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700670 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700671 @Override
672 public void onReceive(Context context, Intent intent) {
673 // on background handler thread, and verified
674 // READ_NETWORK_USAGE_HISTORY permission above.
675
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800676 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700677 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700678 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700679 updateNotificationsLocked();
680 }
681 }
682 };
683
684 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700685 * Receiver that watches for {@link Notification} control of
686 * {@link #mRestrictBackground}.
687 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700688 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700689 @Override
690 public void onReceive(Context context, Intent intent) {
691 // on background handler thread, and verified MANAGE_NETWORK_POLICY
692 // permission above.
693
694 setRestrictBackground(false);
695 }
696 };
697
698 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800699 * Receiver that watches for {@link Notification} control of
700 * {@link NetworkPolicy#lastWarningSnooze}.
701 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700702 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800703 @Override
704 public void onReceive(Context context, Intent intent) {
705 // on background handler thread, and verified MANAGE_NETWORK_POLICY
706 // permission above.
707
708 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
709 performSnooze(template, TYPE_WARNING);
710 }
711 };
712
713 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700714 * Receiver that watches for {@link WifiConfiguration} to be changed.
715 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700716 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700717 @Override
718 public void onReceive(Context context, Intent intent) {
719 // on background handler thread, and verified CONNECTIVITY_INTERNAL
720 // permission above.
721
722 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
723 if (reason == CHANGE_REASON_REMOVED) {
724 final WifiConfiguration config = intent.getParcelableExtra(
725 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700726 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800727 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700728 synchronized (mRulesLock) {
729 if (mNetworkPolicy.containsKey(template)) {
730 mNetworkPolicy.remove(template);
731 writePolicyLocked();
732 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700733 }
734 }
735 }
736 }
737 };
738
739 /**
740 * Receiver that watches {@link WifiInfo} state changes to infer metered
741 * state. Ignores hints when policy is user-defined.
742 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700743 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700744 @Override
745 public void onReceive(Context context, Intent intent) {
746 // on background handler thread, and verified CONNECTIVITY_INTERNAL
747 // permission above.
748
749 // ignore when not connected
750 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
751 if (!netInfo.isConnected()) return;
752
753 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
754 final boolean meteredHint = info.getMeteredHint();
755
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800756 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700757 synchronized (mRulesLock) {
758 NetworkPolicy policy = mNetworkPolicy.get(template);
759 if (policy == null && meteredHint) {
760 // policy doesn't exist, and AP is hinting that it's
761 // metered: create an inferred policy.
762 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
763 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
764 meteredHint, true);
765 addNetworkPolicyLocked(policy);
766
767 } else if (policy != null && policy.inferred) {
768 // policy exists, and was inferred: update its current
769 // metered state.
770 policy.metered = meteredHint;
771
772 // since this is inferred for each wifi session, just update
773 // rules without persisting.
774 updateNetworkRulesLocked();
775 }
776 }
777 }
778 };
779
780 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700781 * Observer that watches for {@link INetworkManagementService} alerts.
782 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700783 final private INetworkManagementEventObserver mAlertObserver
784 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700785 @Override
786 public void limitReached(String limitName, String iface) {
787 // only someone like NMS should be calling us
788 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
789
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800790 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
791 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700792 }
793 }
794 };
795
796 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700797 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
798 * to show visible notifications as needed.
799 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700800 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700801 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
802
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700803 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700804 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700805 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806
807 // TODO: when switching to kernel notifications, compute next future
808 // cycle boundary to recompute notifications.
809
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700810 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800811 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700812 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
813 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700814 // ignore policies that aren't relevant to user
815 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700816 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700817
Jeff Sharkey497e4432011-06-14 17:27:29 -0700818 final long start = computeLastCycleBoundary(currentTime, policy);
819 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700820 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700821
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700822 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800823 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700824 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
825 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700826 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
827 notifyOverLimitLocked(policy.template);
828 }
829
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700831 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800833 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700834 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700835 }
836 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700837 }
838
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700839 // ongoing notification when restricting background data
840 if (mRestrictBackground) {
841 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700842 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700843
844 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700845 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
846 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700847 if (!mActiveNotifs.contains(tag)) {
848 cancelNotification(tag);
849 }
850 }
851 }
852
853 /**
854 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700855 * current device state, such as when
856 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
857 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700858 */
859 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800860 if (template.isMatchRuleMobile()) {
861 final TelephonyManager tele = TelephonyManager.from(mContext);
862 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700863
Jeff Sharkey32566012014-12-02 18:30:14 -0800864 // Mobile template is relevant when any active subscriber matches
865 final int[] subIds = sub.getActiveSubscriptionIdList();
866 for (int subId : subIds) {
867 final String subscriberId = tele.getSubscriberId(subId);
868 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
869 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
870 if (template.matches(probeIdent)) {
871 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700872 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800873 }
874 return false;
875 } else {
876 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700877 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 }
879
880 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700881 * Notify that given {@link NetworkTemplate} is over
882 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
883 */
884 private void notifyOverLimitLocked(NetworkTemplate template) {
885 if (!mOverLimitNotified.contains(template)) {
886 mContext.startActivity(buildNetworkOverLimitIntent(template));
887 mOverLimitNotified.add(template);
888 }
889 }
890
891 private void notifyUnderLimitLocked(NetworkTemplate template) {
892 mOverLimitNotified.remove(template);
893 }
894
895 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700896 * Build unique tag that identifies an active {@link NetworkPolicy}
897 * notification of a specific type, like {@link #TYPE_LIMIT}.
898 */
899 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700900 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700901 }
902
903 /**
904 * Show notification for combined {@link NetworkPolicy} and specific type,
905 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
906 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700907 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700908 final String tag = buildNotificationTag(policy, type);
909 final Notification.Builder builder = new Notification.Builder(mContext);
910 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800911 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700912 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200913 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700914
915 final Resources res = mContext.getResources();
916 switch (type) {
917 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700918 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700919 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700920
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700921 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700922 builder.setTicker(title);
923 builder.setContentTitle(title);
924 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700925
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800926 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
927 builder.setDeleteIntent(PendingIntent.getBroadcast(
928 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
929
930 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700931 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800932 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
933
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934 break;
935 }
936 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700937 final CharSequence body = res.getText(R.string.data_usage_limit_body);
938
939 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400940 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700941 switch (policy.template.getMatchRule()) {
942 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700943 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700944 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700945 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700946 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700947 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700948 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700949 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700950 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700951 case MATCH_WIFI:
952 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400953 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700954 break;
955 default:
956 title = null;
957 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700958 }
959
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800960 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400961 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962 builder.setTicker(title);
963 builder.setContentTitle(title);
964 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700965
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700966 final Intent intent = buildNetworkOverLimitIntent(policy.template);
967 builder.setContentIntent(PendingIntent.getActivity(
968 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
969 break;
970 }
971 case TYPE_LIMIT_SNOOZED: {
972 final long overBytes = totalBytes - policy.limitBytes;
973 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
974 Formatter.formatFileSize(mContext, overBytes));
975
976 final CharSequence title;
977 switch (policy.template.getMatchRule()) {
978 case MATCH_MOBILE_3G_LOWER:
979 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
980 break;
981 case MATCH_MOBILE_4G:
982 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
983 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700984 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
986 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 case MATCH_WIFI:
988 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
989 break;
990 default:
991 title = null;
992 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700993 }
994
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800995 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700996 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700997 builder.setTicker(title);
998 builder.setContentTitle(title);
999 builder.setContentText(body);
1000
1001 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001002 builder.setContentIntent(PendingIntent.getActivity(
1003 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001004 break;
1005 }
1006 }
1007
1008 // TODO: move to NotificationManager once we can mock it
1009 try {
1010 final String packageName = mContext.getPackageName();
1011 final int[] idReceived = new int[1];
1012 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001013 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001014 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001015 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001017 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001018 }
1019 }
1020
1021 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001022 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1023 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001025 private void enqueueRestrictedNotification(String tag) {
1026 final Resources res = mContext.getResources();
1027 final Notification.Builder builder = new Notification.Builder(mContext);
1028
1029 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1030 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1031
1032 builder.setOnlyAlertOnce(true);
1033 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001034 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001035 builder.setTicker(title);
1036 builder.setContentTitle(title);
1037 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001038 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001039 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001040
1041 final Intent intent = buildAllowBackgroundDataIntent();
1042 builder.setContentIntent(
1043 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001044
1045 // TODO: move to NotificationManager once we can mock it
1046 try {
1047 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001048 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001049 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001050 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001051 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001052 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001053 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001054 }
1055 }
1056
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001057 private void cancelNotification(String tag) {
1058 // TODO: move to NotificationManager once we can mock it
1059 try {
1060 final String packageName = mContext.getPackageName();
1061 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001062 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001064 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001065 }
1066 }
1067
1068 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001069 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001070 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001071 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001072 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001073 @Override
1074 public void onReceive(Context context, Intent intent) {
1075 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1076 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001077
1078 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001079 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001080 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001081 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001083 updateNetworkRulesLocked();
1084 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001085 }
1086 }
1087 };
1088
1089 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001090 * Proactively control network data connections when they exceed
1091 * {@link NetworkPolicy#limitBytes}.
1092 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001093 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001094 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1095
1096 // TODO: reset any policy-disabled networks when any policy is removed
1097 // completely, which is currently rare case.
1098
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001099 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001100 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1101 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001102 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001103 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001104 setNetworkTemplateEnabled(policy.template, true);
1105 continue;
1106 }
1107
1108 final long start = computeLastCycleBoundary(currentTime, policy);
1109 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001110 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001111
1112 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001113 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1114 && policy.lastLimitSnooze < start;
1115 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001116
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001117 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001118 }
1119 }
1120
1121 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001122 * Proactively disable networks that match the given
1123 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001124 */
1125 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001126 // TODO: reach into ConnectivityManager to proactively disable bringing
1127 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001128 }
1129
1130 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001131 * Examine all connected {@link NetworkState}, looking for
1132 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1133 * remaining quota based on usage cycle and historical stats.
1134 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001135 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001136 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001137
1138 final NetworkState[] states;
1139 try {
1140 states = mConnManager.getAllNetworkState();
1141 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001142 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001143 return;
1144 }
1145
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001146 // If we are in restrict power mode, we want to treat all interfaces
1147 // as metered, to restrict access to the network by uid. However, we
1148 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001149 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001150 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001151 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001152
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001153 // First, generate identities of all connected networks so we can
1154 // quickly compare them against all defined policies below.
1155 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001156 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001157 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001158 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001159 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001160
1161 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001162 if (baseIface != null) {
1163 connIdents.add(Pair.create(baseIface, ident));
1164 if (powerSave) {
1165 connIfaces.add(baseIface);
1166 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001167 }
1168
1169 // Stacked interfaces are considered to have same identity as
1170 // their parent network.
1171 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1172 for (LinkProperties stackedLink : stackedLinks) {
1173 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001174 if (stackedIface != null) {
1175 connIdents.add(Pair.create(stackedIface, ident));
1176 if (powerSave) {
1177 connIfaces.add(stackedIface);
1178 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001179 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001180 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 }
1182 }
1183
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001184 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001185 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001186 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001187 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001188 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001190 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001191 for (int j = connIdents.size() - 1; j >= 0; j--) {
1192 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1193 if (policy.template.matches(ident.second)) {
1194 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001195 }
1196 }
1197
1198 if (ifaceList.size() > 0) {
1199 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001200 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001201 }
1202 }
1203
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001204 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001205 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001206
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 // apply each policy that we found ifaces for; compute remaining data
1208 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001209 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001210 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1211 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1212 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001213
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001214 final long start;
1215 final long totalBytes;
1216 if (policy.hasCycle()) {
1217 start = computeLastCycleBoundary(currentTime, policy);
1218 totalBytes = getTotalBytes(policy.template, start, currentTime);
1219 } else {
1220 start = Long.MAX_VALUE;
1221 totalBytes = 0;
1222 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224 if (LOGD) {
1225 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001226 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 }
1228
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001229 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001230 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001231 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001232 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001233 if (!hasLimit) {
1234 // metered network, but no policy limit; we still need to
1235 // restrict apps, so push really high quota.
1236 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001237 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001238 // snoozing past quota, but we still need to restrict apps,
1239 // so push really high quota.
1240 quotaBytes = Long.MAX_VALUE;
1241 } else {
1242 // remaining "quota" bytes are based on total usage in
1243 // current cycle. kernel doesn't like 0-byte rules, so we
1244 // set 1-byte quota and disable the radio later.
1245 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1246 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001247
1248 if (ifaces.length > 1) {
1249 // TODO: switch to shared quota once NMS supports
1250 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001251 }
1252
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001253 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001254 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001255 setInterfaceQuota(iface, quotaBytes);
1256 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001257 if (powerSave) {
1258 connIfaces.remove(iface);
1259 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001260 }
1261 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001262
1263 // keep track of lowest warning or limit of active policies
1264 if (hasWarning && policy.warningBytes < lowestRule) {
1265 lowestRule = policy.warningBytes;
1266 }
1267 if (hasLimit && policy.limitBytes < lowestRule) {
1268 lowestRule = policy.limitBytes;
1269 }
1270 }
1271
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001272 for (int i = connIfaces.size()-1; i >= 0; i--) {
1273 String iface = connIfaces.valueAt(i);
1274 removeInterfaceQuota(iface);
1275 setInterfaceQuota(iface, Long.MAX_VALUE);
1276 newMeteredIfaces.add(iface);
1277 }
1278
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001279 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001280
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001281 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001282 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1283 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001284 if (!newMeteredIfaces.contains(iface)) {
1285 removeInterfaceQuota(iface);
1286 }
1287 }
1288 mMeteredIfaces = newMeteredIfaces;
1289
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001290 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001291 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001292 }
1293
1294 /**
1295 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1296 * have at least a default mobile policy defined.
1297 */
1298 private void ensureActiveMobilePolicyLocked() {
1299 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001300 if (mSuppressDefaultPolicy) return;
1301
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001302 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001303 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001304
Jeff Sharkey32566012014-12-02 18:30:14 -08001305 final int[] subIds = sub.getActiveSubscriptionIdList();
1306 for (int subId : subIds) {
1307 final String subscriberId = tele.getSubscriberId(subId);
1308 ensureActiveMobilePolicyLocked(subscriberId);
1309 }
1310 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001311
Jeff Sharkey32566012014-12-02 18:30:14 -08001312 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1313 // Poke around to see if we already have a policy
1314 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1315 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1316 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1317 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1318 if (template.matches(probeIdent)) {
1319 if (LOGD) {
1320 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1321 + NetworkIdentity.scrubSubscriberId(subscriberId));
1322 }
1323 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001324 }
1325 }
1326
Jeff Sharkey32566012014-12-02 18:30:14 -08001327 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1328 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001329
Jeff Sharkey32566012014-12-02 18:30:14 -08001330 // Build default mobile policy, and assume usage cycle starts today
1331 final long warningBytes = mContext.getResources().getInteger(
1332 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001333
Jeff Sharkey32566012014-12-02 18:30:14 -08001334 final Time time = new Time();
1335 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001336
Jeff Sharkey32566012014-12-02 18:30:14 -08001337 final int cycleDay = time.monthDay;
1338 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001339
Jeff Sharkey32566012014-12-02 18:30:14 -08001340 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1341 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1342 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1343 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344 }
1345
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001347 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348
1349 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001350 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001351 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001352
1353 FileInputStream fis = null;
1354 try {
1355 fis = mPolicyFile.openRead();
1356 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001357 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358
1359 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001360 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001361 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001362 while ((type = in.next()) != END_DOCUMENT) {
1363 final String tag = in.getName();
1364 if (type == START_TAG) {
1365 if (TAG_POLICY_LIST.equals(tag)) {
1366 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001367 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1368 mRestrictBackground = readBooleanAttribute(
1369 in, ATTR_RESTRICT_BACKGROUND);
1370 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001371 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001372 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001373
1374 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1375 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1376 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001377 final String networkId;
1378 if (version >= VERSION_ADDED_NETWORK_ID) {
1379 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1380 } else {
1381 networkId = null;
1382 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001383 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001384 final String cycleTimezone;
1385 if (version >= VERSION_ADDED_TIMEZONE) {
1386 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1387 } else {
1388 cycleTimezone = Time.TIMEZONE_UTC;
1389 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001390 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1391 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001392 final long lastLimitSnooze;
1393 if (version >= VERSION_SPLIT_SNOOZE) {
1394 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1395 } else if (version >= VERSION_ADDED_SNOOZE) {
1396 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001397 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001398 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001400 final boolean metered;
1401 if (version >= VERSION_ADDED_METERED) {
1402 metered = readBooleanAttribute(in, ATTR_METERED);
1403 } else {
1404 switch (networkTemplate) {
1405 case MATCH_MOBILE_3G_LOWER:
1406 case MATCH_MOBILE_4G:
1407 case MATCH_MOBILE_ALL:
1408 metered = true;
1409 break;
1410 default:
1411 metered = false;
1412 }
1413 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001414 final long lastWarningSnooze;
1415 if (version >= VERSION_SPLIT_SNOOZE) {
1416 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1417 } else {
1418 lastWarningSnooze = SNOOZE_NEVER;
1419 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001420 final boolean inferred;
1421 if (version >= VERSION_ADDED_INFERRED) {
1422 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1423 } else {
1424 inferred = false;
1425 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001426
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1428 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001429 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001430 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001431 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001432
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001433 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434 final int uid = readIntAttribute(in, ATTR_UID);
1435 final int policy = readIntAttribute(in, ATTR_POLICY);
1436
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001437 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001438 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001439 } else {
1440 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1441 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001442 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001443 final int appId = readIntAttribute(in, ATTR_APP_ID);
1444 final int policy = readIntAttribute(in, ATTR_POLICY);
1445
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001446 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001447 // app policy is deprecated so this is only used in pre system user split.
1448 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001449 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001450 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001451 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001452 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001453 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001454 } else if (TAG_WHITELIST.equals(tag)) {
1455 insideWhitelist = true;
1456 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1457 final int uid = readIntAttribute(in, ATTR_UID);
1458 mRestrictBackgroundWhitelistUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001460 } else if (type == END_TAG) {
1461 if (TAG_WHITELIST.equals(tag)) {
1462 insideWhitelist = false;
1463 }
1464
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 }
1466 }
1467
1468 } catch (FileNotFoundException e) {
1469 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001470 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001471 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001472 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001474 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001475 } finally {
1476 IoUtils.closeQuietly(fis);
1477 }
1478 }
1479
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001480 /**
1481 * Upgrade legacy background data flags, notifying listeners of one last
1482 * change to always-true.
1483 */
1484 private void upgradeLegacyBackgroundData() {
1485 mRestrictBackground = Settings.Secure.getInt(
1486 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1487
1488 // kick off one last broadcast if restricted
1489 if (mRestrictBackground) {
1490 final Intent broadcast = new Intent(
1491 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001492 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001493 }
1494 }
1495
Dianne Hackborn497175b2014-07-01 12:56:08 -07001496 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001497 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498
1499 FileOutputStream fos = null;
1500 try {
1501 fos = mPolicyFile.startWrite();
1502
1503 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001504 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505 out.startDocument(null, true);
1506
1507 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001508 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001509 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510
1511 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001512 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1513 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001514 final NetworkTemplate template = policy.template;
1515
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001517 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1518 final String subscriberId = template.getSubscriberId();
1519 if (subscriberId != null) {
1520 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001521 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001522 final String networkId = template.getNetworkId();
1523 if (networkId != null) {
1524 out.attribute(null, ATTR_NETWORK_ID, networkId);
1525 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001526 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001527 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1529 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001530 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1531 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001532 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001533 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534 out.endTag(null, TAG_NETWORK_POLICY);
1535 }
1536
1537 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001538 for (int i = 0; i < mUidPolicy.size(); i++) {
1539 final int uid = mUidPolicy.keyAt(i);
1540 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541
Jeff Sharkey497e4432011-06-14 17:27:29 -07001542 // skip writing empty policies
1543 if (policy == POLICY_NONE) continue;
1544
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001545 out.startTag(null, TAG_UID_POLICY);
1546 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001548 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 }
1550
1551 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001552
1553 // write all whitelists
1554 out.startTag(null, TAG_WHITELIST);
1555
1556 // restrict background whitelist
1557 final int size = mRestrictBackgroundWhitelistUids.size();
1558 for (int i = 0; i < size; i++) {
1559 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1560 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1561 writeIntAttribute(out, ATTR_UID, uid);
1562 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1563 }
1564
1565 out.endTag(null, TAG_WHITELIST);
1566
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 out.endDocument();
1568
1569 mPolicyFile.finishWrite(fos);
1570 } catch (IOException e) {
1571 if (fos != null) {
1572 mPolicyFile.failWrite(fos);
1573 }
1574 }
1575 }
1576
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001577 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001578 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001580
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001581 if (!UserHandle.isApp(uid)) {
1582 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001583 }
1584
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001585 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001586 final long token = Binder.clearCallingIdentity();
1587 try {
1588 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1589 if (oldPolicy != policy) {
1590 setUidPolicyUncheckedLocked(uid, policy, true);
1591 }
1592 } finally {
1593 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001594 }
1595 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001596 }
1597
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001598 @Override
1599 public void addUidPolicy(int uid, int policy) {
1600 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001601
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001602 if (!UserHandle.isApp(uid)) {
1603 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1604 }
1605
1606 synchronized (mRulesLock) {
1607 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1608 policy |= oldPolicy;
1609 if (oldPolicy != policy) {
1610 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001611 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001613 }
1614
1615 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001616 public void removeUidPolicy(int uid, int policy) {
1617 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1618
1619 if (!UserHandle.isApp(uid)) {
1620 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1621 }
1622
1623 synchronized (mRulesLock) {
1624 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1625 policy = oldPolicy & ~policy;
1626 if (oldPolicy != policy) {
1627 setUidPolicyUncheckedLocked(uid, policy, true);
1628 }
1629 }
1630 }
1631
1632 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1633 mUidPolicy.put(uid, policy);
1634
1635 // uid policy changed, recompute rules and persist policy.
1636 updateRulesForUidLocked(uid);
1637 if (persist) {
1638 writePolicyLocked();
1639 }
1640 }
1641
1642 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001643 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1645
Jeff Sharkeya4620792011-05-20 15:29:23 -07001646 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001647 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001648 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001649 }
1650
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001651 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001652 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001653 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1654
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001655 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001656 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001657 for (int i = 0; i < mUidPolicy.size(); i++) {
1658 final int uid = mUidPolicy.keyAt(i);
1659 final int uidPolicy = mUidPolicy.valueAt(i);
1660 if (uidPolicy == policy) {
1661 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001662 }
1663 }
1664 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001665 return uids;
1666 }
1667
1668 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001669 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001670 * if any changes are made.
1671 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001672 void removeUserStateLocked(int userId) {
1673 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1674 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001675
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001676 // Remove entries from restricted background UID whitelist
1677 int[] wlUids = new int[0];
1678 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1679 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1680 if (UserHandle.getUserId(uid) == userId) {
1681 wlUids = appendInt(wlUids, uid);
1682 }
1683 }
1684
1685 if (wlUids.length > 0) {
1686 for (int uid : wlUids) {
1687 removeRestrictBackgroundWhitelistedUidLocked(uid, false);
1688 }
1689 writePolicy = true;
1690 }
1691
1692 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001693 int[] uids = new int[0];
1694 for (int i = 0; i < mUidPolicy.size(); i++) {
1695 final int uid = mUidPolicy.keyAt(i);
1696 if (UserHandle.getUserId(uid) == userId) {
1697 uids = appendInt(uids, uid);
1698 }
1699 }
1700
1701 if (uids.length > 0) {
1702 for (int uid : uids) {
1703 mUidPolicy.delete(uid);
1704 updateRulesForUidLocked(uid);
1705 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001706 writePolicy = true;
1707 }
1708
1709 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001710 writePolicyLocked();
1711 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001712 }
1713
1714 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001715 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001716 // TODO: create permission for observing network policy
1717 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1718
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001719 mListeners.register(listener);
1720
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001721 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001722 }
1723
1724 @Override
1725 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001726 // TODO: create permission for observing network policy
1727 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001729 mListeners.unregister(listener);
1730 }
1731
Jeff Sharkey1b861272011-05-22 00:34:52 -07001732 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001733 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001734 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1735
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001736 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001737 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001738 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001739 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001740 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001741 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001742 writePolicyLocked();
1743 }
1744 }
1745
Dianne Hackborn497175b2014-07-01 12:56:08 -07001746 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001747 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001748 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1749 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001750 }
1751
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001752 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001753 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001754 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001755 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001756 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1757 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1758 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001759 } catch (SecurityException e) {
1760 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001761
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001762 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1763 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1764 return new NetworkPolicy[0];
1765 }
Svet Ganov16a16892015-04-16 10:32:04 -07001766 }
1767
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001768 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001769 final int size = mNetworkPolicy.size();
1770 final NetworkPolicy[] policies = new NetworkPolicy[size];
1771 for (int i = 0; i < size; i++) {
1772 policies[i] = mNetworkPolicy.valueAt(i);
1773 }
1774 return policies;
1775 }
1776 }
1777
1778 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001779 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001780 }
1781
1782 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1783 final TelephonyManager tele = TelephonyManager.from(mContext);
1784 final String[] merged = tele.getMergedSubscriberIds();
1785
1786 mNetworkPolicy.clear();
1787 for (NetworkPolicy policy : policies) {
1788 // When two normalized templates conflict, prefer the most
1789 // restrictive policy
1790 policy.template = NetworkTemplate.normalize(policy.template, merged);
1791 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1792 if (existing == null || existing.compareTo(policy) > 0) {
1793 if (existing != null) {
1794 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1795 }
1796 mNetworkPolicy.put(policy.template, policy);
1797 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001798 }
1799 }
1800
1801 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001802 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001803 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001804
1805 final long token = Binder.clearCallingIdentity();
1806 try {
1807 performSnooze(template, TYPE_LIMIT);
1808 } finally {
1809 Binder.restoreCallingIdentity(token);
1810 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001811 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001812
Dianne Hackborn497175b2014-07-01 12:56:08 -07001813 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001814 maybeRefreshTrustedTime();
1815 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001816 synchronized (mRulesLock) {
1817 // find and snooze local policy that matches
1818 final NetworkPolicy policy = mNetworkPolicy.get(template);
1819 if (policy == null) {
1820 throw new IllegalArgumentException("unable to find policy for " + template);
1821 }
1822
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001823 switch (type) {
1824 case TYPE_WARNING:
1825 policy.lastWarningSnooze = currentTime;
1826 break;
1827 case TYPE_LIMIT:
1828 policy.lastLimitSnooze = currentTime;
1829 break;
1830 default:
1831 throw new IllegalArgumentException("unexpected type");
1832 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001833
Jeff Sharkey32566012014-12-02 18:30:14 -08001834 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001835 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001836 updateNetworkRulesLocked();
1837 updateNotificationsLocked();
1838 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001839 }
1840 }
1841
1842 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001843 public void setRestrictBackground(boolean restrictBackground) {
1844 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1845
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001846 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001847 synchronized (mRulesLock) {
1848 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001849 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001850 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001851 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001852 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001853
1854 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1855 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001856 }
1857
1858 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001859 public void addRestrictBackgroundWhitelistedUid(int uid) {
1860 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1861 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
1862 synchronized (mRulesLock) {
1863 mRestrictBackgroundWhitelistUids.append(uid, true);
1864 writePolicyLocked();
1865 // TODO: call other update methods like updateNetworkRulesLocked?
1866 }
1867 }
1868
1869 @Override
1870 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1871 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1872 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1873 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001874 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001875 }
1876 }
1877
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001878 private void removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean writePolicy) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08001879 mRestrictBackgroundWhitelistUids.delete(uid);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001880 if (writePolicy) {
1881 writePolicyLocked();
1882 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001883 }
1884
1885 @Override
1886 public int[] getRestrictBackgroundWhitelistedUids() {
1887 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1888 synchronized (mRulesLock) {
1889 final int size = mRestrictBackgroundWhitelistUids.size();
1890 final int[] whitelist = new int[size];
1891 for (int i = 0; i < size; i++) {
1892 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1893 }
1894 if (LOGV) {
1895 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1896 + mRestrictBackgroundWhitelistUids);
1897 }
1898 return whitelist;
1899 }
1900 }
1901
1902 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08001903 public int getRestrictBackgroundByCaller() {
1904 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1905 final int uid = Binder.getCallingUid();
1906 synchronized (mRulesLock) {
1907 if (!mRestrictBackground) {
1908 return RESTRICT_BACKGROUND_STATUS_DISABLED;
1909 }
1910 return mRestrictBackgroundWhitelistUids.get(uid)
1911 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
1912 : RESTRICT_BACKGROUND_STATUS_ENABLED;
1913 }
1914 }
1915
1916 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001917 public boolean getRestrictBackground() {
1918 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1919
1920 synchronized (mRulesLock) {
1921 return mRestrictBackground;
1922 }
1923 }
1924
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001925 @Override
1926 public void setDeviceIdleMode(boolean enabled) {
1927 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1928
1929 synchronized (mRulesLock) {
1930 if (mDeviceIdleMode != enabled) {
1931 mDeviceIdleMode = enabled;
1932 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001933 // Device idle change means we need to rebuild rules for all
1934 // known apps, so do a global refresh.
1935 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001936 }
1937 if (enabled) {
1938 EventLogTags.writeDeviceIdleOnPhase("net");
1939 } else {
1940 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001941 }
1942 }
1943 }
1944 }
1945
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001946 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001947 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1948 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001949 if (policy.template.matches(ident)) {
1950 return policy;
1951 }
1952 }
1953 return null;
1954 }
1955
1956 @Override
1957 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1958 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1959
1960 // only returns usage summary, so we don't require caller to have
1961 // READ_NETWORK_USAGE_HISTORY.
1962 final long token = Binder.clearCallingIdentity();
1963 try {
1964 return getNetworkQuotaInfoUnchecked(state);
1965 } finally {
1966 Binder.restoreCallingIdentity(token);
1967 }
1968 }
1969
1970 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1971 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1972
1973 final NetworkPolicy policy;
1974 synchronized (mRulesLock) {
1975 policy = findPolicyForNetworkLocked(ident);
1976 }
1977
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001978 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001979 // missing policy means we can't derive useful quota info
1980 return null;
1981 }
1982
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001983 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001984
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001985 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001986 final long start = computeLastCycleBoundary(currentTime, policy);
1987 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001988 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001989
1990 // report soft and hard limits under policy
1991 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1992 : NetworkQuotaInfo.NO_LIMIT;
1993 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1994 : NetworkQuotaInfo.NO_LIMIT;
1995
1996 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1997 }
1998
Jeff Sharkey46645002011-07-27 21:11:21 -07001999 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002000 public boolean isNetworkMetered(NetworkState state) {
2001 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2002
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002003 // roaming networks are always considered metered
2004 if (ident.getRoaming()) {
2005 return true;
2006 }
2007
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002008 final NetworkPolicy policy;
2009 synchronized (mRulesLock) {
2010 policy = findPolicyForNetworkLocked(ident);
2011 }
2012
2013 if (policy != null) {
2014 return policy.metered;
2015 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08002016 if (state.networkInfo == null) {
2017 return false;
2018 }
2019
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002020 final int type = state.networkInfo.getType();
2021 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2022 return true;
2023 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002024 return false;
2025 }
2026 }
2027
2028 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002029 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002030 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002031
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002032 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2033
Dianne Hackborn497175b2014-07-01 12:56:08 -07002034 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002035 for (String arg : args) {
2036 argSet.add(arg);
2037 }
2038
Jeff Sharkey1b861272011-05-22 00:34:52 -07002039 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002040 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002041 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2042 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002043 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002044
Jeff Sharkey32566012014-12-02 18:30:14 -08002045 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002046 updateNetworkEnabledLocked();
2047 updateNetworkRulesLocked();
2048 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002049 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002050
2051 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002052 return;
2053 }
2054
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002055 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002056 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002057 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002058 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002059 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002060 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002061 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2062 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002063 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002064 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002065
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002066 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2067
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002068 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002069 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002070 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002071 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002072 final int uid = mUidPolicy.keyAt(i);
2073 final int policy = mUidPolicy.valueAt(i);
2074 fout.print("UID=");
2075 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002076 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002077 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002078 fout.println();
2079 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002080 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002081
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002082 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2083 if (size > 0) {
2084 fout.println("Power save whitelist (except idle) app ids:");
2085 fout.increaseIndent();
2086 for (int i = 0; i < size; i++) {
2087 fout.print("UID=");
2088 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2089 fout.print(": ");
2090 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2091 fout.println();
2092 }
2093 fout.decreaseIndent();
2094 }
2095
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002096 size = mPowerSaveWhitelistAppIds.size();
2097 if (size > 0) {
2098 fout.println("Power save whitelist app ids:");
2099 fout.increaseIndent();
2100 for (int i = 0; i < size; i++) {
2101 fout.print("UID=");
2102 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2103 fout.print(": ");
2104 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2105 fout.println();
2106 }
2107 fout.decreaseIndent();
2108 }
2109
Felipe Lemeb85a6372016-01-14 16:16:16 -08002110 size = mRestrictBackgroundWhitelistUids.size();
2111 if (size > 0) {
2112 fout.println("Restrict background whitelist uids:");
2113 fout.increaseIndent();
2114 for (int i = 0; i < size; i++) {
2115 fout.print("UID=");
2116 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2117 fout.println();
2118 }
2119 fout.decreaseIndent();
2120 }
2121
Jeff Sharkey1b861272011-05-22 00:34:52 -07002122 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002123 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002124 collectKeys(mUidRules, knownUids);
2125
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002126 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002127 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002128 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002129 for (int i = 0; i < size; i++) {
2130 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002131 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002132 fout.print(uid);
2133
Jeff Sharkeydc988062015-09-14 10:09:47 -07002134 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002135 fout.print(" state=");
2136 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002137 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002138
Jeff Sharkeydc988062015-09-14 10:09:47 -07002139 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2140 fout.print(" rule=");
2141 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002142
2143 fout.println();
2144 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002145 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002146 }
2147 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002148
2149 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002150 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2151 String[] args, ResultReceiver resultReceiver) throws RemoteException {
2152 (new NetworkPolicyManagerShellCommand(this)).exec(
2153 this, in, out, err, args, resultReceiver);
2154 }
2155
2156 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002157 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002158 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2159
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002160 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002161 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002162 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002163 }
2164
Dianne Hackborn497175b2014-07-01 12:56:08 -07002165 boolean isUidForegroundLocked(int uid) {
2166 // only really in foreground when screen is also on
2167 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002168 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002169 }
2170
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002171 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002172 * Process state of UID changed; if needed, will trigger
2173 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002174 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002175 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002176 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2177 if (oldUidState != uidState) {
2178 // state changed, push updated rules
2179 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002180 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002181 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2182 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002183 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002184 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002185 }
2186 }
2187
2188 void removeUidStateLocked(int uid) {
2189 final int index = mUidState.indexOfKey(uid);
2190 if (index >= 0) {
2191 final int oldUidState = mUidState.valueAt(index);
2192 mUidState.removeAt(index);
2193 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2194 updateRulesForUidStateChangeLocked(uid, oldUidState,
2195 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002196 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002197 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002198 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002199 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002200 }
2201 }
2202
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002203 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002204 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2205 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002206 if (oldForeground != newForeground) {
2207 updateRulesForUidLocked(uid);
2208 }
2209 }
2210
Jeff Sharkeya4620792011-05-20 15:29:23 -07002211 private void updateScreenOn() {
2212 synchronized (mRulesLock) {
2213 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002214 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002215 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002216 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002217 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002218 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002219 }
2220 }
2221
2222 /**
2223 * Update rules that might be changed by {@link #mScreenOn} value.
2224 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002225 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002226 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002227 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002228 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002229 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002230 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002231 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002232 }
2233 }
2234 }
2235
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002236 static boolean isProcStateAllowedWhileIdle(int procState) {
2237 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2238 }
2239
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002240 void updateRulesForDeviceIdleLocked() {
2241 if (mDeviceIdleMode) {
2242 // sync the whitelists before enable dozable chain. We don't care about the rules if
2243 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002244 final SparseIntArray uidRules = mUidFirewallDozableRules;
2245 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002246 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002247 for (int ui = users.size() - 1; ui >= 0; ui--) {
2248 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002249 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002250 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2251 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2252 int uid = UserHandle.getUid(user.id, appId);
2253 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2254 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002255 }
2256 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2257 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2258 int uid = UserHandle.getUid(user.id, appId);
2259 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2260 }
2261 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002262 for (int i = mUidState.size() - 1; i >= 0; i--) {
2263 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2264 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2265 }
2266 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002267 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2268 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002269
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002270 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2271 }
2272
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002273 void updateRuleForDeviceIdleLocked(int uid) {
2274 if (mDeviceIdleMode) {
2275 int appId = UserHandle.getAppId(uid);
2276 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2277 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2278 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2279 } else {
2280 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2281 }
2282 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002283
2284 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002285 }
2286
2287 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002288 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2289 uidRules.clear();
2290
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002291 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002292 final List<UserInfo> users = mUserManager.getUsers();
2293 for (int ui = users.size() - 1; ui >= 0; ui--) {
2294 UserInfo user = users.get(ui);
2295 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2296 for (int uid : idleUids) {
2297 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2298 uidRules.put(uid, FIREWALL_RULE_DENY);
2299 }
2300 }
2301 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002302
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002303 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2304 }
2305
2306 void updateRuleForAppIdleLocked(int uid) {
2307 if (!isUidValidForRules(uid)) return;
2308
2309 int appId = UserHandle.getAppId(uid);
2310 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2311 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2312 } else {
2313 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2314 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002315
2316 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002317 }
2318
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002319 void updateRulesForAppIdleParoleLocked() {
2320 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2321 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002322 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002323 }
2324
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002325 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002326 * Update rules that might be changed by {@link #mRestrictBackground},
2327 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002328 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002329 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002330 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002331
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002332 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002333 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002334
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002335 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002336 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002337 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002338 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2339 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002340
2341 for (UserInfo user : users) {
2342 for (ApplicationInfo app : apps) {
2343 final int uid = UserHandle.getUid(user.id, app.uid);
2344 updateRulesForUidLocked(uid);
2345 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002346 }
2347
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002348 // limit data usage for some internal system services
2349 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2350 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002351
2352 // If the set of restricted networks may have changed, re-evaluate those.
2353 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002354 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002355 updateNetworkRulesLocked();
2356 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002357 }
2358
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002359 void updateRulesForTempWhitelistChangeLocked() {
2360 final List<UserInfo> users = mUserManager.getUsers();
2361 for (UserInfo user : users) {
2362 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2363 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2364 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002365 updateRuleForAppIdleLocked(uid);
2366 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002367 }
2368 }
2369 }
2370
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002371 private static boolean isUidValidForRules(int uid) {
2372 // allow rules on specific system services, and any apps
2373 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002374 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002375 return true;
2376 }
2377
2378 return false;
2379 }
2380
Amith Yamasani15e472352015-04-24 19:06:07 -07002381 private boolean isUidIdle(int uid) {
2382 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2383 final int userId = UserHandle.getUserId(uid);
2384
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002385 if (!ArrayUtils.isEmpty(packages)) {
2386 for (String packageName : packages) {
2387 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2388 return false;
2389 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002390 }
2391 }
2392 return true;
2393 }
2394
Jeff Sharkeydc988062015-09-14 10:09:47 -07002395 void updateRulesForUidsLocked(SparseIntArray uids) {
2396 for (int i = 0; i < uids.size(); i++) {
2397 updateRulesForUidLocked(uids.keyAt(i));
2398 }
2399 }
2400
Amith Yamasani15e472352015-04-24 19:06:07 -07002401 /**
2402 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2403 * @param uid The uid for which to apply the latest policy
2404 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002405 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002406 if (!isUidValidForRules(uid)) return;
2407
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002408 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2409 // network access anyway, so it is a waste to mess with it here.
2410 final IPackageManager ipm = AppGlobals.getPackageManager();
2411 try {
2412 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2413 != PackageManager.PERMISSION_GRANTED) {
2414 return;
2415 }
2416 } catch (RemoteException e) {
2417 }
2418
Dianne Hackborn497175b2014-07-01 12:56:08 -07002419 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2420 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002421
Jeff Sharkeydc988062015-09-14 10:09:47 -07002422 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002423 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002424 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002425 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002426 // uid in background, and policy says to block metered data
2427 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002428 } else if (mRestrictBackground) {
2429 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002430 // uid in background, global background disabled, and this uid is not on the white
2431 // list of those allowed background access while global background is disabled
2432 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2433 uidRules = RULE_REJECT_METERED;
2434 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002435 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002436 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002437 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002438 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002439 if (!whitelisted && !uidForeground
2440 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2441 // uid is in background, restrict power use mode is on (so we want to
2442 // restrict all background network access), and this uid is not on the
2443 // white list of those allowed background access.
2444 uidRules = RULE_REJECT_METERED;
2445 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002446 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002447
Jeff Sharkeydc988062015-09-14 10:09:47 -07002448 // Check dozable state, which is whitelist
2449 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2450 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2451 uidRules = RULE_REJECT_ALL;
2452 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002453
Jeff Sharkeydc988062015-09-14 10:09:47 -07002454 // Check standby state, which is blacklist
2455 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2456 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2457 uidRules = RULE_REJECT_ALL;
2458 }
2459
2460 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002461 if (uidRules == RULE_ALLOW_ALL) {
2462 mUidRules.delete(uid);
2463 } else {
2464 mUidRules.put(uid, uidRules);
2465 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002466
Jeff Sharkeydc988062015-09-14 10:09:47 -07002467 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2468 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002469
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002470 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002471 if (oldRules != uidRules) {
2472 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2473 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002474
2475 try {
2476 // adjust stats accounting based on foreground status
2477 mNetworkStats.setUidForeground(uid, uidForeground);
2478 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002479 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002480 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002481 }
2482
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002483 private class AppIdleStateChangeListener
2484 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2485
2486 @Override
2487 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2488 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002489 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2490 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002491 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002492 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002493 }
2494 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002495 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002496 }
2497
2498 @Override
2499 public void onParoleStateChanged(boolean isParoleOn) {
2500 synchronized (mRulesLock) {
2501 updateRulesForAppIdleParoleLocked();
2502 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002503 }
2504 }
2505
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002506 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002507 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002508 public boolean handleMessage(Message msg) {
2509 switch (msg.what) {
2510 case MSG_RULES_CHANGED: {
2511 final int uid = msg.arg1;
2512 final int uidRules = msg.arg2;
2513 final int length = mListeners.beginBroadcast();
2514 for (int i = 0; i < length; i++) {
2515 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2516 if (listener != null) {
2517 try {
2518 listener.onUidRulesChanged(uid, uidRules);
2519 } catch (RemoteException e) {
2520 }
2521 }
2522 }
2523 mListeners.finishBroadcast();
2524 return true;
2525 }
2526 case MSG_METERED_IFACES_CHANGED: {
2527 final String[] meteredIfaces = (String[]) msg.obj;
2528 final int length = mListeners.beginBroadcast();
2529 for (int i = 0; i < length; i++) {
2530 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2531 if (listener != null) {
2532 try {
2533 listener.onMeteredIfacesChanged(meteredIfaces);
2534 } catch (RemoteException e) {
2535 }
2536 }
2537 }
2538 mListeners.finishBroadcast();
2539 return true;
2540 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002541 case MSG_LIMIT_REACHED: {
2542 final String iface = (String) msg.obj;
2543
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002544 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002545 synchronized (mRulesLock) {
2546 if (mMeteredIfaces.contains(iface)) {
2547 try {
2548 // force stats update to make sure we have
2549 // numbers that caused alert to trigger.
2550 mNetworkStats.forceUpdate();
2551 } catch (RemoteException e) {
2552 // ignored; service lives in system_server
2553 }
2554
2555 updateNetworkEnabledLocked();
2556 updateNotificationsLocked();
2557 }
2558 }
2559 return true;
2560 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002561 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2562 final boolean restrictBackground = msg.arg1 != 0;
2563 final int length = mListeners.beginBroadcast();
2564 for (int i = 0; i < length; i++) {
2565 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2566 if (listener != null) {
2567 try {
2568 listener.onRestrictBackgroundChanged(restrictBackground);
2569 } catch (RemoteException e) {
2570 }
2571 }
2572 }
2573 mListeners.finishBroadcast();
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002574 return true;
2575 }
2576 case MSG_ADVISE_PERSIST_THRESHOLD: {
2577 final long lowestRule = (Long) msg.obj;
2578 try {
2579 // make sure stats are recorded frequently enough; we aim
2580 // for 2MB threshold for 2GB/month rules.
2581 final long persistThreshold = lowestRule / 1000;
2582 mNetworkStats.advisePersistThreshold(persistThreshold);
2583 } catch (RemoteException e) {
2584 // ignored; service lives in system_server
2585 }
2586 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002587 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002588 case MSG_SCREEN_ON_CHANGED: {
2589 updateScreenOn();
2590 return true;
2591 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002592 default: {
2593 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002594 }
2595 }
2596 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002597 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002598
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002599 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002600 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002601 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002602 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002603 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002604 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002605 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002606 }
2607 }
2608
2609 private void removeInterfaceQuota(String iface) {
2610 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002611 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002612 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002613 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002614 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002615 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002616 }
2617 }
2618
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002619 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2620 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002621 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002622 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002623 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002624 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002625 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002626 }
2627 }
2628
Amith Yamasani15e472352015-04-24 19:06:07 -07002629 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002630 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2631 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2632 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002633 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002634 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002635 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002636 int size = uidRules.size();
2637 int[] uids = new int[size];
2638 int[] rules = new int[size];
2639 for(int index = size - 1; index >= 0; --index) {
2640 uids[index] = uidRules.keyAt(index);
2641 rules[index] = uidRules.valueAt(index);
2642 }
2643 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002644 } catch (IllegalStateException e) {
2645 Log.wtf(TAG, "problem setting firewall uid rules", e);
2646 } catch (RemoteException e) {
2647 // ignored; service lives in system_server
2648 }
2649 }
2650
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002651 /**
2652 * Add or remove a uid to the firewall blacklist for all network ifaces.
2653 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002654 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002655 if (chain == FIREWALL_CHAIN_DOZABLE) {
2656 mUidFirewallDozableRules.put(uid, rule);
2657 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2658 mUidFirewallStandbyRules.put(uid, rule);
2659 }
2660
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002661 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002662 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002663 } catch (IllegalStateException e) {
2664 Log.wtf(TAG, "problem setting firewall uid rules", e);
2665 } catch (RemoteException e) {
2666 // ignored; service lives in system_server
2667 }
2668 }
2669
2670 /**
2671 * Add or remove a uid to the firewall blacklist for all network ifaces.
2672 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002673 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002674 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2675 mFirewallChainStates.get(chain) == enable) {
2676 // All is the same, nothing to do.
2677 return;
2678 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002679 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002680 try {
2681 mNetworkManager.setFirewallChainEnabled(chain, enable);
2682 } catch (IllegalStateException e) {
2683 Log.wtf(TAG, "problem enable firewall chain", e);
2684 } catch (RemoteException e) {
2685 // ignored; service lives in system_server
2686 }
2687 }
2688
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002689 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2690 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002691 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002692 } catch (RuntimeException e) {
2693 Slog.w(TAG, "problem reading network stats: " + e);
2694 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002695 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002696 // ignored; service lives in system_server
2697 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002698 }
2699 }
2700
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002701 private boolean isBandwidthControlEnabled() {
2702 final long token = Binder.clearCallingIdentity();
2703 try {
2704 return mNetworkManager.isBandwidthControlEnabled();
2705 } catch (RemoteException e) {
2706 // ignored; service lives in system_server
2707 return false;
2708 } finally {
2709 Binder.restoreCallingIdentity(token);
2710 }
2711 }
2712
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002713 /**
2714 * Try refreshing {@link #mTime} when stale.
2715 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002716 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002717 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002718 mTime.forceRefresh();
2719 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002720 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002721
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002722 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002723 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2724 }
2725
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002726 private static Intent buildAllowBackgroundDataIntent() {
2727 return new Intent(ACTION_ALLOW_BACKGROUND);
2728 }
2729
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002730 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2731 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2732 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2733 return intent;
2734 }
2735
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002736 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2737 final Intent intent = new Intent();
2738 intent.setComponent(new ComponentName(
2739 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2740 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2741 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2742 return intent;
2743 }
2744
2745 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2746 final Intent intent = new Intent();
2747 intent.setComponent(new ComponentName(
2748 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2749 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2750 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2751 return intent;
2752 }
2753
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002754 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002755 public void addIdleHandler(IdleHandler handler) {
2756 mHandler.getLooper().getQueue().addIdleHandler(handler);
2757 }
2758
Jeff Sharkey1b861272011-05-22 00:34:52 -07002759 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2760 final int size = source.size();
2761 for (int i = 0; i < size; i++) {
2762 target.put(source.keyAt(i), true);
2763 }
2764 }
2765
Stuart Scottf1fb3972015-04-02 18:00:02 -07002766 @Override
2767 public void factoryReset(String subscriber) {
2768 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2769
Stuart Scotte3e314d2015-04-20 14:07:45 -07002770 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2771 return;
2772 }
2773
Stuart Scottf1fb3972015-04-02 18:00:02 -07002774 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002775 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002776 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2777 for (NetworkPolicy policy : policies) {
2778 if (policy.template.equals(template)) {
2779 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2780 policy.inferred = false;
2781 policy.clearSnooze();
2782 }
2783 }
2784 setNetworkPolicies(policies);
2785
2786 // Turn restrict background data off
2787 setRestrictBackground(false);
2788
Stuart Scotte3e314d2015-04-20 14:07:45 -07002789 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2790 // Remove app's "restrict background data" flag
2791 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2792 setUidPolicy(uid, POLICY_NONE);
2793 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002794 }
2795 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002796
2797 private class MyPackageMonitor extends PackageMonitor {
2798
2799 @Override
2800 public void onPackageRemoved(String packageName, int uid) {
2801 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2802 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002803 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002804 }
2805 }
2806
2807 @Override
2808 public void onPackageRemovedAllUsers(String packageName, int uid) {
2809 if (LOGV) Slog.v(TAG, "onPackageRemovedAllUsers: " + packageName + " ->" + uid);
2810 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002811 removeRestrictBackgroundWhitelistedUidLocked(uid, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002812 }
2813 }
2814 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002815}