blob: 7ed75ca2cd6c2670c554c24f37f60450284c876d [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme70c57c22016-03-29 10:45:13 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070052import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_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;
Felipe Leme03e689d2016-03-02 16:17:38 -080070
Jeff Sharkey854b2b12012-04-13 16:03:40 -070071import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070073import static com.android.internal.util.XmlUtils.readBooleanAttribute;
74import static com.android.internal.util.XmlUtils.readIntAttribute;
75import static com.android.internal.util.XmlUtils.readLongAttribute;
76import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
77import static com.android.internal.util.XmlUtils.writeIntAttribute;
78import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070079import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060081
Jeff Sharkey21c9c452011-06-07 12:26:43 -070082import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080083import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070085
Dianne Hackborn88e98df2015-03-23 13:29:14 -070086import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070087import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070088import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070089import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070090import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070092import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070093import android.app.Notification;
94import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070095import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070097import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070098import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070099import android.content.Intent;
100import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700101import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700102import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700103import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700104import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700105import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700106import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700107import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700109import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700110import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700111import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700112import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700114import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700115import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700116import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700117import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700118import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.wifi.WifiConfiguration;
122import android.net.wifi.WifiInfo;
123import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.os.Environment;
126import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700127import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700128import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700129import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700130import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700131import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700132import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700134import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600137import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700139import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700140import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700141import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800142import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700143import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700144import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700145import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700146import android.util.ArrayMap;
147import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700148import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700149import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700150import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700152import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700153import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700154import android.util.SparseBooleanArray;
155import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.util.TrustedTime;
157import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700158
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;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800168import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600169
170import libcore.io.IoUtils;
171
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173
174import org.xmlpull.v1.XmlPullParser;
175import org.xmlpull.v1.XmlPullParserException;
176import org.xmlpull.v1.XmlSerializer;
177
178import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700179import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700184import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100185import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import java.util.ArrayList;
187import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700188import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700191 * Service that maintains low-level network policy rules, using
192 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700193 * <p>
194 * Derives active rules by combining a given policy with other system status,
195 * and delivers to listeners, such as {@link ConnectivityManager}, for
196 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700197 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700198public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800199 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700200 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700201 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700202
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700203 private static final int VERSION_INIT = 1;
204 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700205 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800206 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800207 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800208 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700209 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700210 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700211 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700212 private static final int VERSION_SWITCH_UID = 10;
213 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800215 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700218 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800219 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700220 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700221
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String TAG_POLICY_LIST = "policy-list";
223 private static final String TAG_NETWORK_POLICY = "network-policy";
224 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700225 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800226 private static final String TAG_WHITELIST = "whitelist";
227 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800228 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229
230 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700231 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
233 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700234 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800236 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237 private static final String ATTR_WARNING_BYTES = "warningBytes";
238 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700239 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800240 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
241 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800242 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700243 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700245 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246 private static final String ATTR_POLICY = "policy";
247
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800249 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800250 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800251 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700252
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
254
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700255 private static final int MSG_RULES_CHANGED = 1;
256 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800257 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800258 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700259 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700260 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800261 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700262 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
263 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700264
Jeff Sharkey75279902011-05-24 18:39:45 -0700265 private final Context mContext;
266 private final IActivityManager mActivityManager;
267 private final IPowerManager mPowerManager;
268 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700269 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700272 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700273
274 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700275 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700276 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700277 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700278
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700280
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700281 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700282 volatile boolean mScreenOn;
283 volatile boolean mRestrictBackground;
284 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700285 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700286
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700287 private final boolean mSuppressDefaultPolicy;
288
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700289 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700291 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700293
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700294 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700295 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700296 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800297 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700298
Jeff Sharkeydc988062015-09-14 10:09:47 -0700299 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
300 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800301 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700302
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700303 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700304 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
305
Jeff Sharkey32566012014-12-02 18:30:14 -0800306 /**
307 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700308 * in power save mode, except device idle (doze) still applies.
309 * TODO: An int array might be sufficient
310 */
311 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
312
313 /**
314 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800315 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700316 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800317 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700318 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700319
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700320 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
321
Felipe Lemeb85a6372016-01-14 16:16:16 -0800322 /**
323 * UIDs that have been white-listed to avoid restricted background.
324 */
325 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
326
Felipe Lemea9505cc2016-02-26 10:28:41 -0800327 /**
328 * UIDs that have been initially white-listed by system to avoid restricted background.
329 */
330 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
331 new SparseBooleanArray();
332
333 /**
334 * UIDs that have been initially white-listed by system to avoid restricted background,
335 * but later revoked by user.
336 */
337 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
338 new SparseBooleanArray();
339
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700340 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800341 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700342 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800343 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700344
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700345 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700346 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700347
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700348 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700350
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600351 /** Higher priority listener before general event dispatch */
352 private INetworkPolicyListener mConnectivityListener;
353
Jeff Sharkey32566012014-12-02 18:30:14 -0800354 private final RemoteCallbackList<INetworkPolicyListener>
355 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700356
Dianne Hackborn497175b2014-07-01 12:56:08 -0700357 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358
359 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700360
Svet Ganov16a16892015-04-16 10:32:04 -0700361 private final AppOpsManager mAppOps;
362
Felipe Lemeb85a6372016-01-14 16:16:16 -0800363 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800364 private final IPackageManager mIPm;
365
Felipe Lemeb85a6372016-01-14 16:16:16 -0800366
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700367 // TODO: keep whitelist of system-critical services that should never have
368 // rules enforced, such as system, phone, and radio UIDs.
369
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700370 // TODO: migrate notifications to SystemUI
371
Jeff Sharkey75279902011-05-24 18:39:45 -0700372 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700373 IPowerManager powerManager, INetworkStatsService networkStats,
374 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700375 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700376 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700377 }
378
379 private static File getSystemDir() {
380 return new File(Environment.getDataDirectory(), "system");
381 }
382
383 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700384 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700385 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
386 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700387 mContext = checkNotNull(context, "missing context");
388 mActivityManager = checkNotNull(activityManager, "missing activityManager");
389 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700390 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700391 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700392 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700393 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700394 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700395 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800396 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397
Amith Yamasani450a16b2013-09-18 16:28:50 -0700398 HandlerThread thread = new HandlerThread(TAG);
399 thread.start();
400 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700402 mSuppressDefaultPolicy = suppressDefaultPolicy;
403
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700405
406 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800407
408 mPackageMonitor = new MyPackageMonitor();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700409 }
410
411 public void bindConnectivityManager(IConnectivityManager connManager) {
412 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700413 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700414
Jeff Sharkey497e4432011-06-14 17:27:29 -0700415 public void bindNotificationManager(INotificationManager notifManager) {
416 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
417 }
418
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700419 void updatePowerSaveWhitelistLocked() {
420 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700421 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
422 mPowerSaveWhitelistExceptIdleAppIds.clear();
423 if (whitelist != null) {
424 for (int uid : whitelist) {
425 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
426 }
427 }
428 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700429 mPowerSaveWhitelistAppIds.clear();
430 if (whitelist != null) {
431 for (int uid : whitelist) {
432 mPowerSaveWhitelistAppIds.put(uid, true);
433 }
434 }
435 } catch (RemoteException e) {
436 }
437 }
438
Felipe Lemea9505cc2016-02-26 10:28:41 -0800439 /**
440 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
441 * revoke the whitelist.
442 *
443 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
444 */
Felipe Lemea110eec2016-04-29 09:58:06 -0700445 boolean addDefaultRestrictBackgroundWhitelistUidsLocked() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800446 final List<UserInfo> users = mUserManager.getUsers();
447 final int numberUsers = users.size();
448
Felipe Lemea110eec2016-04-29 09:58:06 -0700449 boolean changed = false;
450 for (int i = 0; i < numberUsers; i++) {
451 final UserInfo user = users.get(i);
452 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(user.id) || changed;
453 }
454 return changed;
455 }
456
457 private boolean addDefaultRestrictBackgroundWhitelistUidsLocked(int userId) {
458 final SystemConfig sysConfig = SystemConfig.getInstance();
459 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800460 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
461 boolean changed = false;
462 for (int i = 0; i < allowDataUsage.size(); i++) {
463 final String pkg = allowDataUsage.valueAt(i);
464 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700465 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
466 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800467 final ApplicationInfo app;
468 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700469 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800470 } catch (PackageManager.NameNotFoundException e) {
471 // Should not happen
472 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
473 continue;
474 }
475 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700476 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800477 continue;
478 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700479 final int uid = UserHandle.getUid(userId, app.uid);
480 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
481 if (LOGD)
482 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
483 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800484 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700485 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
486 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
487 + userId + ") to restrict background whitelist");
488 mRestrictBackgroundWhitelistUids.append(uid, true);
489 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800490 }
491 }
492 return changed;
493 }
494
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700495 void updatePowerSaveTempWhitelistLocked() {
496 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700497 // Clear the states of the current whitelist
498 final int N = mPowerSaveTempWhitelistAppIds.size();
499 for (int i = 0; i < N; i++) {
500 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
501 }
502 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700503 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700504 if (whitelist != null) {
505 for (int uid : whitelist) {
506 mPowerSaveTempWhitelistAppIds.put(uid, true);
507 }
508 }
509 } catch (RemoteException e) {
510 }
511 }
512
Amith Yamasani06f08062015-06-12 13:23:33 -0700513 /**
514 * Remove unnecessary entries in the temp whitelist
515 */
516 void purgePowerSaveTempWhitelistLocked() {
517 final int N = mPowerSaveTempWhitelistAppIds.size();
518 for (int i = N - 1; i >= 0; i--) {
519 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
520 mPowerSaveTempWhitelistAppIds.removeAt(i);
521 }
522 }
523 }
524
Jeff Sharkeya4620792011-05-20 15:29:23 -0700525 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700526 if (!isBandwidthControlEnabled()) {
527 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
528 return;
529 }
530
Amith Yamasani15e472352015-04-24 19:06:07 -0700531 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
532
Felipe Lemeb85a6372016-01-14 16:16:16 -0800533 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
534
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700535 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700536 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700537 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
538 mPowerManagerInternal.registerLowPowerModeObserver(
539 new PowerManagerInternal.LowPowerModeListener() {
540 @Override
541 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800542 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700543 synchronized (mRulesLock) {
544 if (mRestrictPower != enabled) {
545 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800546 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700547 updateRulesForGlobalChangeLocked(true);
548 }
549 }
550 }
551 });
552 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700553 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700554
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700555 // read policy from disk
556 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700557
Felipe Lemea110eec2016-04-29 09:58:06 -0700558 if (addDefaultRestrictBackgroundWhitelistUidsLocked()) {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 writePolicyLocked();
560 }
561
Jeff Sharkeydc988062015-09-14 10:09:47 -0700562 updateRulesForGlobalChangeLocked(false);
563 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700564 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700565
Jeff Sharkeya4620792011-05-20 15:29:23 -0700566 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700567
Jeff Sharkeya4620792011-05-20 15:29:23 -0700568 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700569 mActivityManager.registerUidObserver(mUidObserver,
570 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700571 mNetworkManager.registerObserver(mAlertObserver);
572 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700573 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700574 }
575
Jeff Sharkeya4620792011-05-20 15:29:23 -0700576 // TODO: traverse existing processes to know foreground state, or have
577 // activitymanager dispatch current state when new observer attached.
578
579 final IntentFilter screenFilter = new IntentFilter();
580 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
581 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700582 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700583
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700584 // listen for changes to power save whitelist
585 final IntentFilter whitelistFilter = new IntentFilter(
586 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
587 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
588
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700589 DeviceIdleController.LocalService deviceIdleService
590 = LocalServices.getService(DeviceIdleController.LocalService.class);
591 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
592
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700593 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900594 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700595 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
596
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700597 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700598 final IntentFilter packageFilter = new IntentFilter();
599 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700600 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700601 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700602
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700603 // listen for UID changes to update policy
604 mContext.registerReceiver(
605 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
606
607 // listen for user changes to update policy
608 final IntentFilter userFilter = new IntentFilter();
609 userFilter.addAction(ACTION_USER_ADDED);
610 userFilter.addAction(ACTION_USER_REMOVED);
611 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
612
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700613 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700614 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
615 mContext.registerReceiver(
616 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
617
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700618 // listen for restrict background changes from notifications
619 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
620 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
621
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800622 // listen for snooze warning from notifications
623 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
624 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
625 MANAGE_NETWORK_POLICY, mHandler);
626
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700627 // listen for configured wifi networks to be removed
628 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700629 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700630
631 // listen for wifi state changes to catch metered hint
632 final IntentFilter wifiStateFilter = new IntentFilter(
633 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700634 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700635
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700636 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700637
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700638 }
639
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700640 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700641 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700642 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700643 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700644 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700645 }
646
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700647 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700648 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700649 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700650 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700651 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700652
653 @Override public void onUidActive(int uid) throws RemoteException {
654 }
655
656 @Override public void onUidIdle(int uid) throws RemoteException {
657 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700658 };
659
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700660 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700661 @Override
662 public void onReceive(Context context, Intent intent) {
663 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
664 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700665 updatePowerSaveWhitelistLocked();
666 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700667 }
668 }
669 };
670
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700671 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
672 @Override
673 public void run() {
674 synchronized (mRulesLock) {
675 updatePowerSaveTempWhitelistLocked();
676 updateRulesForTempWhitelistChangeLocked();
677 purgePowerSaveTempWhitelistLocked();
678 }
679 }
680 };
681
682 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700683 @Override
684 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800685 // screen-related broadcasts are protected by system, no need
686 // for permissions check.
687 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700688 }
689 };
690
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700691 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700692 @Override
693 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700694 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700695
696 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700697 final int uid = intent.getIntExtra(EXTRA_UID, -1);
698 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700699
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700700 if (ACTION_PACKAGE_ADDED.equals(action)) {
701 // update rules for UID, since it might be subject to
702 // global background data policy
703 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
704 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700705 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700706 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700707 }
708 }
709 };
710
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700711 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700712 @Override
713 public void onReceive(Context context, Intent intent) {
714 // on background handler thread, and UID_REMOVED is protected
715
716 final int uid = intent.getIntExtra(EXTRA_UID, -1);
717 if (uid == -1) return;
718
719 // remove any policy and update rules to clean up
720 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
721 synchronized (mRulesLock) {
722 mUidPolicy.delete(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -0700723 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700724 writePolicyLocked();
725 }
726 }
727 };
728
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700729 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700730 @Override
731 public void onReceive(Context context, Intent intent) {
732 // on background handler thread, and USER_ADDED and USER_REMOVED
733 // broadcasts are protected
734
735 final String action = intent.getAction();
736 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
737 if (userId == -1) return;
738
Amith Yamasani15e472352015-04-24 19:06:07 -0700739 switch (action) {
740 case ACTION_USER_REMOVED:
741 case ACTION_USER_ADDED:
742 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800743 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700744 // USER_REMOVED, and one last sanity check during USER_ADDED
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800745 removeUserStateLocked(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700746 if (action == ACTION_USER_ADDED) {
747 // Add apps that are whitelisted by default.
748 addDefaultRestrictBackgroundWhitelistUidsLocked(userId);
749 }
750 // Update global restrict for that user
Amith Yamasani15e472352015-04-24 19:06:07 -0700751 updateRulesForGlobalChangeLocked(true);
752 }
753 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700754 }
755 }
756 };
757
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700758 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700759 * Receiver that watches for {@link INetworkStatsService} updates, which we
760 * use to check against {@link NetworkPolicy#warningBytes}.
761 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700762 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700763 @Override
764 public void onReceive(Context context, Intent intent) {
765 // on background handler thread, and verified
766 // READ_NETWORK_USAGE_HISTORY permission above.
767
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800768 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700769 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700770 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700771 updateNotificationsLocked();
772 }
773 }
774 };
775
776 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700777 * Receiver that watches for {@link Notification} control of
778 * {@link #mRestrictBackground}.
779 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700780 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700781 @Override
782 public void onReceive(Context context, Intent intent) {
783 // on background handler thread, and verified MANAGE_NETWORK_POLICY
784 // permission above.
785
786 setRestrictBackground(false);
787 }
788 };
789
790 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800791 * Receiver that watches for {@link Notification} control of
792 * {@link NetworkPolicy#lastWarningSnooze}.
793 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700794 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800795 @Override
796 public void onReceive(Context context, Intent intent) {
797 // on background handler thread, and verified MANAGE_NETWORK_POLICY
798 // permission above.
799
800 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
801 performSnooze(template, TYPE_WARNING);
802 }
803 };
804
805 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700806 * Receiver that watches for {@link WifiConfiguration} to be changed.
807 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700808 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700809 @Override
810 public void onReceive(Context context, Intent intent) {
811 // on background handler thread, and verified CONNECTIVITY_INTERNAL
812 // permission above.
813
814 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
815 if (reason == CHANGE_REASON_REMOVED) {
816 final WifiConfiguration config = intent.getParcelableExtra(
817 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700818 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800819 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700820 synchronized (mRulesLock) {
821 if (mNetworkPolicy.containsKey(template)) {
822 mNetworkPolicy.remove(template);
823 writePolicyLocked();
824 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700825 }
826 }
827 }
828 }
829 };
830
831 /**
832 * Receiver that watches {@link WifiInfo} state changes to infer metered
833 * state. Ignores hints when policy is user-defined.
834 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700835 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700836 @Override
837 public void onReceive(Context context, Intent intent) {
838 // on background handler thread, and verified CONNECTIVITY_INTERNAL
839 // permission above.
840
841 // ignore when not connected
842 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
843 if (!netInfo.isConnected()) return;
844
845 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
846 final boolean meteredHint = info.getMeteredHint();
847
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800848 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700849 synchronized (mRulesLock) {
850 NetworkPolicy policy = mNetworkPolicy.get(template);
851 if (policy == null && meteredHint) {
852 // policy doesn't exist, and AP is hinting that it's
853 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800854 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700855 addNetworkPolicyLocked(policy);
856
857 } else if (policy != null && policy.inferred) {
858 // policy exists, and was inferred: update its current
859 // metered state.
860 policy.metered = meteredHint;
861
862 // since this is inferred for each wifi session, just update
863 // rules without persisting.
864 updateNetworkRulesLocked();
865 }
866 }
867 }
868 };
869
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800870 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
871 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
872 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
873 metered, true);
874 }
875
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700876 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700877 * Observer that watches for {@link INetworkManagementService} alerts.
878 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700879 final private INetworkManagementEventObserver mAlertObserver
880 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700881 @Override
882 public void limitReached(String limitName, String iface) {
883 // only someone like NMS should be calling us
884 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
885
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800886 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
887 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700888 }
889 }
890 };
891
892 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700893 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
894 * to show visible notifications as needed.
895 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700896 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
898
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700899 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700900 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700901 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700902
903 // TODO: when switching to kernel notifications, compute next future
904 // cycle boundary to recompute notifications.
905
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700906 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800907 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700908 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
909 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700910 // ignore policies that aren't relevant to user
911 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700912 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700913
Jeff Sharkey497e4432011-06-14 17:27:29 -0700914 final long start = computeLastCycleBoundary(currentTime, policy);
915 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700916 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700917
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700918 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800919 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700920 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
921 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700922 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
923 notifyOverLimitLocked(policy.template);
924 }
925
Jeff Sharkey497e4432011-06-14 17:27:29 -0700926 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700930 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700931 }
932 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700933 }
934
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700935 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700936 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
937 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700938 if (!mActiveNotifs.contains(tag)) {
939 cancelNotification(tag);
940 }
941 }
942 }
943
944 /**
945 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700946 * current device state, such as when
947 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
948 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 */
950 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800951 if (template.isMatchRuleMobile()) {
952 final TelephonyManager tele = TelephonyManager.from(mContext);
953 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700954
Jeff Sharkey32566012014-12-02 18:30:14 -0800955 // Mobile template is relevant when any active subscriber matches
956 final int[] subIds = sub.getActiveSubscriptionIdList();
957 for (int subId : subIds) {
958 final String subscriberId = tele.getSubscriberId(subId);
959 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700960 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800961 if (template.matches(probeIdent)) {
962 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700963 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800964 }
965 return false;
966 } else {
967 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700968 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700969 }
970
971 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700972 * Notify that given {@link NetworkTemplate} is over
973 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
974 */
975 private void notifyOverLimitLocked(NetworkTemplate template) {
976 if (!mOverLimitNotified.contains(template)) {
977 mContext.startActivity(buildNetworkOverLimitIntent(template));
978 mOverLimitNotified.add(template);
979 }
980 }
981
982 private void notifyUnderLimitLocked(NetworkTemplate template) {
983 mOverLimitNotified.remove(template);
984 }
985
986 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987 * Build unique tag that identifies an active {@link NetworkPolicy}
988 * notification of a specific type, like {@link #TYPE_LIMIT}.
989 */
990 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700991 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700992 }
993
994 /**
995 * Show notification for combined {@link NetworkPolicy} and specific type,
996 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
997 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700998 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700999 final String tag = buildNotificationTag(policy, type);
1000 final Notification.Builder builder = new Notification.Builder(mContext);
1001 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001002 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001003 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001004 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005
1006 final Resources res = mContext.getResources();
1007 switch (type) {
1008 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001009 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001010 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001011
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001012 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013 builder.setTicker(title);
1014 builder.setContentTitle(title);
1015 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001016
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001017 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1018 builder.setDeleteIntent(PendingIntent.getBroadcast(
1019 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1020
1021 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001022 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001023 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1024
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025 break;
1026 }
1027 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001028 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1029
1030 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001031 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001032 switch (policy.template.getMatchRule()) {
1033 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001036 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001039 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001040 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001041 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001042 case MATCH_WIFI:
1043 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001044 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001045 break;
1046 default:
1047 title = null;
1048 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049 }
1050
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001052 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001053 builder.setTicker(title);
1054 builder.setContentTitle(title);
1055 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001056
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001057 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1058 builder.setContentIntent(PendingIntent.getActivity(
1059 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1060 break;
1061 }
1062 case TYPE_LIMIT_SNOOZED: {
1063 final long overBytes = totalBytes - policy.limitBytes;
1064 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1065 Formatter.formatFileSize(mContext, overBytes));
1066
1067 final CharSequence title;
1068 switch (policy.template.getMatchRule()) {
1069 case MATCH_MOBILE_3G_LOWER:
1070 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1071 break;
1072 case MATCH_MOBILE_4G:
1073 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1074 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001075 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1077 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001078 case MATCH_WIFI:
1079 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1080 break;
1081 default:
1082 title = null;
1083 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 }
1085
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001086 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001087 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001088 builder.setTicker(title);
1089 builder.setContentTitle(title);
1090 builder.setContentText(body);
1091
1092 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001093 builder.setContentIntent(PendingIntent.getActivity(
1094 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001095 break;
1096 }
1097 }
1098
1099 // TODO: move to NotificationManager once we can mock it
1100 try {
1101 final String packageName = mContext.getPackageName();
1102 final int[] idReceived = new int[1];
1103 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001104 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001105 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001107 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001108 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001109 }
1110 }
1111
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001112 private void cancelNotification(String tag) {
1113 // TODO: move to NotificationManager once we can mock it
1114 try {
1115 final String packageName = mContext.getPackageName();
1116 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001117 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001118 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001119 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001120 }
1121 }
1122
1123 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001124 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001125 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001126 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001127 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001128 @Override
1129 public void onReceive(Context context, Intent intent) {
1130 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1131 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001132
1133 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001134 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001135 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001136 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001137 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001138 updateNetworkRulesLocked();
1139 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140 }
1141 }
1142 };
1143
1144 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 * Proactively control network data connections when they exceed
1146 * {@link NetworkPolicy#limitBytes}.
1147 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001148 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001149 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1150
1151 // TODO: reset any policy-disabled networks when any policy is removed
1152 // completely, which is currently rare case.
1153
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001154 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001155 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1156 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001157 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001158 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159 setNetworkTemplateEnabled(policy.template, true);
1160 continue;
1161 }
1162
1163 final long start = computeLastCycleBoundary(currentTime, policy);
1164 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001165 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001166
1167 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001168 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1169 && policy.lastLimitSnooze < start;
1170 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001171
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001172 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001173 }
1174 }
1175
1176 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001177 * Proactively disable networks that match the given
1178 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001179 */
1180 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001181 // TODO: reach into ConnectivityManager to proactively disable bringing
1182 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 }
1184
1185 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001186 * Examine all connected {@link NetworkState}, looking for
1187 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1188 * remaining quota based on usage cycle and historical stats.
1189 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001190 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001191 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001192
1193 final NetworkState[] states;
1194 try {
1195 states = mConnManager.getAllNetworkState();
1196 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001197 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001198 return;
1199 }
1200
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001201 // First, generate identities of all connected networks so we can
1202 // quickly compare them against all defined policies below.
1203 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001204 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001206 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001208
1209 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001210 if (baseIface != null) {
1211 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001212 }
1213
1214 // Stacked interfaces are considered to have same identity as
1215 // their parent network.
1216 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1217 for (LinkProperties stackedLink : stackedLinks) {
1218 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001219 if (stackedIface != null) {
1220 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001221 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001222 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223 }
1224 }
1225
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001226 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001227 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001228 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001229 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001230 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001231
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001233 for (int j = connIdents.size() - 1; j >= 0; j--) {
1234 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1235 if (policy.template.matches(ident.second)) {
1236 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237 }
1238 }
1239
1240 if (ifaceList.size() > 0) {
1241 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001242 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 }
1244 }
1245
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001246 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001247 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001248
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001249 // apply each policy that we found ifaces for; compute remaining data
1250 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001251 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001252 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1253 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1254 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001255
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001256 final long start;
1257 final long totalBytes;
1258 if (policy.hasCycle()) {
1259 start = computeLastCycleBoundary(currentTime, policy);
1260 totalBytes = getTotalBytes(policy.template, start, currentTime);
1261 } else {
1262 start = Long.MAX_VALUE;
1263 totalBytes = 0;
1264 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001265
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001266 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001267 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001268 }
1269
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001270 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001271 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001272 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001273 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001274 if (!hasLimit) {
1275 // metered network, but no policy limit; we still need to
1276 // restrict apps, so push really high quota.
1277 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001278 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001279 // snoozing past quota, but we still need to restrict apps,
1280 // so push really high quota.
1281 quotaBytes = Long.MAX_VALUE;
1282 } else {
1283 // remaining "quota" bytes are based on total usage in
1284 // current cycle. kernel doesn't like 0-byte rules, so we
1285 // set 1-byte quota and disable the radio later.
1286 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1287 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001288
1289 if (ifaces.length > 1) {
1290 // TODO: switch to shared quota once NMS supports
1291 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001292 }
1293
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001294 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001295 // long quotaBytes split up into two ints to fit in message
1296 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1297 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1298 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001299 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001300 }
1301 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001302
1303 // keep track of lowest warning or limit of active policies
1304 if (hasWarning && policy.warningBytes < lowestRule) {
1305 lowestRule = policy.warningBytes;
1306 }
1307 if (hasLimit && policy.limitBytes < lowestRule) {
1308 lowestRule = policy.limitBytes;
1309 }
1310 }
1311
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001312 for (int i = connIfaces.size()-1; i >= 0; i--) {
1313 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001314 // long quotaBytes split up into two ints to fit in message
1315 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1316 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1317 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001318 newMeteredIfaces.add(iface);
1319 }
1320
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001321 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001322
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001323 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001324 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1325 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001326 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001327 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1328 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001329 }
1330 }
1331 mMeteredIfaces = newMeteredIfaces;
1332
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001333 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001334 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001335 }
1336
1337 /**
1338 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1339 * have at least a default mobile policy defined.
1340 */
1341 private void ensureActiveMobilePolicyLocked() {
1342 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001343 if (mSuppressDefaultPolicy) return;
1344
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001345 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001346 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001347
Jeff Sharkey32566012014-12-02 18:30:14 -08001348 final int[] subIds = sub.getActiveSubscriptionIdList();
1349 for (int subId : subIds) {
1350 final String subscriberId = tele.getSubscriberId(subId);
1351 ensureActiveMobilePolicyLocked(subscriberId);
1352 }
1353 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001354
Jeff Sharkey32566012014-12-02 18:30:14 -08001355 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1356 // Poke around to see if we already have a policy
1357 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001358 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001359 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1360 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1361 if (template.matches(probeIdent)) {
1362 if (LOGD) {
1363 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1364 + NetworkIdentity.scrubSubscriberId(subscriberId));
1365 }
1366 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001367 }
1368 }
1369
Jeff Sharkey32566012014-12-02 18:30:14 -08001370 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1371 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001372
Jeff Sharkey32566012014-12-02 18:30:14 -08001373 // Build default mobile policy, and assume usage cycle starts today
1374 final long warningBytes = mContext.getResources().getInteger(
1375 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001376
Jeff Sharkey32566012014-12-02 18:30:14 -08001377 final Time time = new Time();
1378 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001379
Jeff Sharkey32566012014-12-02 18:30:14 -08001380 final int cycleDay = time.monthDay;
1381 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001382
Jeff Sharkey32566012014-12-02 18:30:14 -08001383 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1384 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1385 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1386 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001387 }
1388
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001389 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001390 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001391
1392 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001393 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001394 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395
1396 FileInputStream fis = null;
1397 try {
1398 fis = mPolicyFile.openRead();
1399 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001400 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001401
1402 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001403 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001404 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405 while ((type = in.next()) != END_DOCUMENT) {
1406 final String tag = in.getName();
1407 if (type == START_TAG) {
1408 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001409 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001410 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001411 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1412 mRestrictBackground = readBooleanAttribute(
1413 in, ATTR_RESTRICT_BACKGROUND);
1414 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001415 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001416 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001417 if (mRestrictBackground != oldValue) {
1418 // Some early services may have read the default value,
1419 // so notify them that it's changed
1420 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1421 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1422 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001423
1424 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1425 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1426 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001427 final String networkId;
1428 if (version >= VERSION_ADDED_NETWORK_ID) {
1429 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1430 } else {
1431 networkId = null;
1432 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001433 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001434 final String cycleTimezone;
1435 if (version >= VERSION_ADDED_TIMEZONE) {
1436 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1437 } else {
1438 cycleTimezone = Time.TIMEZONE_UTC;
1439 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001440 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1441 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001442 final long lastLimitSnooze;
1443 if (version >= VERSION_SPLIT_SNOOZE) {
1444 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1445 } else if (version >= VERSION_ADDED_SNOOZE) {
1446 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001447 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001448 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001449 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001450 final boolean metered;
1451 if (version >= VERSION_ADDED_METERED) {
1452 metered = readBooleanAttribute(in, ATTR_METERED);
1453 } else {
1454 switch (networkTemplate) {
1455 case MATCH_MOBILE_3G_LOWER:
1456 case MATCH_MOBILE_4G:
1457 case MATCH_MOBILE_ALL:
1458 metered = true;
1459 break;
1460 default:
1461 metered = false;
1462 }
1463 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001464 final long lastWarningSnooze;
1465 if (version >= VERSION_SPLIT_SNOOZE) {
1466 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1467 } else {
1468 lastWarningSnooze = SNOOZE_NEVER;
1469 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001470 final boolean inferred;
1471 if (version >= VERSION_ADDED_INFERRED) {
1472 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1473 } else {
1474 inferred = false;
1475 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476
Jeff Sharkey32566012014-12-02 18:30:14 -08001477 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1478 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001479 if (template.isPersistable()) {
1480 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1481 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1482 lastLimitSnooze, metered, inferred));
1483 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001485 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 final int uid = readIntAttribute(in, ATTR_UID);
1487 final int policy = readIntAttribute(in, ATTR_POLICY);
1488
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001489 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001490 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001491 } else {
1492 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1493 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001494 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001495 final int appId = readIntAttribute(in, ATTR_APP_ID);
1496 final int policy = readIntAttribute(in, ATTR_POLICY);
1497
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001498 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001499 // app policy is deprecated so this is only used in pre system user split.
1500 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001501 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001502 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001503 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001504 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001505 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001506 } else if (TAG_WHITELIST.equals(tag)) {
1507 insideWhitelist = true;
1508 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1509 final int uid = readIntAttribute(in, ATTR_UID);
1510 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001511 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1512 final int uid = readIntAttribute(in, ATTR_UID);
1513 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001514 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001515 } else if (type == END_TAG) {
1516 if (TAG_WHITELIST.equals(tag)) {
1517 insideWhitelist = false;
1518 }
1519
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001520 }
1521 }
1522
1523 } catch (FileNotFoundException e) {
1524 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001525 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001526 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001527 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001529 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001530 } finally {
1531 IoUtils.closeQuietly(fis);
1532 }
1533 }
1534
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001535 /**
1536 * Upgrade legacy background data flags, notifying listeners of one last
1537 * change to always-true.
1538 */
1539 private void upgradeLegacyBackgroundData() {
1540 mRestrictBackground = Settings.Secure.getInt(
1541 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1542
1543 // kick off one last broadcast if restricted
1544 if (mRestrictBackground) {
1545 final Intent broadcast = new Intent(
1546 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001547 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001548 }
1549 }
1550
Dianne Hackborn497175b2014-07-01 12:56:08 -07001551 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001552 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001553
1554 FileOutputStream fos = null;
1555 try {
1556 fos = mPolicyFile.startWrite();
1557
1558 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001559 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560 out.startDocument(null, true);
1561
1562 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001563 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001564 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001565
1566 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001567 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1568 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001569 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001570 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001571
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001573 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1574 final String subscriberId = template.getSubscriberId();
1575 if (subscriberId != null) {
1576 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001578 final String networkId = template.getNetworkId();
1579 if (networkId != null) {
1580 out.attribute(null, ATTR_NETWORK_ID, networkId);
1581 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001583 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1585 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001586 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1587 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001588 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001589 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001590 out.endTag(null, TAG_NETWORK_POLICY);
1591 }
1592
1593 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001594 for (int i = 0; i < mUidPolicy.size(); i++) {
1595 final int uid = mUidPolicy.keyAt(i);
1596 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001597
Jeff Sharkey497e4432011-06-14 17:27:29 -07001598 // skip writing empty policies
1599 if (policy == POLICY_NONE) continue;
1600
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001601 out.startTag(null, TAG_UID_POLICY);
1602 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001603 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001604 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 }
1606
1607 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001608
1609 // write all whitelists
1610 out.startTag(null, TAG_WHITELIST);
1611
1612 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001613 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001614 for (int i = 0; i < size; i++) {
1615 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1616 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1617 writeIntAttribute(out, ATTR_UID, uid);
1618 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1619 }
1620
Felipe Lemea9505cc2016-02-26 10:28:41 -08001621 // revoked restrict background whitelist
1622 size = mRestrictBackgroundWhitelistRevokedUids.size();
1623 for (int i = 0; i < size; i++) {
1624 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1625 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1626 writeIntAttribute(out, ATTR_UID, uid);
1627 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1628 }
1629
Felipe Lemeb85a6372016-01-14 16:16:16 -08001630 out.endTag(null, TAG_WHITELIST);
1631
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001632 out.endDocument();
1633
1634 mPolicyFile.finishWrite(fos);
1635 } catch (IOException e) {
1636 if (fos != null) {
1637 mPolicyFile.failWrite(fos);
1638 }
1639 }
1640 }
1641
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001642 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001643 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001645
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001646 if (!UserHandle.isApp(uid)) {
1647 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001648 }
1649
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001650 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001651 final long token = Binder.clearCallingIdentity();
1652 try {
1653 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1654 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001655 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001656 }
1657 } finally {
1658 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001659 }
1660 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001661 }
1662
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001663 @Override
1664 public void addUidPolicy(int uid, int policy) {
1665 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001666
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001667 if (!UserHandle.isApp(uid)) {
1668 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1669 }
1670
1671 synchronized (mRulesLock) {
1672 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1673 policy |= oldPolicy;
1674 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001675 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001676 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001678 }
1679
1680 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001681 public void removeUidPolicy(int uid, int policy) {
1682 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1683
1684 if (!UserHandle.isApp(uid)) {
1685 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1686 }
1687
1688 synchronized (mRulesLock) {
1689 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1690 policy = oldPolicy & ~policy;
1691 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001692 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001693 }
1694 }
1695 }
1696
Felipe Leme923845f2016-03-02 13:42:48 -08001697 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1698 setUidPolicyUncheckedLocked(uid, policy, persist);
1699
1700 // Checks if app was added or removed to the blacklist.
1701 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1702 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001703 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001704 .sendToTarget();
1705 }
1706 }
1707
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001708 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1709 mUidPolicy.put(uid, policy);
1710
1711 // uid policy changed, recompute rules and persist policy.
Felipe Lemef28983d2016-03-25 12:18:23 -07001712 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001713 if (persist) {
1714 writePolicyLocked();
1715 }
1716 }
1717
1718 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001719 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001720 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1721
Jeff Sharkeya4620792011-05-20 15:29:23 -07001722 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001723 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001724 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001725 }
1726
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001727 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001728 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001729 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1730
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001731 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001732 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001733 for (int i = 0; i < mUidPolicy.size(); i++) {
1734 final int uid = mUidPolicy.keyAt(i);
1735 final int uidPolicy = mUidPolicy.valueAt(i);
1736 if (uidPolicy == policy) {
1737 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001738 }
1739 }
1740 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001741 return uids;
1742 }
1743
1744 /**
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001745 * Remove any persistable state associated with given {@link UserHandle}, persisting
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001746 * if any changes are made.
1747 */
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001748 void removeUserStateLocked(int userId) {
1749 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
1750 boolean writePolicy = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001751
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001752 // Remove entries from restricted background UID whitelist
1753 int[] wlUids = new int[0];
1754 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1755 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1756 if (UserHandle.getUserId(uid) == userId) {
1757 wlUids = appendInt(wlUids, uid);
1758 }
1759 }
1760
1761 if (wlUids.length > 0) {
1762 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001763 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001764 }
1765 writePolicy = true;
1766 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001767
1768 // Remove entries from revoked default restricted background UID whitelist
1769 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1770 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1771 if (UserHandle.getUserId(uid) == userId) {
1772 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
1773 writePolicy = true;
1774 }
1775 }
1776
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001777 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001778 int[] uids = new int[0];
1779 for (int i = 0; i < mUidPolicy.size(); i++) {
1780 final int uid = mUidPolicy.keyAt(i);
1781 if (UserHandle.getUserId(uid) == userId) {
1782 uids = appendInt(uids, uid);
1783 }
1784 }
1785
1786 if (uids.length > 0) {
1787 for (int uid : uids) {
1788 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001789 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001790 writePolicy = true;
1791 }
1792
Felipe Leme76010a32016-03-17 13:03:11 -07001793 updateRulesForGlobalChangeLocked(true);
1794
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001795 if (writePolicy) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001796 writePolicyLocked();
1797 }
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001798 }
1799
1800 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001801 public void setConnectivityListener(INetworkPolicyListener listener) {
1802 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1803 if (mConnectivityListener != null) {
1804 throw new IllegalStateException("Connectivity listener already registered");
1805 }
1806 mConnectivityListener = listener;
1807 }
1808
1809 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001810 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001811 // TODO: create permission for observing network policy
1812 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001813 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001814 }
1815
1816 @Override
1817 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001818 // TODO: create permission for observing network policy
1819 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001820 mListeners.unregister(listener);
1821 }
1822
Jeff Sharkey1b861272011-05-22 00:34:52 -07001823 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001824 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001825 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1826
Felipe Leme6a05eee2016-02-19 14:43:51 -08001827 final long token = Binder.clearCallingIdentity();
1828 try {
1829 maybeRefreshTrustedTime();
1830 synchronized (mRulesLock) {
1831 normalizePoliciesLocked(policies);
1832 updateNetworkEnabledLocked();
1833 updateNetworkRulesLocked();
1834 updateNotificationsLocked();
1835 writePolicyLocked();
1836 }
1837 } finally {
1838 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001839 }
1840 }
1841
Dianne Hackborn497175b2014-07-01 12:56:08 -07001842 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001843 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001844 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1845 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001846 }
1847
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001848 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001849 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001851 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001852 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1853 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1854 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001855 } catch (SecurityException e) {
1856 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001857
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001858 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1859 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1860 return new NetworkPolicy[0];
1861 }
Svet Ganov16a16892015-04-16 10:32:04 -07001862 }
1863
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001864 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001865 final int size = mNetworkPolicy.size();
1866 final NetworkPolicy[] policies = new NetworkPolicy[size];
1867 for (int i = 0; i < size; i++) {
1868 policies[i] = mNetworkPolicy.valueAt(i);
1869 }
1870 return policies;
1871 }
1872 }
1873
1874 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001875 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001876 }
1877
1878 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1879 final TelephonyManager tele = TelephonyManager.from(mContext);
1880 final String[] merged = tele.getMergedSubscriberIds();
1881
1882 mNetworkPolicy.clear();
1883 for (NetworkPolicy policy : policies) {
1884 // When two normalized templates conflict, prefer the most
1885 // restrictive policy
1886 policy.template = NetworkTemplate.normalize(policy.template, merged);
1887 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1888 if (existing == null || existing.compareTo(policy) > 0) {
1889 if (existing != null) {
1890 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1891 }
1892 mNetworkPolicy.put(policy.template, policy);
1893 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001894 }
1895 }
1896
1897 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001898 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001899 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001900
1901 final long token = Binder.clearCallingIdentity();
1902 try {
1903 performSnooze(template, TYPE_LIMIT);
1904 } finally {
1905 Binder.restoreCallingIdentity(token);
1906 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001907 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001908
Dianne Hackborn497175b2014-07-01 12:56:08 -07001909 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001910 maybeRefreshTrustedTime();
1911 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001912 synchronized (mRulesLock) {
1913 // find and snooze local policy that matches
1914 final NetworkPolicy policy = mNetworkPolicy.get(template);
1915 if (policy == null) {
1916 throw new IllegalArgumentException("unable to find policy for " + template);
1917 }
1918
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001919 switch (type) {
1920 case TYPE_WARNING:
1921 policy.lastWarningSnooze = currentTime;
1922 break;
1923 case TYPE_LIMIT:
1924 policy.lastLimitSnooze = currentTime;
1925 break;
1926 default:
1927 throw new IllegalArgumentException("unexpected type");
1928 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001929
Jeff Sharkey32566012014-12-02 18:30:14 -08001930 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001931 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001932 updateNetworkRulesLocked();
1933 updateNotificationsLocked();
1934 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001935 }
1936 }
1937
1938 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001939 public void onTetheringChanged(String iface, boolean tethering) {
1940 // No need to enforce permission because setRestrictBackground() will do it.
1941 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1942 synchronized (mRulesLock) {
1943 if (mRestrictBackground && tethering) {
1944 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1945 setRestrictBackground(false);
1946 }
1947 }
1948 }
1949
1950 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001951 public void setRestrictBackground(boolean restrictBackground) {
1952 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001953 final long token = Binder.clearCallingIdentity();
1954 try {
1955 maybeRefreshTrustedTime();
1956 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001957 if (restrictBackground == mRestrictBackground) {
1958 // Ideally, UI should never allow this scenario...
1959 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1960 return;
1961 }
1962 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001963 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001964
Felipe Leme6a05eee2016-02-19 14:43:51 -08001965 } finally {
1966 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001967 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001968
1969 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1970 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001971 }
1972
Felipe Leme70c57c22016-03-29 10:45:13 -07001973 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1974 final boolean oldRestrictBackground = mRestrictBackground;
1975 mRestrictBackground = restrictBackground;
1976 // Must whitelist foreground apps before turning data saver mode on.
1977 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1978 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
1979 updateRulesForRestrictBackgroundLocked();
1980 try {
1981 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
1982 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
1983 mRestrictBackground = oldRestrictBackground;
1984 // TODO: if it knew the foreground apps (see TODO above), it could call
1985 // updateRulesForRestrictBackgroundLocked() again to restore state.
1986 return;
1987 }
1988 } catch (RemoteException e) {
1989 // ignored; service lives in system_server
1990 }
1991 updateNotificationsLocked();
1992 writePolicyLocked();
1993 }
1994
Jeff Sharkey46645002011-07-27 21:11:21 -07001995 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08001996 public void addRestrictBackgroundWhitelistedUid(int uid) {
1997 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07001998 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07001999 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002000 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002001 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002002 if (oldStatus) {
2003 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2004 return;
2005 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002006 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002007 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002008 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002009 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2010 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2011 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2012 + " from revoked restrict background whitelist");
2013 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2014 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002015 if (needFirewallRules) {
2016 // Only update firewall rules if necessary...
2017 updateRuleForRestrictBackgroundLocked(uid);
2018 }
2019 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08002020 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002021 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002022 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
2023 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2024 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002025 }
2026
2027 @Override
2028 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2029 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002030 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002031 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002032 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002033 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002034 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2035 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002036 }
2037
Felipe Leme70c57c22016-03-29 10:45:13 -07002038 /**
2039 * Removes a uid from the restricted background whitelist, returning whether its current
2040 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2041 */
2042 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2043 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002044 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
2045 if (!oldStatus) {
2046 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2047 return false;
2048 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002049 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002050 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002051 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002052 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2053 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2054 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2055 + " to revoked restrict background whitelist");
2056 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2057 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002058 if (needFirewallRules) {
2059 // Only update firewall rules if necessary...
2060 updateRuleForRestrictBackgroundLocked(uid, uidDeleted);
2061 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002062 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002063 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002064 writePolicyLocked();
2065 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002066 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2067 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002068 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002069 }
2070
2071 @Override
2072 public int[] getRestrictBackgroundWhitelistedUids() {
2073 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2074 synchronized (mRulesLock) {
2075 final int size = mRestrictBackgroundWhitelistUids.size();
2076 final int[] whitelist = new int[size];
2077 for (int i = 0; i < size; i++) {
2078 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2079 }
2080 if (LOGV) {
2081 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2082 + mRestrictBackgroundWhitelistUids);
2083 }
2084 return whitelist;
2085 }
2086 }
2087
2088 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002089 public int getRestrictBackgroundByCaller() {
2090 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2091 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002092
Felipe Leme1b103232016-01-22 09:44:57 -08002093 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002094 // Must clear identity because getUidPolicy() is restricted to system.
2095 final long token = Binder.clearCallingIdentity();
2096 final int policy;
2097 try {
2098 policy = getUidPolicy(uid);
2099 } finally {
2100 Binder.restoreCallingIdentity(token);
2101 }
2102 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2103 // App is blacklisted.
2104 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2105 }
Felipe Leme1b103232016-01-22 09:44:57 -08002106 if (!mRestrictBackground) {
2107 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2108 }
2109 return mRestrictBackgroundWhitelistUids.get(uid)
2110 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2111 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2112 }
2113 }
2114
2115 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002116 public boolean getRestrictBackground() {
2117 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2118
2119 synchronized (mRulesLock) {
2120 return mRestrictBackground;
2121 }
2122 }
2123
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002124 @Override
2125 public void setDeviceIdleMode(boolean enabled) {
2126 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2127
2128 synchronized (mRulesLock) {
2129 if (mDeviceIdleMode != enabled) {
2130 mDeviceIdleMode = enabled;
2131 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002132 // Device idle change means we need to rebuild rules for all
2133 // known apps, so do a global refresh.
2134 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002135 }
2136 if (enabled) {
2137 EventLogTags.writeDeviceIdleOnPhase("net");
2138 } else {
2139 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002140 }
2141 }
2142 }
2143 }
2144
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002145 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002146 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2147 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002148 if (policy.template.matches(ident)) {
2149 return policy;
2150 }
2151 }
2152 return null;
2153 }
2154
2155 @Override
2156 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2157 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2158
2159 // only returns usage summary, so we don't require caller to have
2160 // READ_NETWORK_USAGE_HISTORY.
2161 final long token = Binder.clearCallingIdentity();
2162 try {
2163 return getNetworkQuotaInfoUnchecked(state);
2164 } finally {
2165 Binder.restoreCallingIdentity(token);
2166 }
2167 }
2168
2169 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2170 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2171
2172 final NetworkPolicy policy;
2173 synchronized (mRulesLock) {
2174 policy = findPolicyForNetworkLocked(ident);
2175 }
2176
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002177 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002178 // missing policy means we can't derive useful quota info
2179 return null;
2180 }
2181
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002182 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002183
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002184 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002185 final long start = computeLastCycleBoundary(currentTime, policy);
2186 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002187 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002188
2189 // report soft and hard limits under policy
2190 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2191 : NetworkQuotaInfo.NO_LIMIT;
2192 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2193 : NetworkQuotaInfo.NO_LIMIT;
2194
2195 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2196 }
2197
Jeff Sharkey46645002011-07-27 21:11:21 -07002198 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002199 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002200 if (state.networkInfo == null) {
2201 return false;
2202 }
2203
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002204 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2205
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002206 // roaming networks are always considered metered
2207 if (ident.getRoaming()) {
2208 return true;
2209 }
2210
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002211 final NetworkPolicy policy;
2212 synchronized (mRulesLock) {
2213 policy = findPolicyForNetworkLocked(ident);
2214 }
2215
2216 if (policy != null) {
2217 return policy.metered;
2218 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002219 final int type = state.networkInfo.getType();
2220 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2221 return true;
2222 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002223 return false;
2224 }
2225 }
2226
2227 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002228 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002229 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002230
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002231 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2232
Dianne Hackborn497175b2014-07-01 12:56:08 -07002233 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002234 for (String arg : args) {
2235 argSet.add(arg);
2236 }
2237
Jeff Sharkey1b861272011-05-22 00:34:52 -07002238 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002239 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002240 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2241 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002242 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002243
Jeff Sharkey32566012014-12-02 18:30:14 -08002244 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002245 updateNetworkEnabledLocked();
2246 updateNetworkRulesLocked();
2247 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002248 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002249
2250 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002251 return;
2252 }
2253
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002254 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002255 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002256 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002257 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002258 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002259 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002260 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2261 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002262 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002263 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002264
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002265 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2266
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002267 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002268 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002269 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002270 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002271 final int uid = mUidPolicy.keyAt(i);
2272 final int policy = mUidPolicy.valueAt(i);
2273 fout.print("UID=");
2274 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002275 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002276 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002277 fout.println();
2278 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002279 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002280
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002281 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2282 if (size > 0) {
2283 fout.println("Power save whitelist (except idle) app ids:");
2284 fout.increaseIndent();
2285 for (int i = 0; i < size; i++) {
2286 fout.print("UID=");
2287 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2288 fout.print(": ");
2289 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2290 fout.println();
2291 }
2292 fout.decreaseIndent();
2293 }
2294
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002295 size = mPowerSaveWhitelistAppIds.size();
2296 if (size > 0) {
2297 fout.println("Power save whitelist app ids:");
2298 fout.increaseIndent();
2299 for (int i = 0; i < size; i++) {
2300 fout.print("UID=");
2301 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2302 fout.print(": ");
2303 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2304 fout.println();
2305 }
2306 fout.decreaseIndent();
2307 }
2308
Felipe Lemeb85a6372016-01-14 16:16:16 -08002309 size = mRestrictBackgroundWhitelistUids.size();
2310 if (size > 0) {
2311 fout.println("Restrict background whitelist uids:");
2312 fout.increaseIndent();
2313 for (int i = 0; i < size; i++) {
2314 fout.print("UID=");
2315 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2316 fout.println();
2317 }
2318 fout.decreaseIndent();
2319 }
2320
Felipe Lemea9505cc2016-02-26 10:28:41 -08002321 size = mDefaultRestrictBackgroundWhitelistUids.size();
2322 if (size > 0) {
2323 fout.println("Default restrict background whitelist uids:");
2324 fout.increaseIndent();
2325 for (int i = 0; i < size; i++) {
2326 fout.print("UID=");
2327 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2328 fout.println();
2329 }
2330 fout.decreaseIndent();
2331 }
2332
2333 size = mRestrictBackgroundWhitelistRevokedUids.size();
2334 if (size > 0) {
2335 fout.println("Default restrict background whitelist uids revoked by users:");
2336 fout.increaseIndent();
2337 for (int i = 0; i < size; i++) {
2338 fout.print("UID=");
2339 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2340 fout.println();
2341 }
2342 fout.decreaseIndent();
2343 }
2344
Jeff Sharkey1b861272011-05-22 00:34:52 -07002345 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002346 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002347 collectKeys(mUidRules, knownUids);
2348
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002349 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002350 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002351 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002352 for (int i = 0; i < size; i++) {
2353 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002354 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002355 fout.print(uid);
2356
Jeff Sharkeydc988062015-09-14 10:09:47 -07002357 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002358 fout.print(" state=");
2359 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002360 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2361 fout.print(" (fg)");
2362 } else {
2363 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2364 ? " (fg svc)" : " (bg)");
2365 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002366
Jeff Sharkeydc988062015-09-14 10:09:47 -07002367 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2368 fout.print(" rule=");
Felipe Lemef28983d2016-03-25 12:18:23 -07002369 fout.print(ruleToString(rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002370
2371 fout.println();
2372 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002373 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002374 }
2375 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002376
Felipe Lemef28983d2016-03-25 12:18:23 -07002377 private String ruleToString(int rule) {
2378 return DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule);
2379 }
2380
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002381 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002382 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2383 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002384 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002385 this, in, out, err, args, resultReceiver);
2386 }
2387
2388 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002389 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002390 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2391
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002392 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002393 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002394 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002395 }
2396
Felipe Lemef28983d2016-03-25 12:18:23 -07002397 private boolean isUidForegroundLocked(int uid) {
2398 return isUidStateForegroundLocked(
2399 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2400 }
2401
Felipe Lemeef89c902016-03-30 15:11:31 -07002402 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2403 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2404 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2405 }
2406
Felipe Lemef28983d2016-03-25 12:18:23 -07002407 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002408 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002409 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002410 }
2411
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002412 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002413 * Process state of UID changed; if needed, will trigger
Felipe Leme70c57c22016-03-29 10:45:13 -07002414 * {@link #updateRuleForRestrictBackgroundLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002415 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002416 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002417 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2418 if (oldUidState != uidState) {
2419 // state changed, push updated rules
2420 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002421 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002422 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2423 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2424 if (mDeviceIdleMode) {
2425 updateRuleForDeviceIdleLocked(uid);
2426 }
2427 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002428 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002429 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002430 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002431 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002432 }
2433 }
2434
Felipe Lemef28983d2016-03-25 12:18:23 -07002435 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002436 final int index = mUidState.indexOfKey(uid);
2437 if (index >= 0) {
2438 final int oldUidState = mUidState.valueAt(index);
2439 mUidState.removeAt(index);
2440 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002441 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002442 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002443 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002444 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002445 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002446 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002447 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002448 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002449 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002450 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002451 }
2452 }
2453
Felipe Lemef28983d2016-03-25 12:18:23 -07002454 // adjust stats accounting based on foreground status
2455 private void updateNetworkStats(int uid, boolean uidForeground) {
2456 try {
2457 mNetworkStats.setUidForeground(uid, uidForeground);
2458 } catch (RemoteException e) {
2459 // ignored; service lives in system_server
2460 }
2461 }
2462
2463 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2464 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002465 final boolean oldForeground =
2466 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2467 final boolean newForeground =
2468 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002469 if (oldForeground != newForeground) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002470 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002471 }
2472 }
2473
Jeff Sharkeya4620792011-05-20 15:29:23 -07002474 private void updateScreenOn() {
2475 synchronized (mRulesLock) {
2476 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002477 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002478 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002479 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002480 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002481 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002482 }
2483 }
2484
2485 /**
2486 * Update rules that might be changed by {@link #mScreenOn} value.
2487 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002488 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002489 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002490 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002491 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002492 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002493 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002494 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002495 }
2496 }
2497 }
2498
Felipe Leme011b98f2016-02-10 17:28:31 -08002499 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002500 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2501 }
2502
Felipe Lemeef89c902016-03-30 15:11:31 -07002503 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2504 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2505 }
2506
Felipe Leme011b98f2016-02-10 17:28:31 -08002507 void updateRulesForRestrictPowerLocked() {
2508 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2509 mUidFirewallPowerSaveRules);
2510 }
2511
Felipe Lemef28983d2016-03-25 12:18:23 -07002512 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002513 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2514 }
2515
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002516 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002517 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2518 mUidFirewallDozableRules);
2519 }
2520
2521 void updateRuleForDeviceIdleLocked(int uid) {
2522 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2523 }
2524
Felipe Lemef28983d2016-03-25 12:18:23 -07002525 // NOTE: since both fw_dozable and fw_powersave uses the same map
2526 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002527 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2528 SparseIntArray rules) {
2529 if (enabled) {
2530 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002531 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002532 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002533 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002534 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002535 for (int ui = users.size() - 1; ui >= 0; ui--) {
2536 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002537 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002538 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2539 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2540 int uid = UserHandle.getUid(user.id, appId);
2541 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2542 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002543 }
2544 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2545 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2546 int uid = UserHandle.getUid(user.id, appId);
2547 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2548 }
2549 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002550 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002551 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002552 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2553 }
2554 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002555 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002556 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002557
Felipe Leme011b98f2016-02-10 17:28:31 -08002558 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002559 }
2560
Felipe Lemef28983d2016-03-25 12:18:23 -07002561 // NOTE: since both fw_dozable and fw_powersave uses the same map
2562 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002563 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2564 if (enabled) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002565 int appId = UserHandle.getAppId(uid);
2566 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
Felipe Leme011b98f2016-02-10 17:28:31 -08002567 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2568 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002569 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002570 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002571 }
2572 }
2573 }
2574
2575 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002576 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2577 uidRules.clear();
2578
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002579 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002580 final List<UserInfo> users = mUserManager.getUsers();
2581 for (int ui = users.size() - 1; ui >= 0; ui--) {
2582 UserInfo user = users.get(ui);
2583 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2584 for (int uid : idleUids) {
2585 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002586 // quick check: if this uid doesn't have INTERNET permission, it
2587 // doesn't have network access anyway, so it is a waste to mess
2588 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002589 if (hasInternetPermissions(uid)) {
2590 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002591 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002592 }
2593 }
2594 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002595
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002596 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2597 }
2598
2599 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002600 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002601
2602 int appId = UserHandle.getAppId(uid);
2603 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2604 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2605 } else {
2606 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2607 }
2608 }
2609
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002610 void updateRulesForAppIdleParoleLocked() {
2611 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2612 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002613 }
2614
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002615 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002616 * Update rules that might be changed by {@link #mRestrictBackground},
2617 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002618 */
Felipe Leme76010a32016-03-17 13:03:11 -07002619 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002620 long start;
2621 if (LOGD) start = System.currentTimeMillis();
2622
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002623 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002624 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002625 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002626 updateRulesForRestrictBackgroundLocked();
Felipe Leme70c57c22016-03-29 10:45:13 -07002627 setRestrictBackgroundLocked(mRestrictBackground);
Felipe Leme76010a32016-03-17 13:03:11 -07002628
2629 // If the set of restricted networks may have changed, re-evaluate those.
2630 if (restrictedNetworksChanged) {
2631 normalizePoliciesLocked();
2632 updateNetworkRulesLocked();
2633 }
2634 if (LOGD) {
2635 final long delta = System.currentTimeMillis() - start;
2636 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2637 + delta + "ms");
2638 }
2639 }
2640
Felipe Lemef28983d2016-03-25 12:18:23 -07002641 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002642 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002643
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002644 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002645 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002646 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002647 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2648 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2649 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002650
Felipe Leme03e689d2016-03-02 16:17:38 -08002651 final int usersSize = users.size();
2652 final int appsSize = apps.size();
2653 for (int i = 0; i < usersSize; i++) {
2654 final UserInfo user = users.get(i);
2655 for (int j = 0; j < appsSize; j++) {
2656 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002657 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002658 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002659 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002660 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002661 }
2662
Felipe Leme76010a32016-03-17 13:03:11 -07002663 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002664 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002665 for (int i = 0; i < users.size(); i++) {
2666 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002667 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002668 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002669 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002670 updateRuleForAppIdleLocked(uid);
2671 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002672 updateRuleForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002673 }
2674 }
2675 }
2676
Felipe Leme70c57c22016-03-29 10:45:13 -07002677 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2678 // methods below could be merged into a isUidValidForRules() method.
2679 private boolean isUidValidForBlacklistRules(int uid) {
2680 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002681 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002682 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002683 return true;
2684 }
2685
2686 return false;
2687 }
2688
Felipe Leme70c57c22016-03-29 10:45:13 -07002689 private boolean isUidValidForWhitelistRules(int uid) {
2690 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2691 }
2692
Amith Yamasani15e472352015-04-24 19:06:07 -07002693 private boolean isUidIdle(int uid) {
2694 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2695 final int userId = UserHandle.getUserId(uid);
2696
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002697 if (!ArrayUtils.isEmpty(packages)) {
2698 for (String packageName : packages) {
2699 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2700 return false;
2701 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002702 }
2703 }
2704 return true;
2705 }
2706
2707 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002708 * Checks if an uid has INTERNET permissions.
2709 * <p>
2710 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002711 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002712 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002713 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002714 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002715 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002716 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002717 }
2718 } catch (RemoteException e) {
2719 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002720 return true;
2721 }
2722
2723 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002724 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002725 *
Felipe Lemef28983d2016-03-25 12:18:23 -07002726 * <p>There are currently 2 types of restriction rules:
2727 * <ul>
2728 * <li>Battery Saver Mode (also referred as power save).
2729 * <li>Data Saver Mode (formerly known as restrict background data).
2730 * </ul>
Felipe Leme47585ba2016-02-09 16:56:32 -08002731 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002732 private void updateRestrictionRulesForUidLocked(int uid) {
2733 updateRuleForRestrictPowerLocked(uid);
2734 updateRuleForRestrictBackgroundLocked(uid);
2735 }
2736
Felipe Leme70c57c22016-03-29 10:45:13 -07002737 /**
2738 * Applies network rules to bandwidth controllers based on process state and user-defined
2739 * restrictions (blacklist / whitelist).
2740 *
2741 * <p>
2742 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2743 * networks:
2744 * <ul>
2745 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2746 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2747 * also blacklisted.
2748 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2749 * no UIDs other those whitelisted will have access.
2750 * <ul>
2751 *
2752 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2753 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2754 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2755 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
2756 * this ({@link #updateRuleForRestrictBackgroundLocked(int)}) to propagate the rules to
2757 * {@link INetworkManagementService}, but this method should also be called in events (like
2758 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2759 * following rules should also be applied:
2760 *
2761 * <ul>
2762 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2763 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2764 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2765 * {@code bw_penalty_box}.
2766 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2767 * </ul>
2768 *
2769 * <p>For optimization, the rules are only applied on user apps that have internet access
2770 * permission, since there is no need to change the {@code iptables} rule if the app does not
2771 * have permission to use the internet.
2772 *
2773 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
2774 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002775 private void updateRuleForRestrictBackgroundLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002776 updateRuleForRestrictBackgroundLocked(uid, false);
2777 }
2778
2779 /**
2780 * Overloaded version of {@link #updateRuleForRestrictBackgroundLocked(int)} called when an
2781 * app is removed - it ignores the UID validity check.
2782 */
2783 private void updateRuleForRestrictBackgroundLocked(int uid, boolean uidDeleted) {
2784 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2785 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2786 return;
2787 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002788
Dianne Hackborn497175b2014-07-01 12:56:08 -07002789 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002790 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Felipe Leme70c57c22016-03-29 10:45:13 -07002791 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2792 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002793
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002794 int newRule = RULE_UNKNOWN;
2795 final int oldRule = mUidRules.get(uid, RULE_UNKNOWN);
Felipe Leme76010a32016-03-17 13:03:11 -07002796
Felipe Leme70c57c22016-03-29 10:45:13 -07002797 // First step: define the new rule based on user restrictions and foreground state.
2798 if (isForeground) {
2799 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2800 newRule = RULE_TEMPORARY_ALLOW_METERED;
2801 }
2802 } else {
2803 if (isBlacklisted) {
Felipe Leme76010a32016-03-17 13:03:11 -07002804 newRule = RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -07002805 } else if (isWhitelisted) {
2806 newRule = RULE_ALLOW_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002807 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002808 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002809
Felipe Lemef28983d2016-03-25 12:18:23 -07002810 if (LOGV) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002811 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + "):"
2812 + " isForeground=" +isForeground + ", isBlacklisted: " + isBlacklisted
2813 + ", isWhitelisted: " + isWhitelisted + ", newRule: " + ruleToString(newRule)
2814 + ", oldRule: " + ruleToString(oldRule));
Felipe Lemef28983d2016-03-25 12:18:23 -07002815 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002816
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002817 if (newRule == RULE_UNKNOWN) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002818 mUidRules.delete(uid);
2819 } else {
Felipe Leme76010a32016-03-17 13:03:11 -07002820 mUidRules.put(uid, newRule);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002821 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002822
Felipe Leme70c57c22016-03-29 10:45:13 -07002823 // Second step: apply bw changes based on change of state.
2824 if (newRule != oldRule) {
2825 if (newRule == RULE_TEMPORARY_ALLOW_METERED) {
2826 // Temporarily whitelist foreground app, removing from blacklist if necessary
2827 // (since bw_penalty_box prevails over bw_happy_box).
2828
2829 setMeteredNetworkWhitelist(uid, true);
2830 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2831 // but ideally it should be just:
2832 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2833 if (isBlacklisted) {
2834 setMeteredNetworkBlacklist(uid, false);
2835 }
2836 } else if (oldRule == RULE_TEMPORARY_ALLOW_METERED) {
2837 // Remove temporary whitelist from app that is not on foreground anymore.
2838
2839 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2840 // but ideally they should be just:
2841 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2842 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2843 if (!isWhitelisted) {
2844 setMeteredNetworkWhitelist(uid, false);
2845 }
2846 if (isBlacklisted) {
2847 setMeteredNetworkBlacklist(uid, true);
2848 }
2849 } else if (newRule == RULE_REJECT_METERED || oldRule == RULE_REJECT_METERED) {
2850 // Flip state because app was explicitly added or removed to blacklist.
2851 setMeteredNetworkBlacklist(uid, isBlacklisted);
2852 if (oldRule == RULE_REJECT_METERED && isWhitelisted) {
2853 // Since blacklist prevails over whitelist, we need to handle the special case
2854 // where app is whitelisted and blacklisted at the same time (although such
2855 // scenario should be blocked by the UI), then blacklist is removed.
2856 setMeteredNetworkWhitelist(uid, isWhitelisted);
2857 }
2858 } else if (newRule == RULE_ALLOW_METERED || oldRule == RULE_ALLOW_METERED) {
2859 // Flip state because app was explicitly added or removed to whitelist.
2860 setMeteredNetworkWhitelist(uid, isWhitelisted);
2861 } else {
2862 // All scenarios should have been covered above
2863 Log.wtf(TAG, "Unexpected change of state for " + uid
2864 + ": foreground=" + isForeground + ", whitelisted=" + isWhitelisted
2865 + ", blacklisted=" + isBlacklisted + ", newRule="
2866 + ruleToString(newRule) + ", oldRule=" + ruleToString(oldRule));
2867 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002868
2869 // dispatch changed rule to existing listeners
Felipe Leme76010a32016-03-17 13:03:11 -07002870 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newRule).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002871 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002872 }
2873
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002874 private class AppIdleStateChangeListener
2875 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2876
2877 @Override
2878 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2879 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002880 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2881 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002882 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002883 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002884 }
2885 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002886 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002887 }
2888
2889 @Override
2890 public void onParoleStateChanged(boolean isParoleOn) {
2891 synchronized (mRulesLock) {
2892 updateRulesForAppIdleParoleLocked();
2893 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002894 }
2895 }
2896
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002897 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
2898 if (listener != null) {
2899 try {
2900 listener.onUidRulesChanged(uid, uidRules);
2901 } catch (RemoteException ignored) {
2902 }
2903 }
2904 }
2905
2906 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
2907 String[] meteredIfaces) {
2908 if (listener != null) {
2909 try {
2910 listener.onMeteredIfacesChanged(meteredIfaces);
2911 } catch (RemoteException ignored) {
2912 }
2913 }
2914 }
2915
2916 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
2917 boolean restrictBackground) {
2918 if (listener != null) {
2919 try {
2920 listener.onRestrictBackgroundChanged(restrictBackground);
2921 } catch (RemoteException ignored) {
2922 }
2923 }
2924 }
2925
2926 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
2927 int uid, boolean whitelisted) {
2928 if (listener != null) {
2929 try {
2930 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
2931 } catch (RemoteException ignored) {
2932 }
2933 }
2934 }
2935
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002936 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002937 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002938 public boolean handleMessage(Message msg) {
2939 switch (msg.what) {
2940 case MSG_RULES_CHANGED: {
2941 final int uid = msg.arg1;
2942 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002943 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002944 final int length = mListeners.beginBroadcast();
2945 for (int i = 0; i < length; i++) {
2946 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002947 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002948 }
2949 mListeners.finishBroadcast();
2950 return true;
2951 }
2952 case MSG_METERED_IFACES_CHANGED: {
2953 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002954 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002955 final int length = mListeners.beginBroadcast();
2956 for (int i = 0; i < length; i++) {
2957 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002958 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002959 }
2960 mListeners.finishBroadcast();
2961 return true;
2962 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002963 case MSG_LIMIT_REACHED: {
2964 final String iface = (String) msg.obj;
2965
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002966 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002967 synchronized (mRulesLock) {
2968 if (mMeteredIfaces.contains(iface)) {
2969 try {
2970 // force stats update to make sure we have
2971 // numbers that caused alert to trigger.
2972 mNetworkStats.forceUpdate();
2973 } catch (RemoteException e) {
2974 // ignored; service lives in system_server
2975 }
2976
2977 updateNetworkEnabledLocked();
2978 updateNotificationsLocked();
2979 }
2980 }
2981 return true;
2982 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002983 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2984 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002985 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002986 final int length = mListeners.beginBroadcast();
2987 for (int i = 0; i < length; i++) {
2988 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002989 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002990 }
2991 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002992 final Intent intent =
2993 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2994 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2995 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
2996 return true;
2997 }
2998 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07002999 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3000 // - when an app is whitelisted
3001 // - when an app is blacklisted
3002 //
3003 // Whether the internal listeners (INetworkPolicyListener implementations) or
3004 // app broadcast receivers are notified depend on the following rules:
3005 //
3006 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3007 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3008 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003009 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003010 final boolean changed = msg.arg2 == 1;
3011 final Boolean whitelisted = (Boolean) msg.obj;
3012
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003013 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003014 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003015 final boolean whitelistedBool = whitelisted.booleanValue();
3016 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3017 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003018 final int length = mListeners.beginBroadcast();
3019 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003020 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003021 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3022 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003023 }
3024 mListeners.finishBroadcast();
3025 }
3026
Felipe Leme9778f762016-01-27 14:46:39 -08003027 final PackageManager pm = mContext.getPackageManager();
3028 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003029 if (changed && packages != null) {
3030 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003031 final int userId = UserHandle.getUserId(uid);
3032 for (String packageName : packages) {
3033 final Intent intent = new Intent(
3034 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3035 intent.setPackage(packageName);
3036 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3037 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3038 }
Felipe Leme9778f762016-01-27 14:46:39 -08003039 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003040 return true;
3041 }
3042 case MSG_ADVISE_PERSIST_THRESHOLD: {
3043 final long lowestRule = (Long) msg.obj;
3044 try {
3045 // make sure stats are recorded frequently enough; we aim
3046 // for 2MB threshold for 2GB/month rules.
3047 final long persistThreshold = lowestRule / 1000;
3048 mNetworkStats.advisePersistThreshold(persistThreshold);
3049 } catch (RemoteException e) {
3050 // ignored; service lives in system_server
3051 }
3052 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003053 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003054 case MSG_SCREEN_ON_CHANGED: {
3055 updateScreenOn();
3056 return true;
3057 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003058 case MSG_UPDATE_INTERFACE_QUOTA: {
3059 removeInterfaceQuota((String) msg.obj);
3060 // int params need to be stitched back into a long
3061 setInterfaceQuota((String) msg.obj,
3062 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3063 return true;
3064 }
3065 case MSG_REMOVE_INTERFACE_QUOTA: {
3066 removeInterfaceQuota((String) msg.obj);
3067 return true;
3068 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003069 default: {
3070 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003071 }
3072 }
3073 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003074 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003075
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003076 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003077 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003078 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003079 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003080 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003081 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003082 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003083 }
3084 }
3085
3086 private void removeInterfaceQuota(String iface) {
3087 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003088 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003089 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003090 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003091 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003092 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003093 }
3094 }
3095
Felipe Leme70c57c22016-03-29 10:45:13 -07003096 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3097 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003098 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003099 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003100 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003101 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3102 } catch (RemoteException e) {
3103 // ignored; service lives in system_server
3104 }
3105 }
3106
3107 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3108 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3109 try {
3110 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3111 } catch (IllegalStateException e) {
3112 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003113 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003114 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003115 }
3116 }
3117
Amith Yamasani15e472352015-04-24 19:06:07 -07003118 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003119 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3120 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3121 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003122 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003123 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003124 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003125 int size = uidRules.size();
3126 int[] uids = new int[size];
3127 int[] rules = new int[size];
3128 for(int index = size - 1; index >= 0; --index) {
3129 uids[index] = uidRules.keyAt(index);
3130 rules[index] = uidRules.valueAt(index);
3131 }
3132 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003133 } catch (IllegalStateException e) {
3134 Log.wtf(TAG, "problem setting firewall uid rules", e);
3135 } catch (RemoteException e) {
3136 // ignored; service lives in system_server
3137 }
3138 }
3139
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003140 /**
3141 * Add or remove a uid to the firewall blacklist for all network ifaces.
3142 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003143 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003144 if (chain == FIREWALL_CHAIN_DOZABLE) {
3145 mUidFirewallDozableRules.put(uid, rule);
3146 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3147 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003148 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3149 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003150 }
3151
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003152 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003153 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003154 } catch (IllegalStateException e) {
3155 Log.wtf(TAG, "problem setting firewall uid rules", e);
3156 } catch (RemoteException e) {
3157 // ignored; service lives in system_server
3158 }
3159 }
3160
3161 /**
3162 * Add or remove a uid to the firewall blacklist for all network ifaces.
3163 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003164 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003165 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3166 mFirewallChainStates.get(chain) == enable) {
3167 // All is the same, nothing to do.
3168 return;
3169 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003170 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003171 try {
3172 mNetworkManager.setFirewallChainEnabled(chain, enable);
3173 } catch (IllegalStateException e) {
3174 Log.wtf(TAG, "problem enable firewall chain", e);
3175 } catch (RemoteException e) {
3176 // ignored; service lives in system_server
3177 }
3178 }
3179
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003180 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3181 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003182 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003183 } catch (RuntimeException e) {
3184 Slog.w(TAG, "problem reading network stats: " + e);
3185 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003186 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003187 // ignored; service lives in system_server
3188 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003189 }
3190 }
3191
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003192 private boolean isBandwidthControlEnabled() {
3193 final long token = Binder.clearCallingIdentity();
3194 try {
3195 return mNetworkManager.isBandwidthControlEnabled();
3196 } catch (RemoteException e) {
3197 // ignored; service lives in system_server
3198 return false;
3199 } finally {
3200 Binder.restoreCallingIdentity(token);
3201 }
3202 }
3203
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003204 /**
3205 * Try refreshing {@link #mTime} when stale.
3206 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003207 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003208 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003209 mTime.forceRefresh();
3210 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003211 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003212
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003213 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003214 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3215 }
3216
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003217 private static Intent buildAllowBackgroundDataIntent() {
3218 return new Intent(ACTION_ALLOW_BACKGROUND);
3219 }
3220
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003221 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3222 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3223 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3224 return intent;
3225 }
3226
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003227 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3228 final Intent intent = new Intent();
3229 intent.setComponent(new ComponentName(
3230 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3231 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3232 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3233 return intent;
3234 }
3235
3236 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3237 final Intent intent = new Intent();
3238 intent.setComponent(new ComponentName(
3239 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3240 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3241 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3242 return intent;
3243 }
3244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003245 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003246 public void addIdleHandler(IdleHandler handler) {
3247 mHandler.getLooper().getQueue().addIdleHandler(handler);
3248 }
3249
Jeff Sharkey1b861272011-05-22 00:34:52 -07003250 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3251 final int size = source.size();
3252 for (int i = 0; i < size; i++) {
3253 target.put(source.keyAt(i), true);
3254 }
3255 }
3256
Stuart Scottf1fb3972015-04-02 18:00:02 -07003257 @Override
3258 public void factoryReset(String subscriber) {
3259 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3260
Stuart Scotte3e314d2015-04-20 14:07:45 -07003261 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3262 return;
3263 }
3264
Stuart Scottf1fb3972015-04-02 18:00:02 -07003265 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003266 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003267 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3268 for (NetworkPolicy policy : policies) {
3269 if (policy.template.equals(template)) {
3270 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3271 policy.inferred = false;
3272 policy.clearSnooze();
3273 }
3274 }
3275 setNetworkPolicies(policies);
3276
3277 // Turn restrict background data off
3278 setRestrictBackground(false);
3279
Stuart Scotte3e314d2015-04-20 14:07:45 -07003280 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3281 // Remove app's "restrict background data" flag
3282 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3283 setUidPolicy(uid, POLICY_NONE);
3284 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003285 }
3286 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003287
3288 private class MyPackageMonitor extends PackageMonitor {
3289
3290 @Override
3291 public void onPackageRemoved(String packageName, int uid) {
3292 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3293 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003294 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003295 }
3296 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003297 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003298}