blob: 6a267ca689516c7f9b9fa2983a11221081a5321d [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 Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
128import android.net.wifi.WifiInfo;
129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700141import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700142import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600143import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700145import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700146import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700147import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800148import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700149import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700150import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700151import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700152import android.util.ArrayMap;
153import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700154import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700155import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700156import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700158import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700159import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700160import android.util.SparseBooleanArray;
161import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700162import android.util.TrustedTime;
163import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700164
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800166import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800167import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800168import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700169import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700170import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700171import com.android.server.DeviceIdleController;
172import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700173import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800174import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600175
176import libcore.io.IoUtils;
177
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179
180import org.xmlpull.v1.XmlPullParser;
181import org.xmlpull.v1.XmlPullParserException;
182import org.xmlpull.v1.XmlSerializer;
183
184import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700185import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import java.io.FileInputStream;
187import java.io.FileNotFoundException;
188import java.io.FileOutputStream;
189import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700190import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700191import java.lang.annotation.Retention;
192import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100193import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194import java.util.ArrayList;
195import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700196import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700198/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700199 * Service that maintains low-level network policy rules, using
200 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201 * <p>
202 * Derives active rules by combining a given policy with other system status,
203 * and delivers to listeners, such as {@link ConnectivityManager}, for
204 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700205 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700206public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800207 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700208 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700209 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700211 private static final int VERSION_INIT = 1;
212 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700213 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800214 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800215 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800216 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700217 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700218 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700219 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700220 private static final int VERSION_SWITCH_UID = 10;
221 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800223 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700224 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800225 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700226 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800227 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700228 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700229
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700230 private static final String TAG_POLICY_LIST = "policy-list";
231 private static final String TAG_NETWORK_POLICY = "network-policy";
232 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700233 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800234 private static final String TAG_WHITELIST = "whitelist";
235 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800236 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237
238 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700239 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
241 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700242 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800244 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245 private static final String ATTR_WARNING_BYTES = "warningBytes";
246 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700247 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800248 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
249 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800250 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700251 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700252 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700253 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254 private static final String ATTR_POLICY = "policy";
255
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800256 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800257 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800258 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800259 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700260
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
262
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700263 private static final int MSG_RULES_CHANGED = 1;
264 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800265 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800266 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700267 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700268 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800269 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700270 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
271 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700272 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700273
Jeff Sharkey75279902011-05-24 18:39:45 -0700274 private final Context mContext;
275 private final IActivityManager mActivityManager;
276 private final IPowerManager mPowerManager;
277 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700278 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700279 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700281 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282
283 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700284 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700285 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700286 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700287
Dianne Hackborn497175b2014-07-01 12:56:08 -0700288 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700289
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700290 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700291 volatile boolean mScreenOn;
292 volatile boolean mRestrictBackground;
293 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700294 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700295
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700296 private final boolean mSuppressDefaultPolicy;
297
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700298 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800299 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800301 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700302
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700303 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700304 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700305 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800306 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700307
Jeff Sharkeydc988062015-09-14 10:09:47 -0700308 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
309 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800310 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700311
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700312 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700313 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
314
Jeff Sharkey32566012014-12-02 18:30:14 -0800315 /**
316 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700317 * in power save mode, except device idle (doze) still applies.
318 * TODO: An int array might be sufficient
319 */
320 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
321
322 /**
323 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800324 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700325 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800326 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700327 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700328
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700329 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
330
Felipe Lemeb85a6372016-01-14 16:16:16 -0800331 /**
332 * UIDs that have been white-listed to avoid restricted background.
333 */
334 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
335
Felipe Lemea9505cc2016-02-26 10:28:41 -0800336 /**
337 * UIDs that have been initially white-listed by system to avoid restricted background.
338 */
339 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
340 new SparseBooleanArray();
341
342 /**
343 * UIDs that have been initially white-listed by system to avoid restricted background,
344 * but later revoked by user.
345 */
346 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
347 new SparseBooleanArray();
348
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700349 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800350 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700351 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700353
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700354 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700355 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700356
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700357 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800358 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700359
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600360 /** Higher priority listener before general event dispatch */
361 private INetworkPolicyListener mConnectivityListener;
362
Jeff Sharkey32566012014-12-02 18:30:14 -0800363 private final RemoteCallbackList<INetworkPolicyListener>
364 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700365
Dianne Hackborn497175b2014-07-01 12:56:08 -0700366 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700367
368 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700369
Svet Ganov16a16892015-04-16 10:32:04 -0700370 private final AppOpsManager mAppOps;
371
Felipe Lemeb85a6372016-01-14 16:16:16 -0800372 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800373 private final IPackageManager mIPm;
374
Felipe Lemeb85a6372016-01-14 16:16:16 -0800375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700376 // TODO: keep whitelist of system-critical services that should never have
377 // rules enforced, such as system, phone, and radio UIDs.
378
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700379 // TODO: migrate notifications to SystemUI
380
Jeff Sharkey75279902011-05-24 18:39:45 -0700381 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700382 IPowerManager powerManager, INetworkStatsService networkStats,
383 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700384 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700385 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700386 }
387
388 private static File getSystemDir() {
389 return new File(Environment.getDataDirectory(), "system");
390 }
391
392 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700393 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700394 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
395 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700396 mContext = checkNotNull(context, "missing context");
397 mActivityManager = checkNotNull(activityManager, "missing activityManager");
398 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700399 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700400 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700401 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700402 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700404 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800405 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700406
Amith Yamasani450a16b2013-09-18 16:28:50 -0700407 HandlerThread thread = new HandlerThread(TAG);
408 thread.start();
409 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700410
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700411 mSuppressDefaultPolicy = suppressDefaultPolicy;
412
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700413 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700414
415 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800416
417 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700418
419 // Expose private service for system components to use.
420 LocalServices.addService(NetworkPolicyManagerInternal.class,
421 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700422 }
423
424 public void bindConnectivityManager(IConnectivityManager connManager) {
425 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700426 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700427
Jeff Sharkey497e4432011-06-14 17:27:29 -0700428 public void bindNotificationManager(INotificationManager notifManager) {
429 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
430 }
431
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700432 void updatePowerSaveWhitelistLocked() {
433 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700434 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
435 mPowerSaveWhitelistExceptIdleAppIds.clear();
436 if (whitelist != null) {
437 for (int uid : whitelist) {
438 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
439 }
440 }
441 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700442 mPowerSaveWhitelistAppIds.clear();
443 if (whitelist != null) {
444 for (int uid : whitelist) {
445 mPowerSaveWhitelistAppIds.put(uid, true);
446 }
447 }
448 } catch (RemoteException e) {
449 }
450 }
451
Felipe Lemea9505cc2016-02-26 10:28:41 -0800452 /**
453 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
454 * revoke the whitelist.
455 *
456 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
457 */
Felipe Lemea110eec2016-04-29 09:58:06 -0700458 boolean addDefaultRestrictBackgroundWhitelistUidsLocked() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800459 final List<UserInfo> users = mUserManager.getUsers();
460 final int numberUsers = users.size();
461
Felipe Lemea110eec2016-04-29 09:58:06 -0700462 boolean changed = false;
463 for (int i = 0; i < numberUsers; i++) {
464 final UserInfo user = users.get(i);
465 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(user.id) || changed;
466 }
467 return changed;
468 }
469
470 private boolean addDefaultRestrictBackgroundWhitelistUidsLocked(int userId) {
471 final SystemConfig sysConfig = SystemConfig.getInstance();
472 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800473 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
474 boolean changed = false;
475 for (int i = 0; i < allowDataUsage.size(); i++) {
476 final String pkg = allowDataUsage.valueAt(i);
477 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700478 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
479 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800480 final ApplicationInfo app;
481 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700482 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800483 } catch (PackageManager.NameNotFoundException e) {
484 // Should not happen
485 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
486 continue;
487 }
488 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700489 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800490 continue;
491 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700492 final int uid = UserHandle.getUid(userId, app.uid);
493 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
494 if (LOGD)
495 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
496 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800497 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700498 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
499 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
500 + userId + ") to restrict background whitelist");
501 mRestrictBackgroundWhitelistUids.append(uid, true);
502 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800503 }
504 }
505 return changed;
506 }
507
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700508 void updatePowerSaveTempWhitelistLocked() {
509 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700510 // Clear the states of the current whitelist
511 final int N = mPowerSaveTempWhitelistAppIds.size();
512 for (int i = 0; i < N; i++) {
513 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
514 }
515 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700516 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700517 if (whitelist != null) {
518 for (int uid : whitelist) {
519 mPowerSaveTempWhitelistAppIds.put(uid, true);
520 }
521 }
522 } catch (RemoteException e) {
523 }
524 }
525
Amith Yamasani06f08062015-06-12 13:23:33 -0700526 /**
527 * Remove unnecessary entries in the temp whitelist
528 */
529 void purgePowerSaveTempWhitelistLocked() {
530 final int N = mPowerSaveTempWhitelistAppIds.size();
531 for (int i = N - 1; i >= 0; i--) {
532 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
533 mPowerSaveTempWhitelistAppIds.removeAt(i);
534 }
535 }
536 }
537
Jeff Sharkeya4620792011-05-20 15:29:23 -0700538 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700539 if (!isBandwidthControlEnabled()) {
540 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
541 return;
542 }
543
Amith Yamasani15e472352015-04-24 19:06:07 -0700544 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
545
Felipe Lemeb85a6372016-01-14 16:16:16 -0800546 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
547
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700548 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700549 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700550 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
551 mPowerManagerInternal.registerLowPowerModeObserver(
552 new PowerManagerInternal.LowPowerModeListener() {
553 @Override
554 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800555 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700556 synchronized (mRulesLock) {
557 if (mRestrictPower != enabled) {
558 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800559 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700560 }
561 }
562 }
563 });
564 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Felipe Lemed31a97f2016-05-06 14:53:50 -0700565
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700566 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700567
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700568 // read policy from disk
569 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700570
Felipe Lemea110eec2016-04-29 09:58:06 -0700571 if (addDefaultRestrictBackgroundWhitelistUidsLocked()) {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800572 writePolicyLocked();
573 }
574
Felipe Lemef3e40642016-06-07 17:28:08 -0700575 setRestrictBackgroundLocked(mRestrictBackground);
Jeff Sharkeydc988062015-09-14 10:09:47 -0700576 updateRulesForGlobalChangeLocked(false);
577 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700578 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700579
Jeff Sharkeya4620792011-05-20 15:29:23 -0700580 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700581
Jeff Sharkeya4620792011-05-20 15:29:23 -0700582 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700583 mActivityManager.registerUidObserver(mUidObserver,
584 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700585 mNetworkManager.registerObserver(mAlertObserver);
586 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700587 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700588 }
589
Jeff Sharkeya4620792011-05-20 15:29:23 -0700590 // TODO: traverse existing processes to know foreground state, or have
591 // activitymanager dispatch current state when new observer attached.
592
593 final IntentFilter screenFilter = new IntentFilter();
594 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
595 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700596 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700597
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700598 // listen for changes to power save whitelist
599 final IntentFilter whitelistFilter = new IntentFilter(
600 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
601 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
602
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700603 DeviceIdleController.LocalService deviceIdleService
604 = LocalServices.getService(DeviceIdleController.LocalService.class);
605 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
606
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700607 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900608 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700609 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
610
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700611 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700612 final IntentFilter packageFilter = new IntentFilter();
613 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700614 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700615 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700616
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700617 // listen for UID changes to update policy
618 mContext.registerReceiver(
619 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
620
621 // listen for user changes to update policy
622 final IntentFilter userFilter = new IntentFilter();
623 userFilter.addAction(ACTION_USER_ADDED);
624 userFilter.addAction(ACTION_USER_REMOVED);
625 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
626
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700627 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700628 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
629 mContext.registerReceiver(
630 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
631
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700632 // listen for restrict background changes from notifications
633 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
634 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
635
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800636 // listen for snooze warning from notifications
637 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
638 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
639 MANAGE_NETWORK_POLICY, mHandler);
640
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700641 // listen for configured wifi networks to be removed
642 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700643 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700644
645 // listen for wifi state changes to catch metered hint
646 final IntentFilter wifiStateFilter = new IntentFilter(
647 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700648 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700649
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700650 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700651
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700652 }
653
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700654 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700655 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700656 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700657 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700658 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700659 }
660
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700661 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700662 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700663 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700664 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700665 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700666
667 @Override public void onUidActive(int uid) throws RemoteException {
668 }
669
670 @Override public void onUidIdle(int uid) throws RemoteException {
671 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700672 };
673
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700674 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700675 @Override
676 public void onReceive(Context context, Intent intent) {
677 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
678 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700679 updatePowerSaveWhitelistLocked();
Felipe Lemef3e40642016-06-07 17:28:08 -0700680 updateRulesForRestrictPowerLocked();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700681 }
682 }
683 };
684
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700685 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
686 @Override
687 public void run() {
688 synchronized (mRulesLock) {
689 updatePowerSaveTempWhitelistLocked();
690 updateRulesForTempWhitelistChangeLocked();
691 purgePowerSaveTempWhitelistLocked();
692 }
693 }
694 };
695
696 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700697 @Override
698 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800699 // screen-related broadcasts are protected by system, no need
700 // for permissions check.
701 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700702 }
703 };
704
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700705 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700706 @Override
707 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700708 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700709
710 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700711 final int uid = intent.getIntExtra(EXTRA_UID, -1);
712 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700713
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700714 if (ACTION_PACKAGE_ADDED.equals(action)) {
715 // update rules for UID, since it might be subject to
716 // global background data policy
717 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
718 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700719 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700720 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700721 }
722 }
723 };
724
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700725 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700726 @Override
727 public void onReceive(Context context, Intent intent) {
728 // on background handler thread, and UID_REMOVED is protected
729
730 final int uid = intent.getIntExtra(EXTRA_UID, -1);
731 if (uid == -1) return;
732
733 // remove any policy and update rules to clean up
734 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
735 synchronized (mRulesLock) {
736 mUidPolicy.delete(uid);
Felipe Leme781ba142016-05-09 16:24:48 -0700737 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700738 writePolicyLocked();
739 }
740 }
741 };
742
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700743 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700744 @Override
745 public void onReceive(Context context, Intent intent) {
746 // on background handler thread, and USER_ADDED and USER_REMOVED
747 // broadcasts are protected
748
749 final String action = intent.getAction();
750 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
751 if (userId == -1) return;
752
Amith Yamasani15e472352015-04-24 19:06:07 -0700753 switch (action) {
754 case ACTION_USER_REMOVED:
755 case ACTION_USER_ADDED:
756 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800757 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700758 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemed17fda42016-04-29 11:12:45 -0700759 removeUserStateLocked(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700760 if (action == ACTION_USER_ADDED) {
761 // Add apps that are whitelisted by default.
762 addDefaultRestrictBackgroundWhitelistUidsLocked(userId);
763 }
764 // Update global restrict for that user
Amith Yamasani15e472352015-04-24 19:06:07 -0700765 updateRulesForGlobalChangeLocked(true);
766 }
767 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700768 }
769 }
770 };
771
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700772 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 * Receiver that watches for {@link INetworkStatsService} updates, which we
774 * use to check against {@link NetworkPolicy#warningBytes}.
775 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700776 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700777 @Override
778 public void onReceive(Context context, Intent intent) {
779 // on background handler thread, and verified
780 // READ_NETWORK_USAGE_HISTORY permission above.
781
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800782 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700783 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700784 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700785 updateNotificationsLocked();
786 }
787 }
788 };
789
790 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700791 * Receiver that watches for {@link Notification} control of
792 * {@link #mRestrictBackground}.
793 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700794 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700795 @Override
796 public void onReceive(Context context, Intent intent) {
797 // on background handler thread, and verified MANAGE_NETWORK_POLICY
798 // permission above.
799
800 setRestrictBackground(false);
801 }
802 };
803
804 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800805 * Receiver that watches for {@link Notification} control of
806 * {@link NetworkPolicy#lastWarningSnooze}.
807 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700808 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800809 @Override
810 public void onReceive(Context context, Intent intent) {
811 // on background handler thread, and verified MANAGE_NETWORK_POLICY
812 // permission above.
813
814 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
815 performSnooze(template, TYPE_WARNING);
816 }
817 };
818
819 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700820 * Receiver that watches for {@link WifiConfiguration} to be changed.
821 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700822 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700823 @Override
824 public void onReceive(Context context, Intent intent) {
825 // on background handler thread, and verified CONNECTIVITY_INTERNAL
826 // permission above.
827
828 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
829 if (reason == CHANGE_REASON_REMOVED) {
830 final WifiConfiguration config = intent.getParcelableExtra(
831 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700832 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800833 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700834 synchronized (mRulesLock) {
835 if (mNetworkPolicy.containsKey(template)) {
836 mNetworkPolicy.remove(template);
837 writePolicyLocked();
838 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700839 }
840 }
841 }
842 }
843 };
844
845 /**
846 * Receiver that watches {@link WifiInfo} state changes to infer metered
847 * state. Ignores hints when policy is user-defined.
848 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700849 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700850 @Override
851 public void onReceive(Context context, Intent intent) {
852 // on background handler thread, and verified CONNECTIVITY_INTERNAL
853 // permission above.
854
855 // ignore when not connected
856 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
857 if (!netInfo.isConnected()) return;
858
859 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
860 final boolean meteredHint = info.getMeteredHint();
861
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800862 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700863 synchronized (mRulesLock) {
864 NetworkPolicy policy = mNetworkPolicy.get(template);
865 if (policy == null && meteredHint) {
866 // policy doesn't exist, and AP is hinting that it's
867 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800868 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700869 addNetworkPolicyLocked(policy);
870
871 } else if (policy != null && policy.inferred) {
872 // policy exists, and was inferred: update its current
873 // metered state.
874 policy.metered = meteredHint;
875
876 // since this is inferred for each wifi session, just update
877 // rules without persisting.
878 updateNetworkRulesLocked();
879 }
880 }
881 }
882 };
883
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800884 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
885 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
886 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
887 metered, true);
888 }
889
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700890 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700891 * Observer that watches for {@link INetworkManagementService} alerts.
892 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700893 final private INetworkManagementEventObserver mAlertObserver
894 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700895 @Override
896 public void limitReached(String limitName, String iface) {
897 // only someone like NMS should be calling us
898 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
899
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800900 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
901 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700902 }
903 }
904 };
905
906 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700907 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
908 * to show visible notifications as needed.
909 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700910 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700911 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
912
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700913 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700914 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700915 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700916
917 // TODO: when switching to kernel notifications, compute next future
918 // cycle boundary to recompute notifications.
919
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700920 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800921 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700922 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
923 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700924 // ignore policies that aren't relevant to user
925 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700926 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700927
Jeff Sharkey497e4432011-06-14 17:27:29 -0700928 final long start = computeLastCycleBoundary(currentTime, policy);
929 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700930 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700931
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700932 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800933 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700934 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
935 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700936 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
937 notifyOverLimitLocked(policy.template);
938 }
939
Jeff Sharkey497e4432011-06-14 17:27:29 -0700940 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700941 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700942
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800943 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700944 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700945 }
946 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700947 }
948
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700950 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
951 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 if (!mActiveNotifs.contains(tag)) {
953 cancelNotification(tag);
954 }
955 }
956 }
957
958 /**
959 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700960 * current device state, such as when
961 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
962 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700963 */
964 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800965 if (template.isMatchRuleMobile()) {
966 final TelephonyManager tele = TelephonyManager.from(mContext);
967 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700968
Jeff Sharkey32566012014-12-02 18:30:14 -0800969 // Mobile template is relevant when any active subscriber matches
970 final int[] subIds = sub.getActiveSubscriptionIdList();
971 for (int subId : subIds) {
972 final String subscriberId = tele.getSubscriberId(subId);
973 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700974 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800975 if (template.matches(probeIdent)) {
976 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700977 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800978 }
979 return false;
980 } else {
981 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700982 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700983 }
984
985 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 * Notify that given {@link NetworkTemplate} is over
987 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
988 */
989 private void notifyOverLimitLocked(NetworkTemplate template) {
990 if (!mOverLimitNotified.contains(template)) {
991 mContext.startActivity(buildNetworkOverLimitIntent(template));
992 mOverLimitNotified.add(template);
993 }
994 }
995
996 private void notifyUnderLimitLocked(NetworkTemplate template) {
997 mOverLimitNotified.remove(template);
998 }
999
1000 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001 * Build unique tag that identifies an active {@link NetworkPolicy}
1002 * notification of a specific type, like {@link #TYPE_LIMIT}.
1003 */
1004 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001005 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006 }
1007
1008 /**
1009 * Show notification for combined {@link NetworkPolicy} and specific type,
1010 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1011 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001012 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001013 final String tag = buildNotificationTag(policy, type);
1014 final Notification.Builder builder = new Notification.Builder(mContext);
1015 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001016 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001017 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001018 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001019
1020 final Resources res = mContext.getResources();
1021 switch (type) {
1022 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001023 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001024 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001026 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001027 builder.setTicker(title);
1028 builder.setContentTitle(title);
1029 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001030
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001031 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1032 builder.setDeleteIntent(PendingIntent.getBroadcast(
1033 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1034
1035 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001036 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001037 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1038
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 break;
1040 }
1041 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1043
1044 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001045 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001046 switch (policy.template.getMatchRule()) {
1047 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001050 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001051 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001052 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001053 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001054 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001056 case MATCH_WIFI:
1057 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001058 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001059 break;
1060 default:
1061 title = null;
1062 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063 }
1064
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001065 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001066 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001067 builder.setTicker(title);
1068 builder.setContentTitle(title);
1069 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001070
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1072 builder.setContentIntent(PendingIntent.getActivity(
1073 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1074 break;
1075 }
1076 case TYPE_LIMIT_SNOOZED: {
1077 final long overBytes = totalBytes - policy.limitBytes;
1078 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1079 Formatter.formatFileSize(mContext, overBytes));
1080
1081 final CharSequence title;
1082 switch (policy.template.getMatchRule()) {
1083 case MATCH_MOBILE_3G_LOWER:
1084 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1085 break;
1086 case MATCH_MOBILE_4G:
1087 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1088 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001089 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001090 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1091 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092 case MATCH_WIFI:
1093 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1094 break;
1095 default:
1096 title = null;
1097 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 }
1099
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001100 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001101 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 builder.setTicker(title);
1103 builder.setContentTitle(title);
1104 builder.setContentText(body);
1105
1106 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001107 builder.setContentIntent(PendingIntent.getActivity(
1108 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001109 break;
1110 }
1111 }
1112
1113 // TODO: move to NotificationManager once we can mock it
1114 try {
1115 final String packageName = mContext.getPackageName();
1116 final int[] idReceived = new int[1];
1117 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001118 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001119 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001120 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001121 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001122 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001123 }
1124 }
1125
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001126 private void cancelNotification(String tag) {
1127 // TODO: move to NotificationManager once we can mock it
1128 try {
1129 final String packageName = mContext.getPackageName();
1130 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001131 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001133 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 }
1135 }
1136
1137 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001139 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001140 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001141 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001142 @Override
1143 public void onReceive(Context context, Intent intent) {
1144 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1145 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001146
1147 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001148 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001149 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001150 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001152 updateNetworkRulesLocked();
1153 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001154 }
1155 }
1156 };
1157
1158 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159 * Proactively control network data connections when they exceed
1160 * {@link NetworkPolicy#limitBytes}.
1161 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001162 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1164
1165 // TODO: reset any policy-disabled networks when any policy is removed
1166 // completely, which is currently rare case.
1167
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001168 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001169 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1170 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001171 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001172 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001173 setNetworkTemplateEnabled(policy.template, true);
1174 continue;
1175 }
1176
1177 final long start = computeLastCycleBoundary(currentTime, policy);
1178 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001179 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001180
1181 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001182 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1183 && policy.lastLimitSnooze < start;
1184 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001185
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001186 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001187 }
1188 }
1189
1190 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001191 * Proactively disable networks that match the given
1192 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001193 */
1194 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001195 // TODO: reach into ConnectivityManager to proactively disable bringing
1196 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001197 }
1198
1199 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001200 * Examine all connected {@link NetworkState}, looking for
1201 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1202 * remaining quota based on usage cycle and historical stats.
1203 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001204 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001205 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001206
1207 final NetworkState[] states;
1208 try {
1209 states = mConnManager.getAllNetworkState();
1210 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001211 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 return;
1213 }
1214
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001215 // First, generate identities of all connected networks so we can
1216 // quickly compare them against all defined policies below.
1217 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001218 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001220 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001221 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001222
1223 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001224 if (baseIface != null) {
1225 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001226 }
1227
1228 // Stacked interfaces are considered to have same identity as
1229 // their parent network.
1230 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1231 for (LinkProperties stackedLink : stackedLinks) {
1232 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001233 if (stackedIface != null) {
1234 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001235 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001236 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237 }
1238 }
1239
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001240 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001241 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001242 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001243 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001244 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001245
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001246 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001247 for (int j = connIdents.size() - 1; j >= 0; j--) {
1248 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1249 if (policy.template.matches(ident.second)) {
1250 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251 }
1252 }
1253
1254 if (ifaceList.size() > 0) {
1255 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001256 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 }
1258 }
1259
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001260 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001261 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001262
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001263 // apply each policy that we found ifaces for; compute remaining data
1264 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001265 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001266 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1267 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1268 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001269
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001270 final long start;
1271 final long totalBytes;
1272 if (policy.hasCycle()) {
1273 start = computeLastCycleBoundary(currentTime, policy);
1274 totalBytes = getTotalBytes(policy.template, start, currentTime);
1275 } else {
1276 start = Long.MAX_VALUE;
1277 totalBytes = 0;
1278 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001279
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001280 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001281 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001282 }
1283
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001284 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001285 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001286 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001287 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001288 if (!hasLimit) {
1289 // metered network, but no policy limit; we still need to
1290 // restrict apps, so push really high quota.
1291 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001292 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001293 // snoozing past quota, but we still need to restrict apps,
1294 // so push really high quota.
1295 quotaBytes = Long.MAX_VALUE;
1296 } else {
1297 // remaining "quota" bytes are based on total usage in
1298 // current cycle. kernel doesn't like 0-byte rules, so we
1299 // set 1-byte quota and disable the radio later.
1300 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1301 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001302
1303 if (ifaces.length > 1) {
1304 // TODO: switch to shared quota once NMS supports
1305 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001306 }
1307
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001308 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001309 // long quotaBytes split up into two ints to fit in message
1310 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1311 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1312 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001313 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001314 }
1315 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001316
1317 // keep track of lowest warning or limit of active policies
1318 if (hasWarning && policy.warningBytes < lowestRule) {
1319 lowestRule = policy.warningBytes;
1320 }
1321 if (hasLimit && policy.limitBytes < lowestRule) {
1322 lowestRule = policy.limitBytes;
1323 }
1324 }
1325
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001326 for (int i = connIfaces.size()-1; i >= 0; i--) {
1327 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001328 // long quotaBytes split up into two ints to fit in message
1329 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1330 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1331 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001332 newMeteredIfaces.add(iface);
1333 }
1334
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001335 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001336
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001337 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001338 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1339 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001340 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001341 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1342 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001343 }
1344 }
1345 mMeteredIfaces = newMeteredIfaces;
1346
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001347 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001348 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001349 }
1350
1351 /**
1352 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1353 * have at least a default mobile policy defined.
1354 */
1355 private void ensureActiveMobilePolicyLocked() {
1356 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001357 if (mSuppressDefaultPolicy) return;
1358
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001359 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001360 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001361
Jeff Sharkey32566012014-12-02 18:30:14 -08001362 final int[] subIds = sub.getActiveSubscriptionIdList();
1363 for (int subId : subIds) {
1364 final String subscriberId = tele.getSubscriberId(subId);
1365 ensureActiveMobilePolicyLocked(subscriberId);
1366 }
1367 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001368
Jeff Sharkey32566012014-12-02 18:30:14 -08001369 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1370 // Poke around to see if we already have a policy
1371 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001372 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001373 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1374 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1375 if (template.matches(probeIdent)) {
1376 if (LOGD) {
1377 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1378 + NetworkIdentity.scrubSubscriberId(subscriberId));
1379 }
1380 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001381 }
1382 }
1383
Jeff Sharkey32566012014-12-02 18:30:14 -08001384 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1385 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001386
Jeff Sharkey32566012014-12-02 18:30:14 -08001387 // Build default mobile policy, and assume usage cycle starts today
1388 final long warningBytes = mContext.getResources().getInteger(
1389 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001390
Jeff Sharkey32566012014-12-02 18:30:14 -08001391 final Time time = new Time();
1392 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001393
Jeff Sharkey32566012014-12-02 18:30:14 -08001394 final int cycleDay = time.monthDay;
1395 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001396
Jeff Sharkey32566012014-12-02 18:30:14 -08001397 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1398 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1399 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1400 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001401 }
1402
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001403 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001404 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405
1406 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001407 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001408 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001409
1410 FileInputStream fis = null;
1411 try {
1412 fis = mPolicyFile.openRead();
1413 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001414 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001415
1416 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001417 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001418 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001419 while ((type = in.next()) != END_DOCUMENT) {
1420 final String tag = in.getName();
1421 if (type == START_TAG) {
1422 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001423 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001425 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1426 mRestrictBackground = readBooleanAttribute(
1427 in, ATTR_RESTRICT_BACKGROUND);
1428 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001429 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001430 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001431 if (mRestrictBackground != oldValue) {
1432 // Some early services may have read the default value,
1433 // so notify them that it's changed
1434 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1435 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1436 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437
1438 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1439 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1440 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001441 final String networkId;
1442 if (version >= VERSION_ADDED_NETWORK_ID) {
1443 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1444 } else {
1445 networkId = null;
1446 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001447 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001448 final String cycleTimezone;
1449 if (version >= VERSION_ADDED_TIMEZONE) {
1450 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1451 } else {
1452 cycleTimezone = Time.TIMEZONE_UTC;
1453 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1455 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001456 final long lastLimitSnooze;
1457 if (version >= VERSION_SPLIT_SNOOZE) {
1458 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1459 } else if (version >= VERSION_ADDED_SNOOZE) {
1460 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001461 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001462 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001463 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001464 final boolean metered;
1465 if (version >= VERSION_ADDED_METERED) {
1466 metered = readBooleanAttribute(in, ATTR_METERED);
1467 } else {
1468 switch (networkTemplate) {
1469 case MATCH_MOBILE_3G_LOWER:
1470 case MATCH_MOBILE_4G:
1471 case MATCH_MOBILE_ALL:
1472 metered = true;
1473 break;
1474 default:
1475 metered = false;
1476 }
1477 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001478 final long lastWarningSnooze;
1479 if (version >= VERSION_SPLIT_SNOOZE) {
1480 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1481 } else {
1482 lastWarningSnooze = SNOOZE_NEVER;
1483 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001484 final boolean inferred;
1485 if (version >= VERSION_ADDED_INFERRED) {
1486 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1487 } else {
1488 inferred = false;
1489 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490
Jeff Sharkey32566012014-12-02 18:30:14 -08001491 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1492 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001493 if (template.isPersistable()) {
1494 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1495 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1496 lastLimitSnooze, metered, inferred));
1497 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001498
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001499 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001500 final int uid = readIntAttribute(in, ATTR_UID);
1501 final int policy = readIntAttribute(in, ATTR_POLICY);
1502
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001503 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001504 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001505 } else {
1506 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1507 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001509 final int appId = readIntAttribute(in, ATTR_APP_ID);
1510 final int policy = readIntAttribute(in, ATTR_POLICY);
1511
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001512 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001513 // app policy is deprecated so this is only used in pre system user split.
1514 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001515 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001516 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001517 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001518 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001519 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001520 } else if (TAG_WHITELIST.equals(tag)) {
1521 insideWhitelist = true;
1522 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1523 final int uid = readIntAttribute(in, ATTR_UID);
1524 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001525 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1526 final int uid = readIntAttribute(in, ATTR_UID);
1527 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001529 } else if (type == END_TAG) {
1530 if (TAG_WHITELIST.equals(tag)) {
1531 insideWhitelist = false;
1532 }
1533
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534 }
1535 }
1536
1537 } catch (FileNotFoundException e) {
1538 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001539 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001540 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001541 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001543 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 } finally {
1545 IoUtils.closeQuietly(fis);
1546 }
1547 }
1548
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001549 /**
1550 * Upgrade legacy background data flags, notifying listeners of one last
1551 * change to always-true.
1552 */
1553 private void upgradeLegacyBackgroundData() {
1554 mRestrictBackground = Settings.Secure.getInt(
1555 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1556
1557 // kick off one last broadcast if restricted
1558 if (mRestrictBackground) {
1559 final Intent broadcast = new Intent(
1560 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001561 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001562 }
1563 }
1564
Dianne Hackborn497175b2014-07-01 12:56:08 -07001565 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001566 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567
1568 FileOutputStream fos = null;
1569 try {
1570 fos = mPolicyFile.startWrite();
1571
1572 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001573 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 out.startDocument(null, true);
1575
1576 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001577 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001578 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579
1580 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001581 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1582 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001583 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001584 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001585
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001587 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1588 final String subscriberId = template.getSubscriberId();
1589 if (subscriberId != null) {
1590 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001591 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001592 final String networkId = template.getNetworkId();
1593 if (networkId != null) {
1594 out.attribute(null, ATTR_NETWORK_ID, networkId);
1595 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001596 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001597 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001598 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1599 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001600 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1601 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001602 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001603 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001604 out.endTag(null, TAG_NETWORK_POLICY);
1605 }
1606
1607 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001608 for (int i = 0; i < mUidPolicy.size(); i++) {
1609 final int uid = mUidPolicy.keyAt(i);
1610 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611
Jeff Sharkey497e4432011-06-14 17:27:29 -07001612 // skip writing empty policies
1613 if (policy == POLICY_NONE) continue;
1614
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001615 out.startTag(null, TAG_UID_POLICY);
1616 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001618 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619 }
1620
1621 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001622
1623 // write all whitelists
1624 out.startTag(null, TAG_WHITELIST);
1625
1626 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001627 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001628 for (int i = 0; i < size; i++) {
1629 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1630 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1631 writeIntAttribute(out, ATTR_UID, uid);
1632 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1633 }
1634
Felipe Lemea9505cc2016-02-26 10:28:41 -08001635 // revoked restrict background whitelist
1636 size = mRestrictBackgroundWhitelistRevokedUids.size();
1637 for (int i = 0; i < size; i++) {
1638 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1639 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1640 writeIntAttribute(out, ATTR_UID, uid);
1641 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1642 }
1643
Felipe Lemeb85a6372016-01-14 16:16:16 -08001644 out.endTag(null, TAG_WHITELIST);
1645
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001646 out.endDocument();
1647
1648 mPolicyFile.finishWrite(fos);
1649 } catch (IOException e) {
1650 if (fos != null) {
1651 mPolicyFile.failWrite(fos);
1652 }
1653 }
1654 }
1655
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001656 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001657 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001658 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001659
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001660 if (!UserHandle.isApp(uid)) {
1661 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001662 }
1663
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001664 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001665 final long token = Binder.clearCallingIdentity();
1666 try {
1667 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1668 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001669 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001670 }
1671 } finally {
1672 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001673 }
1674 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001675 }
1676
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001677 @Override
1678 public void addUidPolicy(int uid, int policy) {
1679 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001680
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001681 if (!UserHandle.isApp(uid)) {
1682 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1683 }
1684
1685 synchronized (mRulesLock) {
1686 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1687 policy |= oldPolicy;
1688 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001689 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001690 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001691 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001692 }
1693
1694 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001695 public void removeUidPolicy(int uid, int policy) {
1696 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1697
1698 if (!UserHandle.isApp(uid)) {
1699 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1700 }
1701
1702 synchronized (mRulesLock) {
1703 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1704 policy = oldPolicy & ~policy;
1705 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001706 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001707 }
1708 }
1709 }
1710
Felipe Leme923845f2016-03-02 13:42:48 -08001711 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1712 setUidPolicyUncheckedLocked(uid, policy, persist);
1713
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001714 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1715 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1716 isBlacklisted ? 1 : 0).sendToTarget();
1717
1718 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001719 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001720 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1721 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001722 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001723 .sendToTarget();
1724 }
1725 }
1726
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001727 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1728 mUidPolicy.put(uid, policy);
1729
1730 // uid policy changed, recompute rules and persist policy.
Felipe Leme781ba142016-05-09 16:24:48 -07001731 updateRulesForDataUsageRestrictionsLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001732 if (persist) {
1733 writePolicyLocked();
1734 }
1735 }
1736
1737 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001738 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001739 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1740
Jeff Sharkeya4620792011-05-20 15:29:23 -07001741 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001742 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001743 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001744 }
1745
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001746 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001747 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001748 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1749
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001750 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001751 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001752 for (int i = 0; i < mUidPolicy.size(); i++) {
1753 final int uid = mUidPolicy.keyAt(i);
1754 final int uidPolicy = mUidPolicy.valueAt(i);
1755 if (uidPolicy == policy) {
1756 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001757 }
1758 }
1759 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001760 return uids;
1761 }
1762
1763 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001764 * Removes any persistable state associated with given {@link UserHandle}, persisting
1765 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001766 */
Felipe Lemed17fda42016-04-29 11:12:45 -07001767 boolean removeUserStateLocked(int userId, boolean writePolicy) {
1768
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001769 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001770 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001771
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001772 // Remove entries from restricted background UID whitelist
1773 int[] wlUids = new int[0];
1774 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1775 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1776 if (UserHandle.getUserId(uid) == userId) {
1777 wlUids = appendInt(wlUids, uid);
1778 }
1779 }
1780
1781 if (wlUids.length > 0) {
1782 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001783 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001784 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001785 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001786 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001787
1788 // Remove entries from revoked default restricted background UID whitelist
1789 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1790 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1791 if (UserHandle.getUserId(uid) == userId) {
1792 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001793 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001794 }
1795 }
1796
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001797 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001798 int[] uids = new int[0];
1799 for (int i = 0; i < mUidPolicy.size(); i++) {
1800 final int uid = mUidPolicy.keyAt(i);
1801 if (UserHandle.getUserId(uid) == userId) {
1802 uids = appendInt(uids, uid);
1803 }
1804 }
1805
1806 if (uids.length > 0) {
1807 for (int uid : uids) {
1808 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001809 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001810 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001811 }
1812
Felipe Leme76010a32016-03-17 13:03:11 -07001813 updateRulesForGlobalChangeLocked(true);
1814
Felipe Lemed17fda42016-04-29 11:12:45 -07001815 if (writePolicy && changed) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001816 writePolicyLocked();
1817 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001818 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001819 }
1820
1821 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001822 public void setConnectivityListener(INetworkPolicyListener listener) {
1823 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1824 if (mConnectivityListener != null) {
1825 throw new IllegalStateException("Connectivity listener already registered");
1826 }
1827 mConnectivityListener = listener;
1828 }
1829
1830 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001831 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001832 // TODO: create permission for observing network policy
1833 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001834 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001835 }
1836
1837 @Override
1838 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001839 // TODO: create permission for observing network policy
1840 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001841 mListeners.unregister(listener);
1842 }
1843
Jeff Sharkey1b861272011-05-22 00:34:52 -07001844 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001845 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001846 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1847
Felipe Leme6a05eee2016-02-19 14:43:51 -08001848 final long token = Binder.clearCallingIdentity();
1849 try {
1850 maybeRefreshTrustedTime();
1851 synchronized (mRulesLock) {
1852 normalizePoliciesLocked(policies);
1853 updateNetworkEnabledLocked();
1854 updateNetworkRulesLocked();
1855 updateNotificationsLocked();
1856 writePolicyLocked();
1857 }
1858 } finally {
1859 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001860 }
1861 }
1862
Dianne Hackborn497175b2014-07-01 12:56:08 -07001863 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001864 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001865 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1866 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001867 }
1868
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001869 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001870 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001871 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001872 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001873 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1874 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1875 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001876 } catch (SecurityException e) {
1877 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001878
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001879 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1880 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1881 return new NetworkPolicy[0];
1882 }
Svet Ganov16a16892015-04-16 10:32:04 -07001883 }
1884
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001885 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001886 final int size = mNetworkPolicy.size();
1887 final NetworkPolicy[] policies = new NetworkPolicy[size];
1888 for (int i = 0; i < size; i++) {
1889 policies[i] = mNetworkPolicy.valueAt(i);
1890 }
1891 return policies;
1892 }
1893 }
1894
1895 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001896 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001897 }
1898
1899 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1900 final TelephonyManager tele = TelephonyManager.from(mContext);
1901 final String[] merged = tele.getMergedSubscriberIds();
1902
1903 mNetworkPolicy.clear();
1904 for (NetworkPolicy policy : policies) {
1905 // When two normalized templates conflict, prefer the most
1906 // restrictive policy
1907 policy.template = NetworkTemplate.normalize(policy.template, merged);
1908 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1909 if (existing == null || existing.compareTo(policy) > 0) {
1910 if (existing != null) {
1911 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1912 }
1913 mNetworkPolicy.put(policy.template, policy);
1914 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001915 }
1916 }
1917
1918 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001919 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001920 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001921
1922 final long token = Binder.clearCallingIdentity();
1923 try {
1924 performSnooze(template, TYPE_LIMIT);
1925 } finally {
1926 Binder.restoreCallingIdentity(token);
1927 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001928 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001929
Dianne Hackborn497175b2014-07-01 12:56:08 -07001930 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001931 maybeRefreshTrustedTime();
1932 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001933 synchronized (mRulesLock) {
1934 // find and snooze local policy that matches
1935 final NetworkPolicy policy = mNetworkPolicy.get(template);
1936 if (policy == null) {
1937 throw new IllegalArgumentException("unable to find policy for " + template);
1938 }
1939
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001940 switch (type) {
1941 case TYPE_WARNING:
1942 policy.lastWarningSnooze = currentTime;
1943 break;
1944 case TYPE_LIMIT:
1945 policy.lastLimitSnooze = currentTime;
1946 break;
1947 default:
1948 throw new IllegalArgumentException("unexpected type");
1949 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001950
Jeff Sharkey32566012014-12-02 18:30:14 -08001951 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001952 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001953 updateNetworkRulesLocked();
1954 updateNotificationsLocked();
1955 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001956 }
1957 }
1958
1959 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001960 public void onTetheringChanged(String iface, boolean tethering) {
1961 // No need to enforce permission because setRestrictBackground() will do it.
1962 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1963 synchronized (mRulesLock) {
1964 if (mRestrictBackground && tethering) {
1965 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1966 setRestrictBackground(false);
1967 }
1968 }
1969 }
1970
1971 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001972 public void setRestrictBackground(boolean restrictBackground) {
1973 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001974 final long token = Binder.clearCallingIdentity();
1975 try {
1976 maybeRefreshTrustedTime();
1977 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001978 if (restrictBackground == mRestrictBackground) {
1979 // Ideally, UI should never allow this scenario...
1980 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1981 return;
1982 }
1983 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001984 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001985
Felipe Leme6a05eee2016-02-19 14:43:51 -08001986 } finally {
1987 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001988 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001989
1990 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1991 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001992 }
1993
Felipe Leme70c57c22016-03-29 10:45:13 -07001994 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1995 final boolean oldRestrictBackground = mRestrictBackground;
1996 mRestrictBackground = restrictBackground;
1997 // Must whitelist foreground apps before turning data saver mode on.
1998 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1999 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef3e40642016-06-07 17:28:08 -07002000 updateRulesForAllAppsLocked(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002001 try {
2002 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2003 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2004 mRestrictBackground = oldRestrictBackground;
2005 // TODO: if it knew the foreground apps (see TODO above), it could call
2006 // updateRulesForRestrictBackgroundLocked() again to restore state.
2007 return;
2008 }
2009 } catch (RemoteException e) {
2010 // ignored; service lives in system_server
2011 }
2012 updateNotificationsLocked();
2013 writePolicyLocked();
2014 }
2015
Jeff Sharkey46645002011-07-27 21:11:21 -07002016 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002017 public void addRestrictBackgroundWhitelistedUid(int uid) {
2018 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002019 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002020 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002021 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002022 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002023 if (oldStatus) {
2024 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2025 return;
2026 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002027 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002028 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002029 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002030 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2031 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2032 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2033 + " from revoked restrict background whitelist");
2034 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2035 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002036 if (needFirewallRules) {
2037 // Only update firewall rules if necessary...
Felipe Leme781ba142016-05-09 16:24:48 -07002038 updateRulesForDataUsageRestrictionsLocked(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002039 }
2040 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08002041 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002042 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002043 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
2044 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2045 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002046 }
2047
2048 @Override
2049 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2050 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002051 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002052 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002053 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002054 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002055 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2056 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002057 }
2058
Felipe Leme70c57c22016-03-29 10:45:13 -07002059 /**
2060 * Removes a uid from the restricted background whitelist, returning whether its current
2061 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2062 */
2063 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2064 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002065 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002066 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002067 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2068 return false;
2069 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002070 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002071 if (oldStatus) {
2072 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2073 mRestrictBackgroundWhitelistUids.delete(uid);
2074 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002075 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2076 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2077 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2078 + " to revoked restrict background whitelist");
2079 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2080 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002081 if (needFirewallRules) {
2082 // Only update firewall rules if necessary...
Felipe Leme781ba142016-05-09 16:24:48 -07002083 updateRulesForDataUsageRestrictionsLocked(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002084 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002085 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002086 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002087 writePolicyLocked();
2088 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002089 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2090 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002091 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002092 }
2093
2094 @Override
2095 public int[] getRestrictBackgroundWhitelistedUids() {
2096 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2097 synchronized (mRulesLock) {
2098 final int size = mRestrictBackgroundWhitelistUids.size();
2099 final int[] whitelist = new int[size];
2100 for (int i = 0; i < size; i++) {
2101 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2102 }
2103 if (LOGV) {
2104 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2105 + mRestrictBackgroundWhitelistUids);
2106 }
2107 return whitelist;
2108 }
2109 }
2110
2111 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002112 public int getRestrictBackgroundByCaller() {
2113 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2114 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002115
Felipe Leme1b103232016-01-22 09:44:57 -08002116 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002117 // Must clear identity because getUidPolicy() is restricted to system.
2118 final long token = Binder.clearCallingIdentity();
2119 final int policy;
2120 try {
2121 policy = getUidPolicy(uid);
2122 } finally {
2123 Binder.restoreCallingIdentity(token);
2124 }
2125 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2126 // App is blacklisted.
2127 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2128 }
Felipe Leme1b103232016-01-22 09:44:57 -08002129 if (!mRestrictBackground) {
2130 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2131 }
2132 return mRestrictBackgroundWhitelistUids.get(uid)
2133 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2134 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2135 }
2136 }
2137
2138 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002139 public boolean getRestrictBackground() {
2140 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2141
2142 synchronized (mRulesLock) {
2143 return mRestrictBackground;
2144 }
2145 }
2146
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002147 @Override
2148 public void setDeviceIdleMode(boolean enabled) {
2149 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2150
2151 synchronized (mRulesLock) {
2152 if (mDeviceIdleMode != enabled) {
2153 mDeviceIdleMode = enabled;
2154 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002155 // Device idle change means we need to rebuild rules for all
2156 // known apps, so do a global refresh.
Felipe Lemef3e40642016-06-07 17:28:08 -07002157 updateRulesForRestrictPowerLocked();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002158 }
2159 if (enabled) {
2160 EventLogTags.writeDeviceIdleOnPhase("net");
2161 } else {
2162 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002163 }
2164 }
2165 }
2166 }
2167
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002168 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002169 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2170 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002171 if (policy.template.matches(ident)) {
2172 return policy;
2173 }
2174 }
2175 return null;
2176 }
2177
2178 @Override
2179 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2180 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2181
2182 // only returns usage summary, so we don't require caller to have
2183 // READ_NETWORK_USAGE_HISTORY.
2184 final long token = Binder.clearCallingIdentity();
2185 try {
2186 return getNetworkQuotaInfoUnchecked(state);
2187 } finally {
2188 Binder.restoreCallingIdentity(token);
2189 }
2190 }
2191
2192 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2193 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2194
2195 final NetworkPolicy policy;
2196 synchronized (mRulesLock) {
2197 policy = findPolicyForNetworkLocked(ident);
2198 }
2199
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002200 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002201 // missing policy means we can't derive useful quota info
2202 return null;
2203 }
2204
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002205 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002206
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002207 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002208 final long start = computeLastCycleBoundary(currentTime, policy);
2209 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002210 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002211
2212 // report soft and hard limits under policy
2213 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2214 : NetworkQuotaInfo.NO_LIMIT;
2215 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2216 : NetworkQuotaInfo.NO_LIMIT;
2217
2218 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2219 }
2220
Jeff Sharkey46645002011-07-27 21:11:21 -07002221 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002222 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002223 if (state.networkInfo == null) {
2224 return false;
2225 }
2226
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002227 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2228
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002229 // roaming networks are always considered metered
2230 if (ident.getRoaming()) {
2231 return true;
2232 }
2233
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002234 final NetworkPolicy policy;
2235 synchronized (mRulesLock) {
2236 policy = findPolicyForNetworkLocked(ident);
2237 }
2238
2239 if (policy != null) {
2240 return policy.metered;
2241 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002242 final int type = state.networkInfo.getType();
2243 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2244 return true;
2245 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002246 return false;
2247 }
2248 }
2249
2250 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002251 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002252 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002253
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002254 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2255
Dianne Hackborn497175b2014-07-01 12:56:08 -07002256 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002257 for (String arg : args) {
2258 argSet.add(arg);
2259 }
2260
Jeff Sharkey1b861272011-05-22 00:34:52 -07002261 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002262 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002263 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2264 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002265 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002266
Jeff Sharkey32566012014-12-02 18:30:14 -08002267 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002268 updateNetworkEnabledLocked();
2269 updateNetworkRulesLocked();
2270 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002271 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002272
2273 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002274 return;
2275 }
2276
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002277 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002278 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002279 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002280 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002281 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002282 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002283 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2284 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002285 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002286 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002287
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002288 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2289
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002290 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002291 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002292 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002293 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002294 final int uid = mUidPolicy.keyAt(i);
2295 final int policy = mUidPolicy.valueAt(i);
2296 fout.print("UID=");
2297 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002298 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002299 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002300 fout.println();
2301 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002302 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002303
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002304 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2305 if (size > 0) {
2306 fout.println("Power save whitelist (except idle) app ids:");
2307 fout.increaseIndent();
2308 for (int i = 0; i < size; i++) {
2309 fout.print("UID=");
2310 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2311 fout.print(": ");
2312 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2313 fout.println();
2314 }
2315 fout.decreaseIndent();
2316 }
2317
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002318 size = mPowerSaveWhitelistAppIds.size();
2319 if (size > 0) {
2320 fout.println("Power save whitelist app ids:");
2321 fout.increaseIndent();
2322 for (int i = 0; i < size; i++) {
2323 fout.print("UID=");
2324 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2325 fout.print(": ");
2326 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2327 fout.println();
2328 }
2329 fout.decreaseIndent();
2330 }
2331
Felipe Lemeb85a6372016-01-14 16:16:16 -08002332 size = mRestrictBackgroundWhitelistUids.size();
2333 if (size > 0) {
2334 fout.println("Restrict background whitelist uids:");
2335 fout.increaseIndent();
2336 for (int i = 0; i < size; i++) {
2337 fout.print("UID=");
2338 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2339 fout.println();
2340 }
2341 fout.decreaseIndent();
2342 }
2343
Felipe Lemea9505cc2016-02-26 10:28:41 -08002344 size = mDefaultRestrictBackgroundWhitelistUids.size();
2345 if (size > 0) {
2346 fout.println("Default restrict background whitelist uids:");
2347 fout.increaseIndent();
2348 for (int i = 0; i < size; i++) {
2349 fout.print("UID=");
2350 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2351 fout.println();
2352 }
2353 fout.decreaseIndent();
2354 }
2355
2356 size = mRestrictBackgroundWhitelistRevokedUids.size();
2357 if (size > 0) {
2358 fout.println("Default restrict background whitelist uids revoked by users:");
2359 fout.increaseIndent();
2360 for (int i = 0; i < size; i++) {
2361 fout.print("UID=");
2362 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2363 fout.println();
2364 }
2365 fout.decreaseIndent();
2366 }
2367
Jeff Sharkey1b861272011-05-22 00:34:52 -07002368 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002369 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002370 collectKeys(mUidRules, knownUids);
2371
Felipe Leme46c4fc32016-05-04 09:21:43 -07002372 fout.println("Status for all known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002373 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002374 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002375 for (int i = 0; i < size; i++) {
2376 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002377 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002378 fout.print(uid);
2379
Jeff Sharkeydc988062015-09-14 10:09:47 -07002380 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002381 fout.print(" state=");
2382 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002383 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2384 fout.print(" (fg)");
2385 } else {
2386 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2387 ? " (fg svc)" : " (bg)");
2388 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002389
Felipe Leme46c4fc32016-05-04 09:21:43 -07002390 final int uidRules = mUidRules.get(uid, RULE_NONE);
2391 fout.print(" rules=");
2392 fout.print(uidRulesToString(uidRules));
2393 fout.println();
2394 }
2395 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002396
Felipe Leme46c4fc32016-05-04 09:21:43 -07002397 fout.println("Status for just UIDs with rules:");
2398 fout.increaseIndent();
2399 size = mUidRules.size();
2400 for (int i = 0; i < size; i++) {
2401 final int uid = mUidRules.keyAt(i);
2402 fout.print("UID=");
2403 fout.print(uid);
2404 final int uidRules = mUidRules.get(uid, RULE_NONE);
2405 fout.print(" rules=");
2406 fout.print(uidRulesToString(uidRules));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002407 fout.println();
2408 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002409 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002410 }
2411 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002412
2413 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002414 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2415 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002416 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002417 this, in, out, err, args, resultReceiver);
2418 }
2419
2420 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002421 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002422 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2423
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002424 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002425 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002426 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002427 }
2428
Felipe Lemef28983d2016-03-25 12:18:23 -07002429 private boolean isUidForegroundLocked(int uid) {
2430 return isUidStateForegroundLocked(
2431 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2432 }
2433
Felipe Lemeef89c902016-03-30 15:11:31 -07002434 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2435 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2436 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2437 }
2438
Felipe Leme781ba142016-05-09 16:24:48 -07002439 private boolean isUidForegroundOnRestrictPowerLocked(int uid) {
2440 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2441 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2442 }
2443
Felipe Lemef28983d2016-03-25 12:18:23 -07002444 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002445 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002446 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002447 }
2448
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002449 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002450 * Process state of UID changed; if needed, will trigger
Felipe Leme781ba142016-05-09 16:24:48 -07002451 * {@link #updateRulesForDataUsageRestrictionsLocked(int)} and
2452 * {@link #updateRulesForPowerRestrictionsLocked(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002453 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002454 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002455 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2456 if (oldUidState != uidState) {
2457 // state changed, push updated rules
2458 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002459 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002460 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2461 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002462 if (isUidIdle(uid)) {
2463 updateRuleForAppIdleLocked(uid);
2464 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002465 if (mDeviceIdleMode) {
2466 updateRuleForDeviceIdleLocked(uid);
2467 }
2468 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002469 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002470 }
Felipe Leme781ba142016-05-09 16:24:48 -07002471 updateRulesForPowerRestrictionsLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002472 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002473 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002474 }
2475 }
2476
Felipe Lemef28983d2016-03-25 12:18:23 -07002477 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002478 final int index = mUidState.indexOfKey(uid);
2479 if (index >= 0) {
2480 final int oldUidState = mUidState.valueAt(index);
2481 mUidState.removeAt(index);
2482 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002483 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002484 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002485 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002486 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002487 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002488 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002489 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002490 }
Felipe Leme781ba142016-05-09 16:24:48 -07002491 updateRulesForPowerRestrictionsLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002492 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002493 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002494 }
2495 }
2496
Felipe Lemef28983d2016-03-25 12:18:23 -07002497 // adjust stats accounting based on foreground status
2498 private void updateNetworkStats(int uid, boolean uidForeground) {
2499 try {
2500 mNetworkStats.setUidForeground(uid, uidForeground);
2501 } catch (RemoteException e) {
2502 // ignored; service lives in system_server
2503 }
2504 }
2505
2506 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2507 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002508 final boolean oldForeground =
2509 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2510 final boolean newForeground =
2511 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002512 if (oldForeground != newForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002513 updateRulesForDataUsageRestrictionsLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002514 }
2515 }
2516
Jeff Sharkeya4620792011-05-20 15:29:23 -07002517 private void updateScreenOn() {
2518 synchronized (mRulesLock) {
2519 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002520 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002521 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002522 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002523 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002524 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002525 }
2526 }
2527
2528 /**
2529 * Update rules that might be changed by {@link #mScreenOn} value.
2530 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002531 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002532 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002533 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002534 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002535 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002536 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002537 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002538 }
2539 }
2540 }
2541
Felipe Leme011b98f2016-02-10 17:28:31 -08002542 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002543 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2544 }
2545
Felipe Lemeef89c902016-03-30 15:11:31 -07002546 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2547 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2548 }
2549
Felipe Lemef3e40642016-06-07 17:28:08 -07002550 void updateRulesForPowerSaveLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002551 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2552 mUidFirewallPowerSaveRules);
2553 }
2554
Felipe Lemef28983d2016-03-25 12:18:23 -07002555 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002556 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2557 }
2558
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002559 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002560 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2561 mUidFirewallDozableRules);
2562 }
2563
2564 void updateRuleForDeviceIdleLocked(int uid) {
2565 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2566 }
2567
Felipe Lemef28983d2016-03-25 12:18:23 -07002568 // NOTE: since both fw_dozable and fw_powersave uses the same map
2569 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002570 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2571 SparseIntArray rules) {
2572 if (enabled) {
2573 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002574 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002575 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002576 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002577 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002578 for (int ui = users.size() - 1; ui >= 0; ui--) {
2579 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002580 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002581 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2582 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2583 int uid = UserHandle.getUid(user.id, appId);
2584 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2585 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002586 }
2587 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2588 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2589 int uid = UserHandle.getUid(user.id, appId);
2590 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2591 }
2592 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002593 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002594 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002595 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2596 }
2597 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002598 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002599 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002600
Felipe Leme011b98f2016-02-10 17:28:31 -08002601 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002602 }
2603
Felipe Leme781ba142016-05-09 16:24:48 -07002604 private void updateRulesForNonMeteredNetworksLocked() {
2605
2606 }
2607
Felipe Leme46c4fc32016-05-04 09:21:43 -07002608 private boolean isWhitelistedBatterySaverLocked(int uid) {
2609 final int appId = UserHandle.getAppId(uid);
2610 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2611 }
2612
Felipe Lemef28983d2016-03-25 12:18:23 -07002613 // NOTE: since both fw_dozable and fw_powersave uses the same map
2614 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002615 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2616 if (enabled) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002617 if (isWhitelistedBatterySaverLocked(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002618 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2619 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002620 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002621 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002622 }
2623 }
2624 }
2625
2626 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002627 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2628 uidRules.clear();
2629
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002630 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002631 final List<UserInfo> users = mUserManager.getUsers();
2632 for (int ui = users.size() - 1; ui >= 0; ui--) {
2633 UserInfo user = users.get(ui);
2634 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2635 for (int uid : idleUids) {
2636 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002637 // quick check: if this uid doesn't have INTERNET permission, it
2638 // doesn't have network access anyway, so it is a waste to mess
2639 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002640 if (hasInternetPermissions(uid)) {
2641 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002642 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002643 }
2644 }
2645 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002646
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002647 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2648 }
2649
2650 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002651 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002652
2653 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002654 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2655 && !isUidForegroundOnRestrictPowerLocked(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002656 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2657 } else {
2658 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2659 }
2660 }
2661
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002662 void updateRulesForAppIdleParoleLocked() {
2663 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2664 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002665 }
2666
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002667 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002668 * Update rules that might be changed by {@link #mRestrictBackground},
2669 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002670 */
Felipe Leme76010a32016-03-17 13:03:11 -07002671 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002672 long start;
2673 if (LOGD) start = System.currentTimeMillis();
2674
Felipe Leme011b98f2016-02-10 17:28:31 -08002675 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002676 updateRulesForRestrictBackgroundLocked();
Felipe Leme76010a32016-03-17 13:03:11 -07002677
2678 // If the set of restricted networks may have changed, re-evaluate those.
2679 if (restrictedNetworksChanged) {
2680 normalizePoliciesLocked();
2681 updateNetworkRulesLocked();
2682 }
2683 if (LOGD) {
2684 final long delta = System.currentTimeMillis() - start;
2685 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2686 + delta + "ms");
2687 }
2688 }
2689
Felipe Lemef3e40642016-06-07 17:28:08 -07002690 private void updateRulesForRestrictPowerLocked() {
2691 updateRulesForDeviceIdleLocked();
2692 updateRulesForAppIdleLocked();
2693 updateRulesForPowerSaveLocked();
2694 updateRulesForAllAppsLocked(TYPE_RESTRICT_POWER);
2695 }
2696
Felipe Lemef28983d2016-03-25 12:18:23 -07002697 private void updateRulesForRestrictBackgroundLocked() {
Felipe Lemef3e40642016-06-07 17:28:08 -07002698 updateRulesForAllAppsLocked(TYPE_RESTRICT_BACKGROUND);
2699 }
2700
2701 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2702 private static final int TYPE_RESTRICT_POWER = 2;
2703 @Retention(RetentionPolicy.SOURCE)
2704 @IntDef(flag = false, value = {
2705 TYPE_RESTRICT_BACKGROUND,
2706 TYPE_RESTRICT_POWER,
2707 })
2708 public @interface RestrictType {
2709 }
2710
2711 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
2712 private void updateRulesForAllAppsLocked(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002713 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002714
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002715 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002716 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002717 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002718 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2719 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2720 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002721
Felipe Leme03e689d2016-03-02 16:17:38 -08002722 final int usersSize = users.size();
2723 final int appsSize = apps.size();
2724 for (int i = 0; i < usersSize; i++) {
2725 final UserInfo user = users.get(i);
2726 for (int j = 0; j < appsSize; j++) {
2727 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002728 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002729 switch (type) {
2730 case TYPE_RESTRICT_BACKGROUND:
2731 updateRulesForDataUsageRestrictionsLocked(uid);
2732 break;
2733 case TYPE_RESTRICT_POWER:
2734 updateRulesForPowerRestrictionsLocked(uid);
2735 break;
2736 default:
2737 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2738 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002739 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002740 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002741 }
2742
Felipe Leme76010a32016-03-17 13:03:11 -07002743 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002744 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002745 for (int i = 0; i < users.size(); i++) {
2746 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002747 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002748 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002749 int uid = UserHandle.getUid(user.id, appId);
Felipe Lemef3e40642016-06-07 17:28:08 -07002750 updateRulesForRestrictPowerLocked();
Felipe Leme781ba142016-05-09 16:24:48 -07002751 // Update external firewall rules.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002752 updateRuleForAppIdleLocked(uid);
2753 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002754 updateRuleForRestrictPowerLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002755 // Update internal rules.
2756 updateRulesForPowerRestrictionsLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002757 }
2758 }
2759 }
2760
Felipe Leme70c57c22016-03-29 10:45:13 -07002761 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2762 // methods below could be merged into a isUidValidForRules() method.
2763 private boolean isUidValidForBlacklistRules(int uid) {
2764 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002765 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002766 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002767 return true;
2768 }
2769
2770 return false;
2771 }
2772
Felipe Leme70c57c22016-03-29 10:45:13 -07002773 private boolean isUidValidForWhitelistRules(int uid) {
2774 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2775 }
2776
Amith Yamasani15e472352015-04-24 19:06:07 -07002777 private boolean isUidIdle(int uid) {
2778 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2779 final int userId = UserHandle.getUserId(uid);
2780
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002781 if (!ArrayUtils.isEmpty(packages)) {
2782 for (String packageName : packages) {
2783 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2784 return false;
2785 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002786 }
2787 }
2788 return true;
2789 }
2790
2791 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002792 * Checks if an uid has INTERNET permissions.
2793 * <p>
2794 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002795 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002796 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002797 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002798 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002799 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002800 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002801 }
2802 } catch (RemoteException e) {
2803 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002804 return true;
2805 }
2806
2807 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002808 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002809 *
Felipe Leme781ba142016-05-09 16:24:48 -07002810 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002811 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002812 * <li>Doze mode
2813 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002814 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002815 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002816 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002817 *
2818 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002819 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002820 private void updateRestrictionRulesForUidLocked(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002821 // Methods below only changes the firewall rules for the power-related modes.
2822 updateRuleForDeviceIdleLocked(uid);
2823 updateRuleForAppIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002824 updateRuleForRestrictPowerLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002825
2826 // Update internal state for power-related modes.
2827 updateRulesForPowerRestrictionsLocked(uid);
2828
2829 // Update firewall and internal rules for Data Saver Mode.
2830 updateRulesForDataUsageRestrictionsLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002831 }
2832
Felipe Leme70c57c22016-03-29 10:45:13 -07002833 /**
2834 * Applies network rules to bandwidth controllers based on process state and user-defined
2835 * restrictions (blacklist / whitelist).
2836 *
2837 * <p>
2838 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2839 * networks:
2840 * <ul>
2841 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2842 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2843 * also blacklisted.
2844 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2845 * no UIDs other those whitelisted will have access.
2846 * <ul>
2847 *
2848 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2849 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2850 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2851 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Leme781ba142016-05-09 16:24:48 -07002852 * this ({@link #updateRulesForDataUsageRestrictionsLocked(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002853 * {@link INetworkManagementService}, but this method should also be called in events (like
2854 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2855 * following rules should also be applied:
2856 *
2857 * <ul>
2858 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2859 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2860 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2861 * {@code bw_penalty_box}.
2862 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2863 * </ul>
2864 *
2865 * <p>For optimization, the rules are only applied on user apps that have internet access
2866 * permission, since there is no need to change the {@code iptables} rule if the app does not
2867 * have permission to use the internet.
2868 *
2869 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002870 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002871 */
Felipe Leme781ba142016-05-09 16:24:48 -07002872 private void updateRulesForDataUsageRestrictionsLocked(int uid) {
2873 updateRulesForDataUsageRestrictionsLocked(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002874 }
2875
2876 /**
Felipe Leme781ba142016-05-09 16:24:48 -07002877 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsLocked(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002878 * app is removed - it ignores the UID validity check.
2879 */
Felipe Leme781ba142016-05-09 16:24:48 -07002880 private void updateRulesForDataUsageRestrictionsLocked(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002881 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2882 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2883 return;
2884 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002885
Dianne Hackborn497175b2014-07-01 12:56:08 -07002886 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002887 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002888 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002889
Felipe Leme781ba142016-05-09 16:24:48 -07002890 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2891 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2892 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2893 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002894
Felipe Leme70c57c22016-03-29 10:45:13 -07002895 // First step: define the new rule based on user restrictions and foreground state.
2896 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002897 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2898 newRule = RULE_TEMPORARY_ALLOW_METERED;
2899 } else if (isWhitelisted) {
2900 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002901 }
2902 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002903 if (isBlacklisted) {
2904 newRule = RULE_REJECT_METERED;
2905 } else if (mRestrictBackground && isWhitelisted) {
2906 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002907 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002908 }
Felipe Leme781ba142016-05-09 16:24:48 -07002909 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002910
Felipe Lemef28983d2016-03-25 12:18:23 -07002911 if (LOGV) {
Felipe Leme781ba142016-05-09 16:24:48 -07002912 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + ")"
2913 + ": isForeground=" +isForeground
2914 + ", isBlacklisted=" + isBlacklisted
2915 + ", isWhitelisted=" + isWhitelisted
2916 + ", oldRule=" + uidRulesToString(oldRule)
2917 + ", newRule=" + uidRulesToString(newRule)
2918 + ", newUidRules=" + uidRulesToString(newUidRules)
2919 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002920 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002921
Felipe Leme46c4fc32016-05-04 09:21:43 -07002922 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002923 mUidRules.delete(uid);
2924 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002925 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002926 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002927
Felipe Lemed31a97f2016-05-06 14:53:50 -07002928 boolean changed = false;
2929
Felipe Leme70c57c22016-03-29 10:45:13 -07002930 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002931 if (newRule != oldRule) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07002932 changed = true;
2933
Felipe Leme781ba142016-05-09 16:24:48 -07002934 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002935 // Temporarily whitelist foreground app, removing from blacklist if necessary
2936 // (since bw_penalty_box prevails over bw_happy_box).
2937
2938 setMeteredNetworkWhitelist(uid, true);
2939 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2940 // but ideally it should be just:
2941 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002942 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002943 setMeteredNetworkBlacklist(uid, false);
2944 }
Felipe Leme781ba142016-05-09 16:24:48 -07002945 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002946 // Remove temporary whitelist from app that is not on foreground anymore.
2947
2948 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2949 // but ideally they should be just:
2950 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2951 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002952 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002953 setMeteredNetworkWhitelist(uid, false);
2954 }
Felipe Leme781ba142016-05-09 16:24:48 -07002955 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002956 setMeteredNetworkBlacklist(uid, true);
2957 }
Felipe Leme781ba142016-05-09 16:24:48 -07002958 } else if ((newRule & RULE_REJECT_METERED) != 0
2959 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002960 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002961 setMeteredNetworkBlacklist(uid, isBlacklisted);
2962 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002963 // Since blacklist prevails over whitelist, we need to handle the special case
2964 // where app is whitelisted and blacklisted at the same time (although such
2965 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07002966 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002967 }
Felipe Leme781ba142016-05-09 16:24:48 -07002968 } else if ((newRule & RULE_ALLOW_METERED) != 0
2969 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002970 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07002971 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002972 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002973 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002974 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2975 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07002976 + ", whitelisted=" + isWhitelisted
2977 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07002978 + ", newRule=" + uidRulesToString(newUidRules)
2979 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07002980 }
Felipe Leme781ba142016-05-09 16:24:48 -07002981
2982 // Dispatch changed rule to existing listeners.
2983 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
2984 }
2985 }
2986
2987 /**
2988 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
2989 * listeners in case of change.
2990 * <p>
2991 * There are 3 power-related rules that affects whether an app has background access on
2992 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
2993 * restriction, it's added to the equivalent firewall chain:
2994 * <ul>
2995 * <li>App is idle: {@code fw_standby} firewall chain.
2996 * <li>Device is idle: {@code fw_dozable} firewall chain.
2997 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
2998 * </ul>
2999 * <p>
3000 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3001 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3002 * <p>
3003 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3004 */
3005 private void updateRulesForPowerRestrictionsLocked(int uid) {
3006 if (!isUidValidForBlacklistRules(uid)) {
3007 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3008 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003009 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003010
Felipe Leme781ba142016-05-09 16:24:48 -07003011 final boolean isIdle = isUidIdle(uid);
3012 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
3013 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
3014 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3015 final boolean isForeground = isUidForegroundOnRestrictPowerLocked(uid);
3016
3017 final boolean isWhitelisted = isWhitelistedBatterySaverLocked(uid);
3018 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3019 int newRule = RULE_NONE;
3020
3021 // First step: define the new rule based on user restrictions and foreground state.
3022
3023 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3024 // by considering the foreground and non-foreground states.
3025 if (isForeground) {
3026 if (restrictMode) {
3027 newRule = RULE_ALLOW_ALL;
3028 }
3029 } else if (restrictMode) {
3030 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3031 }
3032
3033 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3034
3035 if (LOGV) {
3036 Log.v(TAG, "updateRulesForNonMeteredNetworksLocked(" + uid + ")"
3037 + ", isIdle: " + isIdle
3038 + ", mRestrictPower: " + mRestrictPower
3039 + ", mDeviceIdleMode: " + mDeviceIdleMode
3040 + ", isForeground=" + isForeground
3041 + ", isWhitelisted=" + isWhitelisted
3042 + ", oldRule=" + uidRulesToString(oldRule)
3043 + ", newRule=" + uidRulesToString(newRule)
3044 + ", newUidRules=" + uidRulesToString(newUidRules)
3045 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3046 }
3047
3048 if (newUidRules == RULE_NONE) {
3049 mUidRules.delete(uid);
3050 } else {
3051 mUidRules.put(uid, newUidRules);
3052 }
3053
3054 // Second step: notify listeners if state changed.
3055 if (newRule != oldRule) {
3056 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003057 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003058 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003059 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3060 } else {
3061 // All scenarios should have been covered above
3062 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3063 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003064 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003065 + ", newRule=" + uidRulesToString(newUidRules)
3066 + ", oldRule=" + uidRulesToString(oldUidRules));
3067 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003068 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003069 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003070 }
3071
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003072 private class AppIdleStateChangeListener
3073 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3074
3075 @Override
3076 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3077 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003078 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3079 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003080 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003081 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003082 updateRuleForAppIdleLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003083 updateRulesForPowerRestrictionsLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003084 }
3085 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003086 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003087 }
3088
3089 @Override
3090 public void onParoleStateChanged(boolean isParoleOn) {
3091 synchronized (mRulesLock) {
3092 updateRulesForAppIdleParoleLocked();
3093 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003094 }
3095 }
3096
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003097 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3098 if (listener != null) {
3099 try {
3100 listener.onUidRulesChanged(uid, uidRules);
3101 } catch (RemoteException ignored) {
3102 }
3103 }
3104 }
3105
3106 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3107 String[] meteredIfaces) {
3108 if (listener != null) {
3109 try {
3110 listener.onMeteredIfacesChanged(meteredIfaces);
3111 } catch (RemoteException ignored) {
3112 }
3113 }
3114 }
3115
3116 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3117 boolean restrictBackground) {
3118 if (listener != null) {
3119 try {
3120 listener.onRestrictBackgroundChanged(restrictBackground);
3121 } catch (RemoteException ignored) {
3122 }
3123 }
3124 }
3125
3126 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3127 int uid, boolean whitelisted) {
3128 if (listener != null) {
3129 try {
3130 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3131 } catch (RemoteException ignored) {
3132 }
3133 }
3134 }
3135
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003136 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3137 int uid, boolean blacklisted) {
3138 if (listener != null) {
3139 try {
3140 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3141 } catch (RemoteException ignored) {
3142 }
3143 }
3144 }
3145
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003146 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003147 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003148 public boolean handleMessage(Message msg) {
3149 switch (msg.what) {
3150 case MSG_RULES_CHANGED: {
3151 final int uid = msg.arg1;
3152 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003153 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003154 final int length = mListeners.beginBroadcast();
3155 for (int i = 0; i < length; i++) {
3156 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003157 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003158 }
3159 mListeners.finishBroadcast();
3160 return true;
3161 }
3162 case MSG_METERED_IFACES_CHANGED: {
3163 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003164 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003165 final int length = mListeners.beginBroadcast();
3166 for (int i = 0; i < length; i++) {
3167 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003168 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003169 }
3170 mListeners.finishBroadcast();
3171 return true;
3172 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003173 case MSG_LIMIT_REACHED: {
3174 final String iface = (String) msg.obj;
3175
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003176 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003177 synchronized (mRulesLock) {
3178 if (mMeteredIfaces.contains(iface)) {
3179 try {
3180 // force stats update to make sure we have
3181 // numbers that caused alert to trigger.
3182 mNetworkStats.forceUpdate();
3183 } catch (RemoteException e) {
3184 // ignored; service lives in system_server
3185 }
3186
3187 updateNetworkEnabledLocked();
3188 updateNotificationsLocked();
3189 }
3190 }
3191 return true;
3192 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003193 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3194 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003195 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003196 final int length = mListeners.beginBroadcast();
3197 for (int i = 0; i < length; i++) {
3198 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003199 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003200 }
3201 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003202 final Intent intent =
3203 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3204 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3205 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3206 return true;
3207 }
3208 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003209 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3210 // - when an app is whitelisted
3211 // - when an app is blacklisted
3212 //
3213 // Whether the internal listeners (INetworkPolicyListener implementations) or
3214 // app broadcast receivers are notified depend on the following rules:
3215 //
3216 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3217 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3218 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003219 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003220 final boolean changed = msg.arg2 == 1;
3221 final Boolean whitelisted = (Boolean) msg.obj;
3222
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003223 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003224 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003225 final boolean whitelistedBool = whitelisted.booleanValue();
3226 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3227 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003228 final int length = mListeners.beginBroadcast();
3229 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003230 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003231 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3232 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003233 }
3234 mListeners.finishBroadcast();
3235 }
Felipe Leme9778f762016-01-27 14:46:39 -08003236 final PackageManager pm = mContext.getPackageManager();
3237 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003238 if (changed && packages != null) {
3239 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003240 final int userId = UserHandle.getUserId(uid);
3241 for (String packageName : packages) {
3242 final Intent intent = new Intent(
3243 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3244 intent.setPackage(packageName);
3245 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3246 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3247 }
Felipe Leme9778f762016-01-27 14:46:39 -08003248 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003249 return true;
3250 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003251 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3252 final int uid = msg.arg1;
3253 final boolean blacklisted = msg.arg2 == 1;
3254
3255 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3256 blacklisted);
3257 final int length = mListeners.beginBroadcast();
3258 for (int i = 0; i < length; i++) {
3259 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3260 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3261 blacklisted);
3262 }
3263 mListeners.finishBroadcast();
3264 return true;
3265 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003266 case MSG_ADVISE_PERSIST_THRESHOLD: {
3267 final long lowestRule = (Long) msg.obj;
3268 try {
3269 // make sure stats are recorded frequently enough; we aim
3270 // for 2MB threshold for 2GB/month rules.
3271 final long persistThreshold = lowestRule / 1000;
3272 mNetworkStats.advisePersistThreshold(persistThreshold);
3273 } catch (RemoteException e) {
3274 // ignored; service lives in system_server
3275 }
3276 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003277 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003278 case MSG_SCREEN_ON_CHANGED: {
3279 updateScreenOn();
3280 return true;
3281 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003282 case MSG_UPDATE_INTERFACE_QUOTA: {
3283 removeInterfaceQuota((String) msg.obj);
3284 // int params need to be stitched back into a long
3285 setInterfaceQuota((String) msg.obj,
3286 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3287 return true;
3288 }
3289 case MSG_REMOVE_INTERFACE_QUOTA: {
3290 removeInterfaceQuota((String) msg.obj);
3291 return true;
3292 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003293 default: {
3294 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003295 }
3296 }
3297 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003298 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003299
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003300 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003301 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003302 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003303 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003304 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003305 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003306 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003307 }
3308 }
3309
3310 private void removeInterfaceQuota(String iface) {
3311 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003312 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003313 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003314 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003315 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003316 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003317 }
3318 }
3319
Felipe Leme70c57c22016-03-29 10:45:13 -07003320 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3321 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003322 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003323 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003324 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003325 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3326 } catch (RemoteException e) {
3327 // ignored; service lives in system_server
3328 }
3329 }
3330
3331 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3332 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3333 try {
3334 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3335 } catch (IllegalStateException e) {
3336 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003337 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003338 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003339 }
3340 }
3341
Amith Yamasani15e472352015-04-24 19:06:07 -07003342 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003343 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3344 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3345 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003346 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003347 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003348 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003349 int size = uidRules.size();
3350 int[] uids = new int[size];
3351 int[] rules = new int[size];
3352 for(int index = size - 1; index >= 0; --index) {
3353 uids[index] = uidRules.keyAt(index);
3354 rules[index] = uidRules.valueAt(index);
3355 }
3356 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003357 } catch (IllegalStateException e) {
3358 Log.wtf(TAG, "problem setting firewall uid rules", e);
3359 } catch (RemoteException e) {
3360 // ignored; service lives in system_server
3361 }
3362 }
3363
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003364 /**
3365 * Add or remove a uid to the firewall blacklist for all network ifaces.
3366 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003367 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003368 if (chain == FIREWALL_CHAIN_DOZABLE) {
3369 mUidFirewallDozableRules.put(uid, rule);
3370 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3371 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003372 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3373 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003374 }
3375
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003376 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003377 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003378 } catch (IllegalStateException e) {
3379 Log.wtf(TAG, "problem setting firewall uid rules", e);
3380 } catch (RemoteException e) {
3381 // ignored; service lives in system_server
3382 }
3383 }
3384
3385 /**
3386 * Add or remove a uid to the firewall blacklist for all network ifaces.
3387 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003388 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003389 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3390 mFirewallChainStates.get(chain) == enable) {
3391 // All is the same, nothing to do.
3392 return;
3393 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003394 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003395 try {
3396 mNetworkManager.setFirewallChainEnabled(chain, enable);
3397 } catch (IllegalStateException e) {
3398 Log.wtf(TAG, "problem enable firewall chain", e);
3399 } catch (RemoteException e) {
3400 // ignored; service lives in system_server
3401 }
3402 }
3403
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003404 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3405 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003406 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003407 } catch (RuntimeException e) {
3408 Slog.w(TAG, "problem reading network stats: " + e);
3409 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003410 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003411 // ignored; service lives in system_server
3412 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003413 }
3414 }
3415
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003416 private boolean isBandwidthControlEnabled() {
3417 final long token = Binder.clearCallingIdentity();
3418 try {
3419 return mNetworkManager.isBandwidthControlEnabled();
3420 } catch (RemoteException e) {
3421 // ignored; service lives in system_server
3422 return false;
3423 } finally {
3424 Binder.restoreCallingIdentity(token);
3425 }
3426 }
3427
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003428 /**
3429 * Try refreshing {@link #mTime} when stale.
3430 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003431 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003432 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003433 mTime.forceRefresh();
3434 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003435 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003436
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003437 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003438 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3439 }
3440
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003441 private static Intent buildAllowBackgroundDataIntent() {
3442 return new Intent(ACTION_ALLOW_BACKGROUND);
3443 }
3444
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003445 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3446 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3447 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3448 return intent;
3449 }
3450
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003451 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3452 final Intent intent = new Intent();
3453 intent.setComponent(new ComponentName(
3454 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3455 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3456 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3457 return intent;
3458 }
3459
3460 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3461 final Intent intent = new Intent();
3462 intent.setComponent(new ComponentName(
3463 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3464 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3465 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3466 return intent;
3467 }
3468
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003469 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003470 public void addIdleHandler(IdleHandler handler) {
3471 mHandler.getLooper().getQueue().addIdleHandler(handler);
3472 }
3473
Jeff Sharkey1b861272011-05-22 00:34:52 -07003474 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3475 final int size = source.size();
3476 for (int i = 0; i < size; i++) {
3477 target.put(source.keyAt(i), true);
3478 }
3479 }
3480
Stuart Scottf1fb3972015-04-02 18:00:02 -07003481 @Override
3482 public void factoryReset(String subscriber) {
3483 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3484
Stuart Scotte3e314d2015-04-20 14:07:45 -07003485 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3486 return;
3487 }
3488
Stuart Scottf1fb3972015-04-02 18:00:02 -07003489 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003490 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003491 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3492 for (NetworkPolicy policy : policies) {
3493 if (policy.template.equals(template)) {
3494 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3495 policy.inferred = false;
3496 policy.clearSnooze();
3497 }
3498 }
3499 setNetworkPolicies(policies);
3500
3501 // Turn restrict background data off
3502 setRestrictBackground(false);
3503
Stuart Scotte3e314d2015-04-20 14:07:45 -07003504 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3505 // Remove app's "restrict background data" flag
3506 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3507 setUidPolicy(uid, POLICY_NONE);
3508 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003509 }
3510 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003511
3512 private class MyPackageMonitor extends PackageMonitor {
3513
3514 @Override
3515 public void onPackageRemoved(String packageName, int uid) {
3516 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3517 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003518 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Leme781ba142016-05-09 16:24:48 -07003519 updateRestrictionRulesForUidLocked(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003520 }
3521 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003522 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003523
3524 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3525
3526 @Override
3527 public void resetUserState(int userId) {
3528 synchronized (mRulesLock) {
3529 boolean changed = removeUserStateLocked(userId, false);
3530 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(userId) || changed;
3531 if (changed) {
3532 writePolicyLocked();
3533 }
3534 }
3535 }
3536 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003537}