blob: 9945b6e5ffe74742819289f28c91180acf6021b9 [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;
Felipe Leme9778f762016-01-27 14:46:39 -0800258 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700259
Jeff Sharkey75279902011-05-24 18:39:45 -0700260 private final Context mContext;
261 private final IActivityManager mActivityManager;
262 private final IPowerManager mPowerManager;
263 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700264 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700265 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700267 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
269 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700270 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700271 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700272 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700273
Dianne Hackborn497175b2014-07-01 12:56:08 -0700274 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700275
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700276 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700277 volatile boolean mScreenOn;
278 volatile boolean mRestrictBackground;
279 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700280 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700281
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700282 private final boolean mSuppressDefaultPolicy;
283
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700284 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800285 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800287 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700288
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700289 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700290 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700291 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700293
Jeff Sharkeydc988062015-09-14 10:09:47 -0700294 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
295 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
296
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700297 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700298 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
299
Jeff Sharkey32566012014-12-02 18:30:14 -0800300 /**
301 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700302 * in power save mode, except device idle (doze) still applies.
303 * TODO: An int array might be sufficient
304 */
305 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
306
307 /**
308 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800309 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700310 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800311 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700312 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700313
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700314 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
315
Felipe Lemeb85a6372016-01-14 16:16:16 -0800316 /**
317 * UIDs that have been white-listed to avoid restricted background.
318 */
319 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
320
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700321 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700323 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800324 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700325
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700327 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700328
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700329 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800330 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700331
Jeff Sharkey32566012014-12-02 18:30:14 -0800332 private final RemoteCallbackList<INetworkPolicyListener>
333 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700334
Dianne Hackborn497175b2014-07-01 12:56:08 -0700335 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700336
337 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700338
Svet Ganov16a16892015-04-16 10:32:04 -0700339 private final AppOpsManager mAppOps;
340
Felipe Lemeb85a6372016-01-14 16:16:16 -0800341 private final MyPackageMonitor mPackageMonitor;
342
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700343 // TODO: keep whitelist of system-critical services that should never have
344 // rules enforced, such as system, phone, and radio UIDs.
345
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 // TODO: migrate notifications to SystemUI
347
Jeff Sharkey75279902011-05-24 18:39:45 -0700348 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700349 IPowerManager powerManager, INetworkStatsService networkStats,
350 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700351 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700352 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700353 }
354
355 private static File getSystemDir() {
356 return new File(Environment.getDataDirectory(), "system");
357 }
358
359 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700360 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700361 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
362 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700363 mContext = checkNotNull(context, "missing context");
364 mActivityManager = checkNotNull(activityManager, "missing activityManager");
365 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700366 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700367 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700368 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700369 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700370 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700371 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700372
Amith Yamasani450a16b2013-09-18 16:28:50 -0700373 HandlerThread thread = new HandlerThread(TAG);
374 thread.start();
375 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700376
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700377 mSuppressDefaultPolicy = suppressDefaultPolicy;
378
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700379 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700380
381 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800382
383 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700384 }
385
386 public void bindConnectivityManager(IConnectivityManager connManager) {
387 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700388 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700389
Jeff Sharkey497e4432011-06-14 17:27:29 -0700390 public void bindNotificationManager(INotificationManager notifManager) {
391 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
392 }
393
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700394 void updatePowerSaveWhitelistLocked() {
395 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700396 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
397 mPowerSaveWhitelistExceptIdleAppIds.clear();
398 if (whitelist != null) {
399 for (int uid : whitelist) {
400 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
401 }
402 }
403 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700404 mPowerSaveWhitelistAppIds.clear();
405 if (whitelist != null) {
406 for (int uid : whitelist) {
407 mPowerSaveWhitelistAppIds.put(uid, true);
408 }
409 }
410 } catch (RemoteException e) {
411 }
412 }
413
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700414 void updatePowerSaveTempWhitelistLocked() {
415 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700416 // Clear the states of the current whitelist
417 final int N = mPowerSaveTempWhitelistAppIds.size();
418 for (int i = 0; i < N; i++) {
419 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
420 }
421 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700422 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700423 if (whitelist != null) {
424 for (int uid : whitelist) {
425 mPowerSaveTempWhitelistAppIds.put(uid, true);
426 }
427 }
428 } catch (RemoteException e) {
429 }
430 }
431
Amith Yamasani06f08062015-06-12 13:23:33 -0700432 /**
433 * Remove unnecessary entries in the temp whitelist
434 */
435 void purgePowerSaveTempWhitelistLocked() {
436 final int N = mPowerSaveTempWhitelistAppIds.size();
437 for (int i = N - 1; i >= 0; i--) {
438 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
439 mPowerSaveTempWhitelistAppIds.removeAt(i);
440 }
441 }
442 }
443
Jeff Sharkeya4620792011-05-20 15:29:23 -0700444 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700445 if (!isBandwidthControlEnabled()) {
446 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
447 return;
448 }
449
Amith Yamasani15e472352015-04-24 19:06:07 -0700450 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
451
Felipe Lemeb85a6372016-01-14 16:16:16 -0800452 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
453
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700454 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700455 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700456 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
457 mPowerManagerInternal.registerLowPowerModeObserver(
458 new PowerManagerInternal.LowPowerModeListener() {
459 @Override
460 public void onLowPowerModeChanged(boolean enabled) {
461 synchronized (mRulesLock) {
462 if (mRestrictPower != enabled) {
463 mRestrictPower = enabled;
464 updateRulesForGlobalChangeLocked(true);
465 }
466 }
467 }
468 });
469 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700470 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700471
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700472 // read policy from disk
473 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700474
Jeff Sharkeydc988062015-09-14 10:09:47 -0700475 updateRulesForGlobalChangeLocked(false);
476 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700477 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700478
Jeff Sharkeya4620792011-05-20 15:29:23 -0700479 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700480
Jeff Sharkeya4620792011-05-20 15:29:23 -0700481 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700482 mActivityManager.registerUidObserver(mUidObserver,
483 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700484 mNetworkManager.registerObserver(mAlertObserver);
485 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700486 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700487 }
488
Jeff Sharkeya4620792011-05-20 15:29:23 -0700489 // TODO: traverse existing processes to know foreground state, or have
490 // activitymanager dispatch current state when new observer attached.
491
492 final IntentFilter screenFilter = new IntentFilter();
493 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
494 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700495 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700496
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700497 // listen for changes to power save whitelist
498 final IntentFilter whitelistFilter = new IntentFilter(
499 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
500 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
501
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700502 DeviceIdleController.LocalService deviceIdleService
503 = LocalServices.getService(DeviceIdleController.LocalService.class);
504 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
505
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900507 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700508 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
509
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700510 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700511 final IntentFilter packageFilter = new IntentFilter();
512 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700513 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700514 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700515
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700516 // listen for UID changes to update policy
517 mContext.registerReceiver(
518 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
519
520 // listen for user changes to update policy
521 final IntentFilter userFilter = new IntentFilter();
522 userFilter.addAction(ACTION_USER_ADDED);
523 userFilter.addAction(ACTION_USER_REMOVED);
524 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
525
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700526 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700527 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
528 mContext.registerReceiver(
529 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
530
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700531 // listen for restrict background changes from notifications
532 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
533 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
534
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800535 // listen for snooze warning from notifications
536 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
537 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
538 MANAGE_NETWORK_POLICY, mHandler);
539
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700540 // listen for configured wifi networks to be removed
541 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700542 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700543
544 // listen for wifi state changes to catch metered hint
545 final IntentFilter wifiStateFilter = new IntentFilter(
546 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700547 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700548
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700549 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700550
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700551 }
552
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700553 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700554 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700555 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700556 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700557 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700558 }
559
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700560 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700561 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700562 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700563 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700564 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700565
566 @Override public void onUidActive(int uid) throws RemoteException {
567 }
568
569 @Override public void onUidIdle(int uid) throws RemoteException {
570 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700571 };
572
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700573 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700574 @Override
575 public void onReceive(Context context, Intent intent) {
576 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
577 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700578 updatePowerSaveWhitelistLocked();
579 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700580 }
581 }
582 };
583
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700584 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
585 @Override
586 public void run() {
587 synchronized (mRulesLock) {
588 updatePowerSaveTempWhitelistLocked();
589 updateRulesForTempWhitelistChangeLocked();
590 purgePowerSaveTempWhitelistLocked();
591 }
592 }
593 };
594
595 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700596 @Override
597 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800598 // screen-related broadcasts are protected by system, no need
599 // for permissions check.
600 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700601 }
602 };
603
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700604 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700605 @Override
606 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700607 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700608
609 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700610 final int uid = intent.getIntExtra(EXTRA_UID, -1);
611 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700612
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700613 if (ACTION_PACKAGE_ADDED.equals(action)) {
614 // update rules for UID, since it might be subject to
615 // global background data policy
616 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
617 synchronized (mRulesLock) {
618 updateRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700619 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700620 }
621 }
622 };
623
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700624 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700625 @Override
626 public void onReceive(Context context, Intent intent) {
627 // on background handler thread, and UID_REMOVED is protected
628
629 final int uid = intent.getIntExtra(EXTRA_UID, -1);
630 if (uid == -1) return;
631
632 // remove any policy and update rules to clean up
633 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
634 synchronized (mRulesLock) {
635 mUidPolicy.delete(uid);
636 updateRulesForUidLocked(uid);
637 writePolicyLocked();
638 }
639 }
640 };
641
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700642 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700643 @Override
644 public void onReceive(Context context, Intent intent) {
645 // on background handler thread, and USER_ADDED and USER_REMOVED
646 // broadcasts are protected
647
648 final String action = intent.getAction();
649 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
650 if (userId == -1) return;
651
Amith Yamasani15e472352015-04-24 19:06:07 -0700652 switch (action) {
653 case ACTION_USER_REMOVED:
654 case ACTION_USER_ADDED:
655 synchronized (mRulesLock) {
656 // Remove any policies for given user; both cleaning up after a
657 // USER_REMOVED, and one last sanity check during USER_ADDED
658 removePoliciesForUserLocked(userId);
659 // Update global restrict for new user
660 updateRulesForGlobalChangeLocked(true);
661 }
662 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700663 }
664 }
665 };
666
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700667 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700668 * Receiver that watches for {@link INetworkStatsService} updates, which we
669 * use to check against {@link NetworkPolicy#warningBytes}.
670 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700671 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700672 @Override
673 public void onReceive(Context context, Intent intent) {
674 // on background handler thread, and verified
675 // READ_NETWORK_USAGE_HISTORY permission above.
676
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800677 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700678 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700679 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700680 updateNotificationsLocked();
681 }
682 }
683 };
684
685 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700686 * Receiver that watches for {@link Notification} control of
687 * {@link #mRestrictBackground}.
688 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700689 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700690 @Override
691 public void onReceive(Context context, Intent intent) {
692 // on background handler thread, and verified MANAGE_NETWORK_POLICY
693 // permission above.
694
695 setRestrictBackground(false);
696 }
697 };
698
699 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800700 * Receiver that watches for {@link Notification} control of
701 * {@link NetworkPolicy#lastWarningSnooze}.
702 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700703 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800704 @Override
705 public void onReceive(Context context, Intent intent) {
706 // on background handler thread, and verified MANAGE_NETWORK_POLICY
707 // permission above.
708
709 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
710 performSnooze(template, TYPE_WARNING);
711 }
712 };
713
714 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700715 * Receiver that watches for {@link WifiConfiguration} to be changed.
716 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700717 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700718 @Override
719 public void onReceive(Context context, Intent intent) {
720 // on background handler thread, and verified CONNECTIVITY_INTERNAL
721 // permission above.
722
723 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
724 if (reason == CHANGE_REASON_REMOVED) {
725 final WifiConfiguration config = intent.getParcelableExtra(
726 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700727 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800728 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700729 synchronized (mRulesLock) {
730 if (mNetworkPolicy.containsKey(template)) {
731 mNetworkPolicy.remove(template);
732 writePolicyLocked();
733 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700734 }
735 }
736 }
737 }
738 };
739
740 /**
741 * Receiver that watches {@link WifiInfo} state changes to infer metered
742 * state. Ignores hints when policy is user-defined.
743 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700744 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700745 @Override
746 public void onReceive(Context context, Intent intent) {
747 // on background handler thread, and verified CONNECTIVITY_INTERNAL
748 // permission above.
749
750 // ignore when not connected
751 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
752 if (!netInfo.isConnected()) return;
753
754 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
755 final boolean meteredHint = info.getMeteredHint();
756
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800757 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700758 synchronized (mRulesLock) {
759 NetworkPolicy policy = mNetworkPolicy.get(template);
760 if (policy == null && meteredHint) {
761 // policy doesn't exist, and AP is hinting that it's
762 // metered: create an inferred policy.
763 policy = new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
764 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
765 meteredHint, true);
766 addNetworkPolicyLocked(policy);
767
768 } else if (policy != null && policy.inferred) {
769 // policy exists, and was inferred: update its current
770 // metered state.
771 policy.metered = meteredHint;
772
773 // since this is inferred for each wifi session, just update
774 // rules without persisting.
775 updateNetworkRulesLocked();
776 }
777 }
778 }
779 };
780
781 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700782 * Observer that watches for {@link INetworkManagementService} alerts.
783 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700784 final private INetworkManagementEventObserver mAlertObserver
785 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700786 @Override
787 public void limitReached(String limitName, String iface) {
788 // only someone like NMS should be calling us
789 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
790
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800791 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
792 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700793 }
794 }
795 };
796
797 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700798 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
799 * to show visible notifications as needed.
800 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700801 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
803
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700804 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700805 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700806 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807
808 // TODO: when switching to kernel notifications, compute next future
809 // cycle boundary to recompute notifications.
810
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700811 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800812 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700813 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
814 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700815 // ignore policies that aren't relevant to user
816 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700817 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700818
Jeff Sharkey497e4432011-06-14 17:27:29 -0700819 final long start = computeLastCycleBoundary(currentTime, policy);
820 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700821 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700822
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700823 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800824 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700825 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
826 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700827 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
828 notifyOverLimitLocked(policy.template);
829 }
830
Jeff Sharkey497e4432011-06-14 17:27:29 -0700831 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700832 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700833
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800834 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700835 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700836 }
837 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700838 }
839
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700840 // ongoing notification when restricting background data
841 if (mRestrictBackground) {
842 enqueueRestrictedNotification(TAG_ALLOW_BACKGROUND);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700843 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700844
845 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700846 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
847 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700848 if (!mActiveNotifs.contains(tag)) {
849 cancelNotification(tag);
850 }
851 }
852 }
853
854 /**
855 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700856 * current device state, such as when
857 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
858 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700859 */
860 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800861 if (template.isMatchRuleMobile()) {
862 final TelephonyManager tele = TelephonyManager.from(mContext);
863 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700864
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 // Mobile template is relevant when any active subscriber matches
866 final int[] subIds = sub.getActiveSubscriptionIdList();
867 for (int subId : subIds) {
868 final String subscriberId = tele.getSubscriberId(subId);
869 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
870 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
871 if (template.matches(probeIdent)) {
872 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700873 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800874 }
875 return false;
876 } else {
877 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700878 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700879 }
880
881 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700882 * Notify that given {@link NetworkTemplate} is over
883 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
884 */
885 private void notifyOverLimitLocked(NetworkTemplate template) {
886 if (!mOverLimitNotified.contains(template)) {
887 mContext.startActivity(buildNetworkOverLimitIntent(template));
888 mOverLimitNotified.add(template);
889 }
890 }
891
892 private void notifyUnderLimitLocked(NetworkTemplate template) {
893 mOverLimitNotified.remove(template);
894 }
895
896 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 * Build unique tag that identifies an active {@link NetworkPolicy}
898 * notification of a specific type, like {@link #TYPE_LIMIT}.
899 */
900 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700901 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902 }
903
904 /**
905 * Show notification for combined {@link NetworkPolicy} and specific type,
906 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
907 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700908 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700909 final String tag = buildNotificationTag(policy, type);
910 final Notification.Builder builder = new Notification.Builder(mContext);
911 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800912 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -0700913 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +0200914 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -0700915
916 final Resources res = mContext.getResources();
917 switch (type) {
918 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700919 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -0700920 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700921
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700922 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700923 builder.setTicker(title);
924 builder.setContentTitle(title);
925 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700926
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800927 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
928 builder.setDeleteIntent(PendingIntent.getBroadcast(
929 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
930
931 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700932 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800933 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
934
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935 break;
936 }
937 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700938 final CharSequence body = res.getText(R.string.data_usage_limit_body);
939
940 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -0400941 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700942 switch (policy.template.getMatchRule()) {
943 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700944 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700945 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700946 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700947 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 case MATCH_WIFI:
953 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -0400954 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700955 break;
956 default:
957 title = null;
958 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700959 }
960
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800961 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -0400962 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 builder.setTicker(title);
964 builder.setContentTitle(title);
965 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -0700966
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967 final Intent intent = buildNetworkOverLimitIntent(policy.template);
968 builder.setContentIntent(PendingIntent.getActivity(
969 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
970 break;
971 }
972 case TYPE_LIMIT_SNOOZED: {
973 final long overBytes = totalBytes - policy.limitBytes;
974 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
975 Formatter.formatFileSize(mContext, overBytes));
976
977 final CharSequence title;
978 switch (policy.template.getMatchRule()) {
979 case MATCH_MOBILE_3G_LOWER:
980 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
981 break;
982 case MATCH_MOBILE_4G:
983 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
984 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
987 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700988 case MATCH_WIFI:
989 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
990 break;
991 default:
992 title = null;
993 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 }
995
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800996 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700997 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 builder.setTicker(title);
999 builder.setContentTitle(title);
1000 builder.setContentText(body);
1001
1002 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001003 builder.setContentIntent(PendingIntent.getActivity(
1004 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005 break;
1006 }
1007 }
1008
1009 // TODO: move to NotificationManager once we can mock it
1010 try {
1011 final String packageName = mContext.getPackageName();
1012 final int[] idReceived = new int[1];
1013 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001014 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001015 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001016 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001018 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019 }
1020 }
1021
1022 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001023 * Show ongoing notification to reflect that {@link #mRestrictBackground}
1024 * has been enabled.
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025 */
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001026 private void enqueueRestrictedNotification(String tag) {
1027 final Resources res = mContext.getResources();
1028 final Notification.Builder builder = new Notification.Builder(mContext);
1029
1030 final CharSequence title = res.getText(R.string.data_usage_restricted_title);
1031 final CharSequence body = res.getString(R.string.data_usage_restricted_body);
1032
1033 builder.setOnlyAlertOnce(true);
1034 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001035 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001036 builder.setTicker(title);
1037 builder.setContentTitle(title);
1038 builder.setContentText(body);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001039 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001040 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001041
1042 final Intent intent = buildAllowBackgroundDataIntent();
1043 builder.setContentIntent(
1044 PendingIntent.getBroadcast(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045
1046 // TODO: move to NotificationManager once we can mock it
1047 try {
1048 final String packageName = mContext.getPackageName();
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001049 final int[] idReceived = new int[1];
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001050 mNotifManager.enqueueNotificationWithTag(packageName, packageName, tag,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001051 0x0, builder.getNotification(), idReceived, UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 mActiveNotifs.add(tag);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001053 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001054 // ignored; service lives in system_server
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001055 }
1056 }
1057
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001058 private void cancelNotification(String tag) {
1059 // TODO: move to NotificationManager once we can mock it
1060 try {
1061 final String packageName = mContext.getPackageName();
1062 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001063 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001065 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001066 }
1067 }
1068
1069 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001070 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001071 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001072 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001073 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001074 @Override
1075 public void onReceive(Context context, Intent intent) {
1076 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1077 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001078
1079 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001080 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001081 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001082 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001084 updateNetworkRulesLocked();
1085 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001086 }
1087 }
1088 };
1089
1090 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001091 * Proactively control network data connections when they exceed
1092 * {@link NetworkPolicy#limitBytes}.
1093 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001094 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001095 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1096
1097 // TODO: reset any policy-disabled networks when any policy is removed
1098 // completely, which is currently rare case.
1099
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001100 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001101 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1102 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001103 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001104 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 setNetworkTemplateEnabled(policy.template, true);
1106 continue;
1107 }
1108
1109 final long start = computeLastCycleBoundary(currentTime, policy);
1110 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001111 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001112
1113 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001114 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1115 && policy.lastLimitSnooze < start;
1116 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001117
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001118 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 }
1120 }
1121
1122 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001123 * Proactively disable networks that match the given
1124 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001125 */
1126 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001127 // TODO: reach into ConnectivityManager to proactively disable bringing
1128 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 }
1130
1131 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001132 * Examine all connected {@link NetworkState}, looking for
1133 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1134 * remaining quota based on usage cycle and historical stats.
1135 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001136 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001137 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138
1139 final NetworkState[] states;
1140 try {
1141 states = mConnManager.getAllNetworkState();
1142 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001143 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001144 return;
1145 }
1146
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001147 // If we are in restrict power mode, we want to treat all interfaces
1148 // as metered, to restrict access to the network by uid. However, we
1149 // will not have a bandwidth limit. Also only do this if restrict
Felipe Lemeb85a6372016-01-14 16:16:16 -08001150 // background data use is *not* enabled, since that takes precedence
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001151 // use over those networks can have a cost associated with it).
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07001152 final boolean powerSave = mRestrictPower && !mRestrictBackground;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001153
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001154 // First, generate identities of all connected networks so we can
1155 // quickly compare them against all defined policies below.
1156 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001157 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001158 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001159 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001160 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001161
1162 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001163 if (baseIface != null) {
1164 connIdents.add(Pair.create(baseIface, ident));
1165 if (powerSave) {
1166 connIfaces.add(baseIface);
1167 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001168 }
1169
1170 // Stacked interfaces are considered to have same identity as
1171 // their parent network.
1172 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1173 for (LinkProperties stackedLink : stackedLinks) {
1174 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001175 if (stackedIface != null) {
1176 connIdents.add(Pair.create(stackedIface, ident));
1177 if (powerSave) {
1178 connIfaces.add(stackedIface);
1179 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001180 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001181 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001182 }
1183 }
1184
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001185 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001186 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001188 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001189 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001190
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001192 for (int j = connIdents.size() - 1; j >= 0; j--) {
1193 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1194 if (policy.template.matches(ident.second)) {
1195 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001196 }
1197 }
1198
1199 if (ifaceList.size() > 0) {
1200 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001201 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001202 }
1203 }
1204
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001205 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001206 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001207
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001208 // apply each policy that we found ifaces for; compute remaining data
1209 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001210 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001211 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1212 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1213 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001215 final long start;
1216 final long totalBytes;
1217 if (policy.hasCycle()) {
1218 start = computeLastCycleBoundary(currentTime, policy);
1219 totalBytes = getTotalBytes(policy.template, start, currentTime);
1220 } else {
1221 start = Long.MAX_VALUE;
1222 totalBytes = 0;
1223 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001224
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001225 if (LOGD) {
1226 Slog.d(TAG, "applying policy " + policy.toString() + " to ifaces "
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001227 + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001228 }
1229
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001230 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001231 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001232 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001233 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001234 if (!hasLimit) {
1235 // metered network, but no policy limit; we still need to
1236 // restrict apps, so push really high quota.
1237 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001238 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 // snoozing past quota, but we still need to restrict apps,
1240 // so push really high quota.
1241 quotaBytes = Long.MAX_VALUE;
1242 } else {
1243 // remaining "quota" bytes are based on total usage in
1244 // current cycle. kernel doesn't like 0-byte rules, so we
1245 // set 1-byte quota and disable the radio later.
1246 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1247 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001248
1249 if (ifaces.length > 1) {
1250 // TODO: switch to shared quota once NMS supports
1251 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001252 }
1253
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001254 for (String iface : ifaces) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001255 removeInterfaceQuota(iface);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001256 setInterfaceQuota(iface, quotaBytes);
1257 newMeteredIfaces.add(iface);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001258 if (powerSave) {
1259 connIfaces.remove(iface);
1260 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001261 }
1262 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001263
1264 // keep track of lowest warning or limit of active policies
1265 if (hasWarning && policy.warningBytes < lowestRule) {
1266 lowestRule = policy.warningBytes;
1267 }
1268 if (hasLimit && policy.limitBytes < lowestRule) {
1269 lowestRule = policy.limitBytes;
1270 }
1271 }
1272
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001273 for (int i = connIfaces.size()-1; i >= 0; i--) {
1274 String iface = connIfaces.valueAt(i);
1275 removeInterfaceQuota(iface);
1276 setInterfaceQuota(iface, Long.MAX_VALUE);
1277 newMeteredIfaces.add(iface);
1278 }
1279
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001280 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001281
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001282 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001283 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1284 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001285 if (!newMeteredIfaces.contains(iface)) {
1286 removeInterfaceQuota(iface);
1287 }
1288 }
1289 mMeteredIfaces = newMeteredIfaces;
1290
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001291 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001292 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001293 }
1294
1295 /**
1296 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1297 * have at least a default mobile policy defined.
1298 */
1299 private void ensureActiveMobilePolicyLocked() {
1300 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001301 if (mSuppressDefaultPolicy) return;
1302
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001303 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001304 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001305
Jeff Sharkey32566012014-12-02 18:30:14 -08001306 final int[] subIds = sub.getActiveSubscriptionIdList();
1307 for (int subId : subIds) {
1308 final String subscriberId = tele.getSubscriberId(subId);
1309 ensureActiveMobilePolicyLocked(subscriberId);
1310 }
1311 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001312
Jeff Sharkey32566012014-12-02 18:30:14 -08001313 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1314 // Poke around to see if we already have a policy
1315 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1316 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false);
1317 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1318 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1319 if (template.matches(probeIdent)) {
1320 if (LOGD) {
1321 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1322 + NetworkIdentity.scrubSubscriberId(subscriberId));
1323 }
1324 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001325 }
1326 }
1327
Jeff Sharkey32566012014-12-02 18:30:14 -08001328 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1329 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001330
Jeff Sharkey32566012014-12-02 18:30:14 -08001331 // Build default mobile policy, and assume usage cycle starts today
1332 final long warningBytes = mContext.getResources().getInteger(
1333 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001334
Jeff Sharkey32566012014-12-02 18:30:14 -08001335 final Time time = new Time();
1336 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001337
Jeff Sharkey32566012014-12-02 18:30:14 -08001338 final int cycleDay = time.monthDay;
1339 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001340
Jeff Sharkey32566012014-12-02 18:30:14 -08001341 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1342 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1343 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1344 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 }
1346
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001347 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001348 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001349
1350 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001351 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001352 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353
1354 FileInputStream fis = null;
1355 try {
1356 fis = mPolicyFile.openRead();
1357 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001358 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001359
1360 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001361 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001362 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 while ((type = in.next()) != END_DOCUMENT) {
1364 final String tag = in.getName();
1365 if (type == START_TAG) {
1366 if (TAG_POLICY_LIST.equals(tag)) {
1367 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001368 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1369 mRestrictBackground = readBooleanAttribute(
1370 in, ATTR_RESTRICT_BACKGROUND);
1371 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001372 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001373 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001374
1375 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1376 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1377 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001378 final String networkId;
1379 if (version >= VERSION_ADDED_NETWORK_ID) {
1380 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1381 } else {
1382 networkId = null;
1383 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001384 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001385 final String cycleTimezone;
1386 if (version >= VERSION_ADDED_TIMEZONE) {
1387 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1388 } else {
1389 cycleTimezone = Time.TIMEZONE_UTC;
1390 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001391 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1392 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001393 final long lastLimitSnooze;
1394 if (version >= VERSION_SPLIT_SNOOZE) {
1395 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1396 } else if (version >= VERSION_ADDED_SNOOZE) {
1397 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001398 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001399 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001400 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001401 final boolean metered;
1402 if (version >= VERSION_ADDED_METERED) {
1403 metered = readBooleanAttribute(in, ATTR_METERED);
1404 } else {
1405 switch (networkTemplate) {
1406 case MATCH_MOBILE_3G_LOWER:
1407 case MATCH_MOBILE_4G:
1408 case MATCH_MOBILE_ALL:
1409 metered = true;
1410 break;
1411 default:
1412 metered = false;
1413 }
1414 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001415 final long lastWarningSnooze;
1416 if (version >= VERSION_SPLIT_SNOOZE) {
1417 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1418 } else {
1419 lastWarningSnooze = SNOOZE_NEVER;
1420 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001421 final boolean inferred;
1422 if (version >= VERSION_ADDED_INFERRED) {
1423 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1424 } else {
1425 inferred = false;
1426 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001427
Jeff Sharkey32566012014-12-02 18:30:14 -08001428 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1429 subscriberId, networkId);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001430 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001431 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey837f9242012-03-20 16:52:20 -07001432 lastLimitSnooze, metered, inferred));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001433
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001434 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001435 final int uid = readIntAttribute(in, ATTR_UID);
1436 final int policy = readIntAttribute(in, ATTR_POLICY);
1437
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001438 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001439 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001440 } else {
1441 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1442 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001443 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001444 final int appId = readIntAttribute(in, ATTR_APP_ID);
1445 final int policy = readIntAttribute(in, ATTR_POLICY);
1446
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001447 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001448 // app policy is deprecated so this is only used in pre system user split.
1449 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001450 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001451 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001452 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001453 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001454 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001455 } else if (TAG_WHITELIST.equals(tag)) {
1456 insideWhitelist = true;
1457 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1458 final int uid = readIntAttribute(in, ATTR_UID);
1459 mRestrictBackgroundWhitelistUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001460 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001461 } else if (type == END_TAG) {
1462 if (TAG_WHITELIST.equals(tag)) {
1463 insideWhitelist = false;
1464 }
1465
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466 }
1467 }
1468
1469 } catch (FileNotFoundException e) {
1470 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001471 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001472 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001473 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001474 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001475 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476 } finally {
1477 IoUtils.closeQuietly(fis);
1478 }
1479 }
1480
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001481 /**
1482 * Upgrade legacy background data flags, notifying listeners of one last
1483 * change to always-true.
1484 */
1485 private void upgradeLegacyBackgroundData() {
1486 mRestrictBackground = Settings.Secure.getInt(
1487 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1488
1489 // kick off one last broadcast if restricted
1490 if (mRestrictBackground) {
1491 final Intent broadcast = new Intent(
1492 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001493 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001494 }
1495 }
1496
Dianne Hackborn497175b2014-07-01 12:56:08 -07001497 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001498 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499
1500 FileOutputStream fos = null;
1501 try {
1502 fos = mPolicyFile.startWrite();
1503
1504 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001505 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506 out.startDocument(null, true);
1507
1508 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001509 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001510 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001511
1512 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001513 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1514 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001515 final NetworkTemplate template = policy.template;
1516
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001518 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1519 final String subscriberId = template.getSubscriberId();
1520 if (subscriberId != null) {
1521 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001523 final String networkId = template.getNetworkId();
1524 if (networkId != null) {
1525 out.attribute(null, ATTR_NETWORK_ID, networkId);
1526 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001527 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001528 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001529 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1530 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001531 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1532 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001533 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001534 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001535 out.endTag(null, TAG_NETWORK_POLICY);
1536 }
1537
1538 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001539 for (int i = 0; i < mUidPolicy.size(); i++) {
1540 final int uid = mUidPolicy.keyAt(i);
1541 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542
Jeff Sharkey497e4432011-06-14 17:27:29 -07001543 // skip writing empty policies
1544 if (policy == POLICY_NONE) continue;
1545
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001546 out.startTag(null, TAG_UID_POLICY);
1547 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001549 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001550 }
1551
1552 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001553
1554 // write all whitelists
1555 out.startTag(null, TAG_WHITELIST);
1556
1557 // restrict background whitelist
1558 final int size = mRestrictBackgroundWhitelistUids.size();
1559 for (int i = 0; i < size; i++) {
1560 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1561 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1562 writeIntAttribute(out, ATTR_UID, uid);
1563 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1564 }
1565
1566 out.endTag(null, TAG_WHITELIST);
1567
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001568 out.endDocument();
1569
1570 mPolicyFile.finishWrite(fos);
1571 } catch (IOException e) {
1572 if (fos != null) {
1573 mPolicyFile.failWrite(fos);
1574 }
1575 }
1576 }
1577
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001578 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001579 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001581
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001582 if (!UserHandle.isApp(uid)) {
1583 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001584 }
1585
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001586 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001587 final long token = Binder.clearCallingIdentity();
1588 try {
1589 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1590 if (oldPolicy != policy) {
1591 setUidPolicyUncheckedLocked(uid, policy, true);
1592 }
1593 } finally {
1594 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001595 }
1596 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001597 }
1598
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001599 @Override
1600 public void addUidPolicy(int uid, int policy) {
1601 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001602
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001603 if (!UserHandle.isApp(uid)) {
1604 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1605 }
1606
1607 synchronized (mRulesLock) {
1608 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1609 policy |= oldPolicy;
1610 if (oldPolicy != policy) {
1611 setUidPolicyUncheckedLocked(uid, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001612 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001614 }
1615
1616 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001617 public void removeUidPolicy(int uid, int policy) {
1618 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1619
1620 if (!UserHandle.isApp(uid)) {
1621 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1622 }
1623
1624 synchronized (mRulesLock) {
1625 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1626 policy = oldPolicy & ~policy;
1627 if (oldPolicy != policy) {
1628 setUidPolicyUncheckedLocked(uid, policy, true);
1629 }
1630 }
1631 }
1632
1633 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1634 mUidPolicy.put(uid, policy);
1635
1636 // uid policy changed, recompute rules and persist policy.
1637 updateRulesForUidLocked(uid);
1638 if (persist) {
1639 writePolicyLocked();
1640 }
1641 }
1642
1643 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001644 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1646
Jeff Sharkeya4620792011-05-20 15:29:23 -07001647 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001648 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001649 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001650 }
1651
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001652 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001654 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1655
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001656 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001657 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001658 for (int i = 0; i < mUidPolicy.size(); i++) {
1659 final int uid = mUidPolicy.keyAt(i);
1660 final int uidPolicy = mUidPolicy.valueAt(i);
1661 if (uidPolicy == policy) {
1662 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001663 }
1664 }
1665 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001666 return uids;
1667 }
1668
1669 /**
1670 * Remove any policies associated with given {@link UserHandle}, persisting
1671 * if any changes are made.
1672 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001673 void removePoliciesForUserLocked(int userId) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001674 if (LOGV) Slog.v(TAG, "removePoliciesForUserLocked()");
1675
1676 int[] uids = new int[0];
1677 for (int i = 0; i < mUidPolicy.size(); i++) {
1678 final int uid = mUidPolicy.keyAt(i);
1679 if (UserHandle.getUserId(uid) == userId) {
1680 uids = appendInt(uids, uid);
1681 }
1682 }
1683
1684 if (uids.length > 0) {
1685 for (int uid : uids) {
1686 mUidPolicy.delete(uid);
1687 updateRulesForUidLocked(uid);
1688 }
1689 writePolicyLocked();
1690 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001691 }
1692
1693 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001694 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001695 // TODO: create permission for observing network policy
1696 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1697
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001698 mListeners.register(listener);
1699
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001700 // TODO: consider dispatching existing rules to new listeners
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001701 }
1702
1703 @Override
1704 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001705 // TODO: create permission for observing network policy
1706 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1707
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001708 mListeners.unregister(listener);
1709 }
1710
Jeff Sharkey1b861272011-05-22 00:34:52 -07001711 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001712 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001713 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1714
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001715 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001717 normalizePoliciesLocked(policies);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001718 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001719 updateNetworkRulesLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001720 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001721 writePolicyLocked();
1722 }
1723 }
1724
Dianne Hackborn497175b2014-07-01 12:56:08 -07001725 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001726 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001727 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1728 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001729 }
1730
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001731 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001732 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001733 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001734 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001735 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1736 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1737 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001738 } catch (SecurityException e) {
1739 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001740
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001741 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1742 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1743 return new NetworkPolicy[0];
1744 }
Svet Ganov16a16892015-04-16 10:32:04 -07001745 }
1746
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001747 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001748 final int size = mNetworkPolicy.size();
1749 final NetworkPolicy[] policies = new NetworkPolicy[size];
1750 for (int i = 0; i < size; i++) {
1751 policies[i] = mNetworkPolicy.valueAt(i);
1752 }
1753 return policies;
1754 }
1755 }
1756
1757 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001758 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001759 }
1760
1761 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1762 final TelephonyManager tele = TelephonyManager.from(mContext);
1763 final String[] merged = tele.getMergedSubscriberIds();
1764
1765 mNetworkPolicy.clear();
1766 for (NetworkPolicy policy : policies) {
1767 // When two normalized templates conflict, prefer the most
1768 // restrictive policy
1769 policy.template = NetworkTemplate.normalize(policy.template, merged);
1770 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1771 if (existing == null || existing.compareTo(policy) > 0) {
1772 if (existing != null) {
1773 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1774 }
1775 mNetworkPolicy.put(policy.template, policy);
1776 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001777 }
1778 }
1779
1780 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001781 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001782 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001783
1784 final long token = Binder.clearCallingIdentity();
1785 try {
1786 performSnooze(template, TYPE_LIMIT);
1787 } finally {
1788 Binder.restoreCallingIdentity(token);
1789 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001790 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001791
Dianne Hackborn497175b2014-07-01 12:56:08 -07001792 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001793 maybeRefreshTrustedTime();
1794 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001795 synchronized (mRulesLock) {
1796 // find and snooze local policy that matches
1797 final NetworkPolicy policy = mNetworkPolicy.get(template);
1798 if (policy == null) {
1799 throw new IllegalArgumentException("unable to find policy for " + template);
1800 }
1801
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001802 switch (type) {
1803 case TYPE_WARNING:
1804 policy.lastWarningSnooze = currentTime;
1805 break;
1806 case TYPE_LIMIT:
1807 policy.lastLimitSnooze = currentTime;
1808 break;
1809 default:
1810 throw new IllegalArgumentException("unexpected type");
1811 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001812
Jeff Sharkey32566012014-12-02 18:30:14 -08001813 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001814 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001815 updateNetworkRulesLocked();
1816 updateNotificationsLocked();
1817 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001818 }
1819 }
1820
1821 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001822 public void setRestrictBackground(boolean restrictBackground) {
1823 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1824
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001825 maybeRefreshTrustedTime();
Jeff Sharkey46645002011-07-27 21:11:21 -07001826 synchronized (mRulesLock) {
1827 mRestrictBackground = restrictBackground;
Jeff Sharkey9d142062015-08-12 16:46:05 -07001828 updateRulesForGlobalChangeLocked(true);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001829 updateNotificationsLocked();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001830 writePolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -07001831 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001832
1833 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1834 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001835 }
1836
1837 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001838 public void addRestrictBackgroundWhitelistedUid(int uid) {
1839 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1840 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
1841 synchronized (mRulesLock) {
1842 mRestrictBackgroundWhitelistUids.append(uid, true);
1843 writePolicyLocked();
1844 // TODO: call other update methods like updateNetworkRulesLocked?
1845 }
Felipe Leme9778f762016-01-27 14:46:39 -08001846 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001847 }
1848
1849 @Override
1850 public void removeRestrictBackgroundWhitelistedUid(int uid) {
1851 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1852 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
1853 synchronized (mRulesLock) {
1854 removeRestrictBackgroundWhitelistedUidLocked(uid);
1855 }
Felipe Leme9778f762016-01-27 14:46:39 -08001856 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 0).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001857 }
1858
1859 private void removeRestrictBackgroundWhitelistedUidLocked(int uid) {
1860 mRestrictBackgroundWhitelistUids.delete(uid);
1861 writePolicyLocked();
1862 // TODO: call other update methods like updateNetworkRulesLocked?
1863 }
1864
1865 @Override
1866 public int[] getRestrictBackgroundWhitelistedUids() {
1867 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1868 synchronized (mRulesLock) {
1869 final int size = mRestrictBackgroundWhitelistUids.size();
1870 final int[] whitelist = new int[size];
1871 for (int i = 0; i < size; i++) {
1872 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
1873 }
1874 if (LOGV) {
1875 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
1876 + mRestrictBackgroundWhitelistUids);
1877 }
1878 return whitelist;
1879 }
1880 }
1881
1882 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08001883 public int getRestrictBackgroundByCaller() {
1884 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1885 final int uid = Binder.getCallingUid();
1886 synchronized (mRulesLock) {
1887 if (!mRestrictBackground) {
1888 return RESTRICT_BACKGROUND_STATUS_DISABLED;
1889 }
1890 return mRestrictBackgroundWhitelistUids.get(uid)
1891 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
1892 : RESTRICT_BACKGROUND_STATUS_ENABLED;
1893 }
1894 }
1895
1896 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001897 public boolean getRestrictBackground() {
1898 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1899
1900 synchronized (mRulesLock) {
1901 return mRestrictBackground;
1902 }
1903 }
1904
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001905 @Override
1906 public void setDeviceIdleMode(boolean enabled) {
1907 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1908
1909 synchronized (mRulesLock) {
1910 if (mDeviceIdleMode != enabled) {
1911 mDeviceIdleMode = enabled;
1912 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07001913 // Device idle change means we need to rebuild rules for all
1914 // known apps, so do a global refresh.
1915 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07001916 }
1917 if (enabled) {
1918 EventLogTags.writeDeviceIdleOnPhase("net");
1919 } else {
1920 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07001921 }
1922 }
1923 }
1924 }
1925
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001926 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001927 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1928 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001929 if (policy.template.matches(ident)) {
1930 return policy;
1931 }
1932 }
1933 return null;
1934 }
1935
1936 @Override
1937 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
1938 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
1939
1940 // only returns usage summary, so we don't require caller to have
1941 // READ_NETWORK_USAGE_HISTORY.
1942 final long token = Binder.clearCallingIdentity();
1943 try {
1944 return getNetworkQuotaInfoUnchecked(state);
1945 } finally {
1946 Binder.restoreCallingIdentity(token);
1947 }
1948 }
1949
1950 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
1951 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1952
1953 final NetworkPolicy policy;
1954 synchronized (mRulesLock) {
1955 policy = findPolicyForNetworkLocked(ident);
1956 }
1957
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001958 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001959 // missing policy means we can't derive useful quota info
1960 return null;
1961 }
1962
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001963 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001964
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001965 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001966 final long start = computeLastCycleBoundary(currentTime, policy);
1967 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001968 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001969
1970 // report soft and hard limits under policy
1971 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
1972 : NetworkQuotaInfo.NO_LIMIT;
1973 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
1974 : NetworkQuotaInfo.NO_LIMIT;
1975
1976 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
1977 }
1978
Jeff Sharkey46645002011-07-27 21:11:21 -07001979 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001980 public boolean isNetworkMetered(NetworkState state) {
1981 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
1982
Jeff Sharkeyf166f482012-04-30 15:59:21 -07001983 // roaming networks are always considered metered
1984 if (ident.getRoaming()) {
1985 return true;
1986 }
1987
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001988 final NetworkPolicy policy;
1989 synchronized (mRulesLock) {
1990 policy = findPolicyForNetworkLocked(ident);
1991 }
1992
1993 if (policy != null) {
1994 return policy.metered;
1995 } else {
Wei Liub8eaf452016-01-25 10:32:27 -08001996 if (state.networkInfo == null) {
1997 return false;
1998 }
1999
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002000 final int type = state.networkInfo.getType();
2001 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2002 return true;
2003 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002004 return false;
2005 }
2006 }
2007
2008 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002009 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002010 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002011
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002012 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2013
Dianne Hackborn497175b2014-07-01 12:56:08 -07002014 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002015 for (String arg : args) {
2016 argSet.add(arg);
2017 }
2018
Jeff Sharkey1b861272011-05-22 00:34:52 -07002019 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002020 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002021 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2022 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002023 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002024
Jeff Sharkey32566012014-12-02 18:30:14 -08002025 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002026 updateNetworkEnabledLocked();
2027 updateNetworkRulesLocked();
2028 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002029 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002030
2031 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002032 return;
2033 }
2034
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002035 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002036 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002037 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002038 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002039 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002040 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002041 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2042 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002043 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002044 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002045
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002046 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2047
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002048 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002049 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002050 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002051 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002052 final int uid = mUidPolicy.keyAt(i);
2053 final int policy = mUidPolicy.valueAt(i);
2054 fout.print("UID=");
2055 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002056 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002057 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002058 fout.println();
2059 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002060 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002061
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002062 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2063 if (size > 0) {
2064 fout.println("Power save whitelist (except idle) app ids:");
2065 fout.increaseIndent();
2066 for (int i = 0; i < size; i++) {
2067 fout.print("UID=");
2068 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2069 fout.print(": ");
2070 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2071 fout.println();
2072 }
2073 fout.decreaseIndent();
2074 }
2075
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002076 size = mPowerSaveWhitelistAppIds.size();
2077 if (size > 0) {
2078 fout.println("Power save whitelist app ids:");
2079 fout.increaseIndent();
2080 for (int i = 0; i < size; i++) {
2081 fout.print("UID=");
2082 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2083 fout.print(": ");
2084 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2085 fout.println();
2086 }
2087 fout.decreaseIndent();
2088 }
2089
Felipe Lemeb85a6372016-01-14 16:16:16 -08002090 size = mRestrictBackgroundWhitelistUids.size();
2091 if (size > 0) {
2092 fout.println("Restrict background whitelist uids:");
2093 fout.increaseIndent();
2094 for (int i = 0; i < size; i++) {
2095 fout.print("UID=");
2096 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2097 fout.println();
2098 }
2099 fout.decreaseIndent();
2100 }
2101
Jeff Sharkey1b861272011-05-22 00:34:52 -07002102 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002103 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002104 collectKeys(mUidRules, knownUids);
2105
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002106 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002107 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002108 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002109 for (int i = 0; i < size; i++) {
2110 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002111 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002112 fout.print(uid);
2113
Jeff Sharkeydc988062015-09-14 10:09:47 -07002114 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002115 fout.print(" state=");
2116 fout.print(state);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002117 fout.print(state <= ActivityManager.PROCESS_STATE_TOP ? " (fg)" : " (bg)");
Dianne Hackborn497175b2014-07-01 12:56:08 -07002118
Jeff Sharkeydc988062015-09-14 10:09:47 -07002119 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2120 fout.print(" rule=");
2121 fout.print(DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002122
2123 fout.println();
2124 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002125 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002126 }
2127 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002128
2129 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002130 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2131 String[] args, ResultReceiver resultReceiver) throws RemoteException {
2132 (new NetworkPolicyManagerShellCommand(this)).exec(
2133 this, in, out, err, args, resultReceiver);
2134 }
2135
2136 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002137 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002138 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2139
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002140 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002141 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002142 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002143 }
2144
Dianne Hackborn497175b2014-07-01 12:56:08 -07002145 boolean isUidForegroundLocked(int uid) {
2146 // only really in foreground when screen is also on
2147 return mScreenOn && mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY)
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002148 <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002149 }
2150
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002151 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002152 * Process state of UID changed; if needed, will trigger
2153 * {@link #updateRulesForUidLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002154 */
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002155 void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002156 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2157 if (oldUidState != uidState) {
2158 // state changed, push updated rules
2159 mUidState.put(uid, uidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002160 updateRulesForUidStateChangeLocked(uid, oldUidState, uidState);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002161 if (mDeviceIdleMode && isProcStateAllowedWhileIdle(oldUidState)
2162 != isProcStateAllowedWhileIdle(uidState)) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002163 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002164 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002165 }
2166 }
2167
2168 void removeUidStateLocked(int uid) {
2169 final int index = mUidState.indexOfKey(uid);
2170 if (index >= 0) {
2171 final int oldUidState = mUidState.valueAt(index);
2172 mUidState.removeAt(index);
2173 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
2174 updateRulesForUidStateChangeLocked(uid, oldUidState,
2175 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002176 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002177 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002178 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002179 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002180 }
2181 }
2182
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002183 void updateRulesForUidStateChangeLocked(int uid, int oldUidState, int newUidState) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002184 final boolean oldForeground = oldUidState <= ActivityManager.PROCESS_STATE_TOP;
2185 final boolean newForeground = newUidState <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002186 if (oldForeground != newForeground) {
2187 updateRulesForUidLocked(uid);
2188 }
2189 }
2190
Jeff Sharkeya4620792011-05-20 15:29:23 -07002191 private void updateScreenOn() {
2192 synchronized (mRulesLock) {
2193 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002194 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002195 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002196 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002197 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002198 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002199 }
2200 }
2201
2202 /**
2203 * Update rules that might be changed by {@link #mScreenOn} value.
2204 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002205 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002206 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002207 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002208 for (int i = 0; i < size; i++) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002209 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_TOP) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002210 final int uid = mUidState.keyAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002211 updateRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002212 }
2213 }
2214 }
2215
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002216 static boolean isProcStateAllowedWhileIdle(int procState) {
2217 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2218 }
2219
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002220 void updateRulesForDeviceIdleLocked() {
2221 if (mDeviceIdleMode) {
2222 // sync the whitelists before enable dozable chain. We don't care about the rules if
2223 // we are disabling the chain.
Jeff Sharkeydc988062015-09-14 10:09:47 -07002224 final SparseIntArray uidRules = mUidFirewallDozableRules;
2225 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002226 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002227 for (int ui = users.size() - 1; ui >= 0; ui--) {
2228 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002229 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002230 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2231 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2232 int uid = UserHandle.getUid(user.id, appId);
2233 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2234 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002235 }
2236 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2237 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2238 int uid = UserHandle.getUid(user.id, appId);
2239 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2240 }
2241 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002242 for (int i = mUidState.size() - 1; i >= 0; i--) {
2243 if (isProcStateAllowedWhileIdle(mUidState.valueAt(i))) {
2244 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2245 }
2246 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002247 setUidFirewallRules(FIREWALL_CHAIN_DOZABLE, uidRules);
2248 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002249
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002250 enableFirewallChainLocked(FIREWALL_CHAIN_DOZABLE, mDeviceIdleMode);
2251 }
2252
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002253 void updateRuleForDeviceIdleLocked(int uid) {
2254 if (mDeviceIdleMode) {
2255 int appId = UserHandle.getAppId(uid);
2256 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
2257 || isProcStateAllowedWhileIdle(mUidState.get(uid))) {
2258 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_ALLOW);
2259 } else {
2260 setUidFirewallRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
2261 }
2262 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002263
2264 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002265 }
2266
2267 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002268 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2269 uidRules.clear();
2270
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002271 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002272 final List<UserInfo> users = mUserManager.getUsers();
2273 for (int ui = users.size() - 1; ui >= 0; ui--) {
2274 UserInfo user = users.get(ui);
2275 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2276 for (int uid : idleUids) {
2277 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2278 uidRules.put(uid, FIREWALL_RULE_DENY);
2279 }
2280 }
2281 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002282
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002283 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2284 }
2285
2286 void updateRuleForAppIdleLocked(int uid) {
2287 if (!isUidValidForRules(uid)) return;
2288
2289 int appId = UserHandle.getAppId(uid);
2290 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2291 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2292 } else {
2293 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2294 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002295
2296 updateRulesForUidLocked(uid);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002297 }
2298
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002299 void updateRulesForAppIdleParoleLocked() {
2300 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2301 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Jeff Sharkeydc988062015-09-14 10:09:47 -07002302 updateRulesForUidsLocked(mUidFirewallStandbyRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002303 }
2304
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002305 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002306 * Update rules that might be changed by {@link #mRestrictBackground},
2307 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002308 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002309 void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002310 final PackageManager pm = mContext.getPackageManager();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002312 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002313 updateRulesForAppIdleLocked();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002314
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002315 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002316 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey2a9e3f82015-12-18 10:57:58 -07002318 PackageManager.GET_UNINSTALLED_PACKAGES | PackageManager.GET_DISABLED_COMPONENTS
2319 | PackageManager.MATCH_ENCRYPTION_AWARE_AND_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002320
2321 for (UserInfo user : users) {
2322 for (ApplicationInfo app : apps) {
2323 final int uid = UserHandle.getUid(user.id, app.uid);
2324 updateRulesForUidLocked(uid);
2325 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002326 }
2327
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002328 // limit data usage for some internal system services
2329 updateRulesForUidLocked(android.os.Process.MEDIA_UID);
2330 updateRulesForUidLocked(android.os.Process.DRM_UID);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002331
2332 // If the set of restricted networks may have changed, re-evaluate those.
2333 if (restrictedNetworksChanged) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002334 normalizePoliciesLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002335 updateNetworkRulesLocked();
2336 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002337 }
2338
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002339 void updateRulesForTempWhitelistChangeLocked() {
2340 final List<UserInfo> users = mUserManager.getUsers();
2341 for (UserInfo user : users) {
2342 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
2343 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2344 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002345 updateRuleForAppIdleLocked(uid);
2346 updateRuleForDeviceIdleLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002347 }
2348 }
2349 }
2350
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002351 private static boolean isUidValidForRules(int uid) {
2352 // allow rules on specific system services, and any apps
2353 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Dianne Hackbornf02b60a2012-08-16 10:48:27 -07002354 || UserHandle.isApp(uid)) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002355 return true;
2356 }
2357
2358 return false;
2359 }
2360
Amith Yamasani15e472352015-04-24 19:06:07 -07002361 private boolean isUidIdle(int uid) {
2362 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2363 final int userId = UserHandle.getUserId(uid);
2364
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002365 if (!ArrayUtils.isEmpty(packages)) {
2366 for (String packageName : packages) {
2367 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2368 return false;
2369 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002370 }
2371 }
2372 return true;
2373 }
2374
Jeff Sharkeydc988062015-09-14 10:09:47 -07002375 void updateRulesForUidsLocked(SparseIntArray uids) {
2376 for (int i = 0; i < uids.size(); i++) {
2377 updateRulesForUidLocked(uids.keyAt(i));
2378 }
2379 }
2380
Amith Yamasani15e472352015-04-24 19:06:07 -07002381 /**
2382 * Applies network rules to bandwidth and firewall controllers based on uid policy.
2383 * @param uid The uid for which to apply the latest policy
2384 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002385 void updateRulesForUidLocked(int uid) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002386 if (!isUidValidForRules(uid)) return;
2387
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002388 // quick check: if this uid doesn't have INTERNET permission, it doesn't have
2389 // network access anyway, so it is a waste to mess with it here.
2390 final IPackageManager ipm = AppGlobals.getPackageManager();
2391 try {
2392 if (ipm.checkUidPermission(Manifest.permission.INTERNET, uid)
2393 != PackageManager.PERMISSION_GRANTED) {
2394 return;
2395 }
2396 } catch (RemoteException e) {
2397 }
2398
Dianne Hackborn497175b2014-07-01 12:56:08 -07002399 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2400 final boolean uidForeground = isUidForegroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002401
Jeff Sharkeydc988062015-09-14 10:09:47 -07002402 // Derive active rules based on policy and active state
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002403 int appId = UserHandle.getAppId(uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002404 int uidRules = RULE_ALLOW_ALL;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002405 if (!uidForeground && (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07002406 // uid in background, and policy says to block metered data
2407 uidRules = RULE_REJECT_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002408 } else if (mRestrictBackground) {
2409 if (!uidForeground) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002410 // uid in background, global background disabled, and this uid is not on the white
2411 // list of those allowed background access while global background is disabled
2412 if (!mRestrictBackgroundWhitelistUids.get(uid)) {
2413 uidRules = RULE_REJECT_METERED;
2414 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002415 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002416 } else if (mRestrictPower) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002417 final boolean whitelisted = mPowerSaveWhitelistExceptIdleAppIds.get(appId)
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002418 || mPowerSaveTempWhitelistAppIds.get(appId);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002419 if (!whitelisted && !uidForeground
2420 && (uidPolicy & POLICY_ALLOW_BACKGROUND_BATTERY_SAVE) == 0) {
2421 // uid is in background, restrict power use mode is on (so we want to
2422 // restrict all background network access), and this uid is not on the
2423 // white list of those allowed background access.
2424 uidRules = RULE_REJECT_METERED;
2425 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002426 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002427
Jeff Sharkeydc988062015-09-14 10:09:47 -07002428 // Check dozable state, which is whitelist
2429 if (mFirewallChainStates.get(FIREWALL_CHAIN_DOZABLE)
2430 && mUidFirewallDozableRules.get(uid, FIREWALL_RULE_DEFAULT) != FIREWALL_RULE_ALLOW) {
2431 uidRules = RULE_REJECT_ALL;
2432 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002433
Jeff Sharkeydc988062015-09-14 10:09:47 -07002434 // Check standby state, which is blacklist
2435 if (mFirewallChainStates.get(FIREWALL_CHAIN_STANDBY)
2436 && mUidFirewallStandbyRules.get(uid, FIREWALL_RULE_DEFAULT) == FIREWALL_RULE_DENY) {
2437 uidRules = RULE_REJECT_ALL;
2438 }
2439
2440 final int oldRules = mUidRules.get(uid);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002441 if (uidRules == RULE_ALLOW_ALL) {
2442 mUidRules.delete(uid);
2443 } else {
2444 mUidRules.put(uid, uidRules);
2445 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002446
Jeff Sharkeydc988062015-09-14 10:09:47 -07002447 final boolean rejectMetered = (uidRules == RULE_REJECT_METERED);
2448 setUidNetworkRules(uid, rejectMetered);
Amith Yamasani15e472352015-04-24 19:06:07 -07002449
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002450 // dispatch changed rule to existing listeners
Amith Yamasani15e472352015-04-24 19:06:07 -07002451 if (oldRules != uidRules) {
2452 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, uidRules).sendToTarget();
2453 }
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002454
2455 try {
2456 // adjust stats accounting based on foreground status
2457 mNetworkStats.setUidForeground(uid, uidForeground);
2458 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002459 // ignored; service lives in system_server
Jeff Sharkeyb5d55e32011-08-10 17:53:27 -07002460 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002461 }
2462
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002463 private class AppIdleStateChangeListener
2464 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2465
2466 @Override
2467 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2468 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002469 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2470 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002471 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002472 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002473 }
2474 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002475 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002476 }
2477
2478 @Override
2479 public void onParoleStateChanged(boolean isParoleOn) {
2480 synchronized (mRulesLock) {
2481 updateRulesForAppIdleParoleLocked();
2482 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002483 }
2484 }
2485
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002486 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002487 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002488 public boolean handleMessage(Message msg) {
2489 switch (msg.what) {
2490 case MSG_RULES_CHANGED: {
2491 final int uid = msg.arg1;
2492 final int uidRules = msg.arg2;
2493 final int length = mListeners.beginBroadcast();
2494 for (int i = 0; i < length; i++) {
2495 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2496 if (listener != null) {
2497 try {
2498 listener.onUidRulesChanged(uid, uidRules);
2499 } catch (RemoteException e) {
2500 }
2501 }
2502 }
2503 mListeners.finishBroadcast();
2504 return true;
2505 }
2506 case MSG_METERED_IFACES_CHANGED: {
2507 final String[] meteredIfaces = (String[]) msg.obj;
2508 final int length = mListeners.beginBroadcast();
2509 for (int i = 0; i < length; i++) {
2510 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2511 if (listener != null) {
2512 try {
2513 listener.onMeteredIfacesChanged(meteredIfaces);
2514 } catch (RemoteException e) {
2515 }
2516 }
2517 }
2518 mListeners.finishBroadcast();
2519 return true;
2520 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002521 case MSG_LIMIT_REACHED: {
2522 final String iface = (String) msg.obj;
2523
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002524 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002525 synchronized (mRulesLock) {
2526 if (mMeteredIfaces.contains(iface)) {
2527 try {
2528 // force stats update to make sure we have
2529 // numbers that caused alert to trigger.
2530 mNetworkStats.forceUpdate();
2531 } catch (RemoteException e) {
2532 // ignored; service lives in system_server
2533 }
2534
2535 updateNetworkEnabledLocked();
2536 updateNotificationsLocked();
2537 }
2538 }
2539 return true;
2540 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002541 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2542 final boolean restrictBackground = msg.arg1 != 0;
2543 final int length = mListeners.beginBroadcast();
2544 for (int i = 0; i < length; i++) {
2545 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
2546 if (listener != null) {
2547 try {
2548 listener.onRestrictBackgroundChanged(restrictBackground);
2549 } catch (RemoteException e) {
2550 }
2551 }
2552 }
2553 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002554 final Intent intent =
2555 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2556 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2557 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2558 return true;
2559 }
2560 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
2561 final int uid = msg.arg1;
2562 final PackageManager pm = mContext.getPackageManager();
2563 final String[] packages = pm.getPackagesForUid(uid);
2564 final int userId = UserHandle.getUserId(uid);
2565 for (String packageName : packages) {
2566 final Intent intent =
2567 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2568 intent.setPackage(packageName);
2569 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2570 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
2571 }
2572
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07002573 return true;
2574 }
2575 case MSG_ADVISE_PERSIST_THRESHOLD: {
2576 final long lowestRule = (Long) msg.obj;
2577 try {
2578 // make sure stats are recorded frequently enough; we aim
2579 // for 2MB threshold for 2GB/month rules.
2580 final long persistThreshold = lowestRule / 1000;
2581 mNetworkStats.advisePersistThreshold(persistThreshold);
2582 } catch (RemoteException e) {
2583 // ignored; service lives in system_server
2584 }
2585 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002586 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07002587 case MSG_SCREEN_ON_CHANGED: {
2588 updateScreenOn();
2589 return true;
2590 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002591 default: {
2592 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07002593 }
2594 }
2595 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002596 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002597
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002598 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002599 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002600 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002601 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002602 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002603 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002604 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002605 }
2606 }
2607
2608 private void removeInterfaceQuota(String iface) {
2609 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002610 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002611 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002612 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002613 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002614 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002615 }
2616 }
2617
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002618 private void setUidNetworkRules(int uid, boolean rejectOnQuotaInterfaces) {
2619 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002620 mNetworkManager.setUidNetworkRules(uid, rejectOnQuotaInterfaces);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002621 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002622 Log.wtf(TAG, "problem setting uid rules", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002623 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002624 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002625 }
2626 }
2627
Amith Yamasani15e472352015-04-24 19:06:07 -07002628 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002629 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
2630 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
2631 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07002632 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002633 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002634 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002635 int size = uidRules.size();
2636 int[] uids = new int[size];
2637 int[] rules = new int[size];
2638 for(int index = size - 1; index >= 0; --index) {
2639 uids[index] = uidRules.keyAt(index);
2640 rules[index] = uidRules.valueAt(index);
2641 }
2642 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07002643 } catch (IllegalStateException e) {
2644 Log.wtf(TAG, "problem setting firewall uid rules", e);
2645 } catch (RemoteException e) {
2646 // ignored; service lives in system_server
2647 }
2648 }
2649
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002650 /**
2651 * Add or remove a uid to the firewall blacklist for all network ifaces.
2652 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002653 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002654 if (chain == FIREWALL_CHAIN_DOZABLE) {
2655 mUidFirewallDozableRules.put(uid, rule);
2656 } else if (chain == FIREWALL_CHAIN_STANDBY) {
2657 mUidFirewallStandbyRules.put(uid, rule);
2658 }
2659
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002660 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002661 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002662 } catch (IllegalStateException e) {
2663 Log.wtf(TAG, "problem setting firewall uid rules", e);
2664 } catch (RemoteException e) {
2665 // ignored; service lives in system_server
2666 }
2667 }
2668
2669 /**
2670 * Add or remove a uid to the firewall blacklist for all network ifaces.
2671 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002672 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002673 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
2674 mFirewallChainStates.get(chain) == enable) {
2675 // All is the same, nothing to do.
2676 return;
2677 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002678 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002679 try {
2680 mNetworkManager.setFirewallChainEnabled(chain, enable);
2681 } catch (IllegalStateException e) {
2682 Log.wtf(TAG, "problem enable firewall chain", e);
2683 } catch (RemoteException e) {
2684 // ignored; service lives in system_server
2685 }
2686 }
2687
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002688 private long getTotalBytes(NetworkTemplate template, long start, long end) {
2689 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07002690 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08002691 } catch (RuntimeException e) {
2692 Slog.w(TAG, "problem reading network stats: " + e);
2693 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002694 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002695 // ignored; service lives in system_server
2696 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002697 }
2698 }
2699
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07002700 private boolean isBandwidthControlEnabled() {
2701 final long token = Binder.clearCallingIdentity();
2702 try {
2703 return mNetworkManager.isBandwidthControlEnabled();
2704 } catch (RemoteException e) {
2705 // ignored; service lives in system_server
2706 return false;
2707 } finally {
2708 Binder.restoreCallingIdentity(token);
2709 }
2710 }
2711
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002712 /**
2713 * Try refreshing {@link #mTime} when stale.
2714 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07002715 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002716 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002717 mTime.forceRefresh();
2718 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002719 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002720
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002721 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002722 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
2723 }
2724
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002725 private static Intent buildAllowBackgroundDataIntent() {
2726 return new Intent(ACTION_ALLOW_BACKGROUND);
2727 }
2728
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002729 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
2730 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
2731 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2732 return intent;
2733 }
2734
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002735 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
2736 final Intent intent = new Intent();
2737 intent.setComponent(new ComponentName(
2738 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
2739 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2740 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2741 return intent;
2742 }
2743
2744 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
2745 final Intent intent = new Intent();
2746 intent.setComponent(new ComponentName(
2747 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
2748 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2749 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
2750 return intent;
2751 }
2752
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08002753 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07002754 public void addIdleHandler(IdleHandler handler) {
2755 mHandler.getLooper().getQueue().addIdleHandler(handler);
2756 }
2757
Jeff Sharkey1b861272011-05-22 00:34:52 -07002758 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
2759 final int size = source.size();
2760 for (int i = 0; i < size; i++) {
2761 target.put(source.keyAt(i), true);
2762 }
2763 }
2764
Stuart Scottf1fb3972015-04-02 18:00:02 -07002765 @Override
2766 public void factoryReset(String subscriber) {
2767 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
2768
Stuart Scotte3e314d2015-04-20 14:07:45 -07002769 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
2770 return;
2771 }
2772
Stuart Scottf1fb3972015-04-02 18:00:02 -07002773 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07002774 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07002775 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
2776 for (NetworkPolicy policy : policies) {
2777 if (policy.template.equals(template)) {
2778 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
2779 policy.inferred = false;
2780 policy.clearSnooze();
2781 }
2782 }
2783 setNetworkPolicies(policies);
2784
2785 // Turn restrict background data off
2786 setRestrictBackground(false);
2787
Stuart Scotte3e314d2015-04-20 14:07:45 -07002788 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
2789 // Remove app's "restrict background data" flag
2790 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
2791 setUidPolicy(uid, POLICY_NONE);
2792 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07002793 }
2794 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002795
2796 private class MyPackageMonitor extends PackageMonitor {
2797
2798 @Override
2799 public void onPackageRemoved(String packageName, int uid) {
2800 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
2801 synchronized (mRulesLock) {
2802 removeRestrictBackgroundWhitelistedUidLocked(uid);
2803 }
2804 }
2805
2806 @Override
2807 public void onPackageRemovedAllUsers(String packageName, int uid) {
2808 if (LOGV) Slog.v(TAG, "onPackageRemovedAllUsers: " + packageName + " ->" + uid);
2809 synchronized (mRulesLock) {
2810 removeRestrictBackgroundWhitelistedUidLocked(uid);
2811 }
2812 }
2813 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002814}