blob: abd7ff440499aae26b543c592d680ee012d959a9 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme70c57c22016-03-29 10:45:13 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070052import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
53import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
54import static android.net.NetworkPolicyManager.RULE_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070056import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070057import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070058import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070059import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
60import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
62import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070063import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080064import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070065import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
66import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
67import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
68import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
69import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
70import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
71import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080073
Jeff Sharkey854b2b12012-04-13 16:03:40 -070074import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070076import static com.android.internal.util.XmlUtils.readBooleanAttribute;
77import static com.android.internal.util.XmlUtils.readIntAttribute;
78import static com.android.internal.util.XmlUtils.readLongAttribute;
79import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
80import static com.android.internal.util.XmlUtils.writeIntAttribute;
81import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070082import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070083import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060084
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080086import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070088
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070090import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070092import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070093import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070094import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070095import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import android.app.Notification;
97import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070098import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070099import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700100import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700101import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.Intent;
103import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700104import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700105import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700106import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700107import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700108import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700109import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700110import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700111import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700112import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700114import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700115import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700116import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700117import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700118import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700120import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700121import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700123import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700124import android.net.wifi.WifiConfiguration;
125import android.net.wifi.WifiInfo;
126import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700127import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700128import android.os.Environment;
129import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700130import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700131import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700132import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700133import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700134import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700135import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700136import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700137import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700138import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700139import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600140import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700141import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700142import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700143import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700144import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800145import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700146import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700147import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700148import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700149import android.util.ArrayMap;
150import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700151import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700152import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700153import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700154import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700155import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700156import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700157import android.util.SparseBooleanArray;
158import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700159import android.util.TrustedTime;
160import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161
Jeff Sharkey497e4432011-06-14 17:27:29 -0700162import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800163import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800164import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800165import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700167import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700168import com.android.server.DeviceIdleController;
169import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700170import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800171import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600172
173import libcore.io.IoUtils;
174
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700175import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700176
177import org.xmlpull.v1.XmlPullParser;
178import org.xmlpull.v1.XmlPullParserException;
179import org.xmlpull.v1.XmlSerializer;
180
181import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700182import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700183import java.io.FileInputStream;
184import java.io.FileNotFoundException;
185import java.io.FileOutputStream;
186import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700187import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100188import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189import java.util.ArrayList;
190import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700191import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700192
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700193/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700194 * Service that maintains low-level network policy rules, using
195 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196 * <p>
197 * Derives active rules by combining a given policy with other system status,
198 * and delivers to listeners, such as {@link ConnectivityManager}, for
199 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700200 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700201public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800202 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700203 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700204 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700205
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700206 private static final int VERSION_INIT = 1;
207 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700208 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800209 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800210 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800211 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700212 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700213 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700214 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700215 private static final int VERSION_SWITCH_UID = 10;
216 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700217
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800218 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700219 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700221 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800222 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700223 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700224
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700225 private static final String TAG_POLICY_LIST = "policy-list";
226 private static final String TAG_NETWORK_POLICY = "network-policy";
227 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700228 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800229 private static final String TAG_WHITELIST = "whitelist";
230 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800231 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232
233 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700234 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
236 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700237 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700238 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800239 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private static final String ATTR_WARNING_BYTES = "warningBytes";
241 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700242 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800243 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
244 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800245 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700246 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700247 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700248 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700249 private static final String ATTR_POLICY = "policy";
250
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800251 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800252 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800253 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800254 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700255
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700256 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
257
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700258 private static final int MSG_RULES_CHANGED = 1;
259 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800260 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800261 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700262 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700263 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800264 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700265 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
266 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700267
Jeff Sharkey75279902011-05-24 18:39:45 -0700268 private final Context mContext;
269 private final IActivityManager mActivityManager;
270 private final IPowerManager mPowerManager;
271 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700272 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700273 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700275 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276
277 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700278 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700279 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700280 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700281
Dianne Hackborn497175b2014-07-01 12:56:08 -0700282 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700283
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700284 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700285 volatile boolean mScreenOn;
286 volatile boolean mRestrictBackground;
287 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700288 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700289
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700290 private final boolean mSuppressDefaultPolicy;
291
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700292 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800293 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700294 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700296
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700297 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700298 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700299 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800300 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700301
Jeff Sharkeydc988062015-09-14 10:09:47 -0700302 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
303 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800304 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700305
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700306 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700307 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
308
Jeff Sharkey32566012014-12-02 18:30:14 -0800309 /**
310 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700311 * in power save mode, except device idle (doze) still applies.
312 * TODO: An int array might be sufficient
313 */
314 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
315
316 /**
317 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800318 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700319 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800320 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700321 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700322
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700323 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
324
Felipe Lemeb85a6372016-01-14 16:16:16 -0800325 /**
326 * UIDs that have been white-listed to avoid restricted background.
327 */
328 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
329
Felipe Lemea9505cc2016-02-26 10:28:41 -0800330 /**
331 * UIDs that have been initially white-listed by system to avoid restricted background.
332 */
333 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
334 new SparseBooleanArray();
335
336 /**
337 * UIDs that have been initially white-listed by system to avoid restricted background,
338 * but later revoked by user.
339 */
340 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
341 new SparseBooleanArray();
342
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700343 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800344 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700345 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800346 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700347
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700348 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700349 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700350
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700351 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700353
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600354 /** Higher priority listener before general event dispatch */
355 private INetworkPolicyListener mConnectivityListener;
356
Jeff Sharkey32566012014-12-02 18:30:14 -0800357 private final RemoteCallbackList<INetworkPolicyListener>
358 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700359
Dianne Hackborn497175b2014-07-01 12:56:08 -0700360 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700361
362 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700363
Svet Ganov16a16892015-04-16 10:32:04 -0700364 private final AppOpsManager mAppOps;
365
Felipe Lemeb85a6372016-01-14 16:16:16 -0800366 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800367 private final IPackageManager mIPm;
368
Felipe Lemeb85a6372016-01-14 16:16:16 -0800369
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700370 // TODO: keep whitelist of system-critical services that should never have
371 // rules enforced, such as system, phone, and radio UIDs.
372
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700373 // TODO: migrate notifications to SystemUI
374
Jeff Sharkey75279902011-05-24 18:39:45 -0700375 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700376 IPowerManager powerManager, INetworkStatsService networkStats,
377 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700378 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700379 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700380 }
381
382 private static File getSystemDir() {
383 return new File(Environment.getDataDirectory(), "system");
384 }
385
386 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700387 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700388 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
389 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700390 mContext = checkNotNull(context, "missing context");
391 mActivityManager = checkNotNull(activityManager, "missing activityManager");
392 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700393 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700394 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700395 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700396 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700398 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800399 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700400
Amith Yamasani450a16b2013-09-18 16:28:50 -0700401 HandlerThread thread = new HandlerThread(TAG);
402 thread.start();
403 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700405 mSuppressDefaultPolicy = suppressDefaultPolicy;
406
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700408
409 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800410
411 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700412
413 // Expose private service for system components to use.
414 LocalServices.addService(NetworkPolicyManagerInternal.class,
415 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700416 }
417
418 public void bindConnectivityManager(IConnectivityManager connManager) {
419 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700420 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700421
Jeff Sharkey497e4432011-06-14 17:27:29 -0700422 public void bindNotificationManager(INotificationManager notifManager) {
423 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
424 }
425
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700426 void updatePowerSaveWhitelistLocked() {
427 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700428 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
429 mPowerSaveWhitelistExceptIdleAppIds.clear();
430 if (whitelist != null) {
431 for (int uid : whitelist) {
432 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
433 }
434 }
435 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700436 mPowerSaveWhitelistAppIds.clear();
437 if (whitelist != null) {
438 for (int uid : whitelist) {
439 mPowerSaveWhitelistAppIds.put(uid, true);
440 }
441 }
442 } catch (RemoteException e) {
443 }
444 }
445
Felipe Lemea9505cc2016-02-26 10:28:41 -0800446 /**
447 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
448 * revoke the whitelist.
449 *
450 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
451 */
Felipe Lemea110eec2016-04-29 09:58:06 -0700452 boolean addDefaultRestrictBackgroundWhitelistUidsLocked() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800453 final List<UserInfo> users = mUserManager.getUsers();
454 final int numberUsers = users.size();
455
Felipe Lemea110eec2016-04-29 09:58:06 -0700456 boolean changed = false;
457 for (int i = 0; i < numberUsers; i++) {
458 final UserInfo user = users.get(i);
459 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(user.id) || changed;
460 }
461 return changed;
462 }
463
464 private boolean addDefaultRestrictBackgroundWhitelistUidsLocked(int userId) {
465 final SystemConfig sysConfig = SystemConfig.getInstance();
466 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800467 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
468 boolean changed = false;
469 for (int i = 0; i < allowDataUsage.size(); i++) {
470 final String pkg = allowDataUsage.valueAt(i);
471 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700472 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
473 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800474 final ApplicationInfo app;
475 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700476 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800477 } catch (PackageManager.NameNotFoundException e) {
478 // Should not happen
479 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
480 continue;
481 }
482 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700483 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800484 continue;
485 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700486 final int uid = UserHandle.getUid(userId, app.uid);
487 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
488 if (LOGD)
489 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
490 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800491 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700492 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
493 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
494 + userId + ") to restrict background whitelist");
495 mRestrictBackgroundWhitelistUids.append(uid, true);
496 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800497 }
498 }
499 return changed;
500 }
501
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700502 void updatePowerSaveTempWhitelistLocked() {
503 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700504 // Clear the states of the current whitelist
505 final int N = mPowerSaveTempWhitelistAppIds.size();
506 for (int i = 0; i < N; i++) {
507 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
508 }
509 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700510 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700511 if (whitelist != null) {
512 for (int uid : whitelist) {
513 mPowerSaveTempWhitelistAppIds.put(uid, true);
514 }
515 }
516 } catch (RemoteException e) {
517 }
518 }
519
Amith Yamasani06f08062015-06-12 13:23:33 -0700520 /**
521 * Remove unnecessary entries in the temp whitelist
522 */
523 void purgePowerSaveTempWhitelistLocked() {
524 final int N = mPowerSaveTempWhitelistAppIds.size();
525 for (int i = N - 1; i >= 0; i--) {
526 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
527 mPowerSaveTempWhitelistAppIds.removeAt(i);
528 }
529 }
530 }
531
Jeff Sharkeya4620792011-05-20 15:29:23 -0700532 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700533 if (!isBandwidthControlEnabled()) {
534 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
535 return;
536 }
537
Amith Yamasani15e472352015-04-24 19:06:07 -0700538 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
539
Felipe Lemeb85a6372016-01-14 16:16:16 -0800540 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
541
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700542 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700543 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700544 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
545 mPowerManagerInternal.registerLowPowerModeObserver(
546 new PowerManagerInternal.LowPowerModeListener() {
547 @Override
548 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800549 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700550 synchronized (mRulesLock) {
551 if (mRestrictPower != enabled) {
552 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800553 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700554 updateRulesForGlobalChangeLocked(true);
555 }
556 }
557 }
558 });
559 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700560 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700561
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700562 // read policy from disk
563 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700564
Felipe Lemea110eec2016-04-29 09:58:06 -0700565 if (addDefaultRestrictBackgroundWhitelistUidsLocked()) {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800566 writePolicyLocked();
567 }
568
Jeff Sharkeydc988062015-09-14 10:09:47 -0700569 updateRulesForGlobalChangeLocked(false);
570 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700571 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700572
Jeff Sharkeya4620792011-05-20 15:29:23 -0700573 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700574
Jeff Sharkeya4620792011-05-20 15:29:23 -0700575 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700576 mActivityManager.registerUidObserver(mUidObserver,
577 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700578 mNetworkManager.registerObserver(mAlertObserver);
579 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700580 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700581 }
582
Jeff Sharkeya4620792011-05-20 15:29:23 -0700583 // TODO: traverse existing processes to know foreground state, or have
584 // activitymanager dispatch current state when new observer attached.
585
586 final IntentFilter screenFilter = new IntentFilter();
587 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
588 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700589 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700590
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700591 // listen for changes to power save whitelist
592 final IntentFilter whitelistFilter = new IntentFilter(
593 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
594 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
595
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700596 DeviceIdleController.LocalService deviceIdleService
597 = LocalServices.getService(DeviceIdleController.LocalService.class);
598 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
599
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700600 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900601 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700602 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
603
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700604 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700605 final IntentFilter packageFilter = new IntentFilter();
606 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700607 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700608 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700609
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700610 // listen for UID changes to update policy
611 mContext.registerReceiver(
612 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
613
614 // listen for user changes to update policy
615 final IntentFilter userFilter = new IntentFilter();
616 userFilter.addAction(ACTION_USER_ADDED);
617 userFilter.addAction(ACTION_USER_REMOVED);
618 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
619
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700620 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700621 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
622 mContext.registerReceiver(
623 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
624
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700625 // listen for restrict background changes from notifications
626 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
627 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
628
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800629 // listen for snooze warning from notifications
630 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
631 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
632 MANAGE_NETWORK_POLICY, mHandler);
633
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700634 // listen for configured wifi networks to be removed
635 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700636 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700637
638 // listen for wifi state changes to catch metered hint
639 final IntentFilter wifiStateFilter = new IntentFilter(
640 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700641 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700642
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700643 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700644
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700645 }
646
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700647 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700648 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700649 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700650 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700651 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700652 }
653
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700654 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700655 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700656 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700657 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700658 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700659
660 @Override public void onUidActive(int uid) throws RemoteException {
661 }
662
663 @Override public void onUidIdle(int uid) throws RemoteException {
664 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700665 };
666
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700667 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700668 @Override
669 public void onReceive(Context context, Intent intent) {
670 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
671 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700672 updatePowerSaveWhitelistLocked();
673 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700674 }
675 }
676 };
677
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700678 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
679 @Override
680 public void run() {
681 synchronized (mRulesLock) {
682 updatePowerSaveTempWhitelistLocked();
683 updateRulesForTempWhitelistChangeLocked();
684 purgePowerSaveTempWhitelistLocked();
685 }
686 }
687 };
688
689 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700690 @Override
691 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800692 // screen-related broadcasts are protected by system, no need
693 // for permissions check.
694 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700695 }
696 };
697
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700698 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700699 @Override
700 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700701 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700702
703 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700704 final int uid = intent.getIntExtra(EXTRA_UID, -1);
705 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700706
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700707 if (ACTION_PACKAGE_ADDED.equals(action)) {
708 // update rules for UID, since it might be subject to
709 // global background data policy
710 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
711 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700712 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700713 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700714 }
715 }
716 };
717
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700718 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700719 @Override
720 public void onReceive(Context context, Intent intent) {
721 // on background handler thread, and UID_REMOVED is protected
722
723 final int uid = intent.getIntExtra(EXTRA_UID, -1);
724 if (uid == -1) return;
725
726 // remove any policy and update rules to clean up
727 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
728 synchronized (mRulesLock) {
729 mUidPolicy.delete(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -0700730 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700731 writePolicyLocked();
732 }
733 }
734 };
735
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700736 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700737 @Override
738 public void onReceive(Context context, Intent intent) {
739 // on background handler thread, and USER_ADDED and USER_REMOVED
740 // broadcasts are protected
741
742 final String action = intent.getAction();
743 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
744 if (userId == -1) return;
745
Amith Yamasani15e472352015-04-24 19:06:07 -0700746 switch (action) {
747 case ACTION_USER_REMOVED:
748 case ACTION_USER_ADDED:
749 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800750 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700751 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemed17fda42016-04-29 11:12:45 -0700752 removeUserStateLocked(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700753 if (action == ACTION_USER_ADDED) {
754 // Add apps that are whitelisted by default.
755 addDefaultRestrictBackgroundWhitelistUidsLocked(userId);
756 }
757 // Update global restrict for that user
Amith Yamasani15e472352015-04-24 19:06:07 -0700758 updateRulesForGlobalChangeLocked(true);
759 }
760 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700761 }
762 }
763 };
764
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700765 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700766 * Receiver that watches for {@link INetworkStatsService} updates, which we
767 * use to check against {@link NetworkPolicy#warningBytes}.
768 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700769 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700770 @Override
771 public void onReceive(Context context, Intent intent) {
772 // on background handler thread, and verified
773 // READ_NETWORK_USAGE_HISTORY permission above.
774
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800775 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700776 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700777 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700778 updateNotificationsLocked();
779 }
780 }
781 };
782
783 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700784 * Receiver that watches for {@link Notification} control of
785 * {@link #mRestrictBackground}.
786 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700787 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700788 @Override
789 public void onReceive(Context context, Intent intent) {
790 // on background handler thread, and verified MANAGE_NETWORK_POLICY
791 // permission above.
792
793 setRestrictBackground(false);
794 }
795 };
796
797 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800798 * Receiver that watches for {@link Notification} control of
799 * {@link NetworkPolicy#lastWarningSnooze}.
800 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700801 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800802 @Override
803 public void onReceive(Context context, Intent intent) {
804 // on background handler thread, and verified MANAGE_NETWORK_POLICY
805 // permission above.
806
807 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
808 performSnooze(template, TYPE_WARNING);
809 }
810 };
811
812 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700813 * Receiver that watches for {@link WifiConfiguration} to be changed.
814 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700815 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700816 @Override
817 public void onReceive(Context context, Intent intent) {
818 // on background handler thread, and verified CONNECTIVITY_INTERNAL
819 // permission above.
820
821 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
822 if (reason == CHANGE_REASON_REMOVED) {
823 final WifiConfiguration config = intent.getParcelableExtra(
824 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700825 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800826 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700827 synchronized (mRulesLock) {
828 if (mNetworkPolicy.containsKey(template)) {
829 mNetworkPolicy.remove(template);
830 writePolicyLocked();
831 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700832 }
833 }
834 }
835 }
836 };
837
838 /**
839 * Receiver that watches {@link WifiInfo} state changes to infer metered
840 * state. Ignores hints when policy is user-defined.
841 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700842 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700843 @Override
844 public void onReceive(Context context, Intent intent) {
845 // on background handler thread, and verified CONNECTIVITY_INTERNAL
846 // permission above.
847
848 // ignore when not connected
849 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
850 if (!netInfo.isConnected()) return;
851
852 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
853 final boolean meteredHint = info.getMeteredHint();
854
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800855 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700856 synchronized (mRulesLock) {
857 NetworkPolicy policy = mNetworkPolicy.get(template);
858 if (policy == null && meteredHint) {
859 // policy doesn't exist, and AP is hinting that it's
860 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800861 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700862 addNetworkPolicyLocked(policy);
863
864 } else if (policy != null && policy.inferred) {
865 // policy exists, and was inferred: update its current
866 // metered state.
867 policy.metered = meteredHint;
868
869 // since this is inferred for each wifi session, just update
870 // rules without persisting.
871 updateNetworkRulesLocked();
872 }
873 }
874 }
875 };
876
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800877 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
878 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
879 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
880 metered, true);
881 }
882
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700883 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700884 * Observer that watches for {@link INetworkManagementService} alerts.
885 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700886 final private INetworkManagementEventObserver mAlertObserver
887 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700888 @Override
889 public void limitReached(String limitName, String iface) {
890 // only someone like NMS should be calling us
891 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
892
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800893 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
894 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700895 }
896 }
897 };
898
899 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700900 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
901 * to show visible notifications as needed.
902 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700903 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700904 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
905
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700906 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700907 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700908 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700909
910 // TODO: when switching to kernel notifications, compute next future
911 // cycle boundary to recompute notifications.
912
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700913 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800914 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700915 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
916 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700917 // ignore policies that aren't relevant to user
918 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700919 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920
Jeff Sharkey497e4432011-06-14 17:27:29 -0700921 final long start = computeLastCycleBoundary(currentTime, policy);
922 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700923 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700924
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700925 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800926 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
928 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700929 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
930 notifyOverLimitLocked(policy.template);
931 }
932
Jeff Sharkey497e4432011-06-14 17:27:29 -0700933 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700934 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800936 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700937 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 }
939 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700940 }
941
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700942 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700943 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
944 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 if (!mActiveNotifs.contains(tag)) {
946 cancelNotification(tag);
947 }
948 }
949 }
950
951 /**
952 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700953 * current device state, such as when
954 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
955 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700956 */
957 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800958 if (template.isMatchRuleMobile()) {
959 final TelephonyManager tele = TelephonyManager.from(mContext);
960 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700961
Jeff Sharkey32566012014-12-02 18:30:14 -0800962 // Mobile template is relevant when any active subscriber matches
963 final int[] subIds = sub.getActiveSubscriptionIdList();
964 for (int subId : subIds) {
965 final String subscriberId = tele.getSubscriberId(subId);
966 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700967 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800968 if (template.matches(probeIdent)) {
969 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700970 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800971 }
972 return false;
973 } else {
974 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700975 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 }
977
978 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700979 * Notify that given {@link NetworkTemplate} is over
980 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
981 */
982 private void notifyOverLimitLocked(NetworkTemplate template) {
983 if (!mOverLimitNotified.contains(template)) {
984 mContext.startActivity(buildNetworkOverLimitIntent(template));
985 mOverLimitNotified.add(template);
986 }
987 }
988
989 private void notifyUnderLimitLocked(NetworkTemplate template) {
990 mOverLimitNotified.remove(template);
991 }
992
993 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700994 * Build unique tag that identifies an active {@link NetworkPolicy}
995 * notification of a specific type, like {@link #TYPE_LIMIT}.
996 */
997 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700998 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700999 }
1000
1001 /**
1002 * Show notification for combined {@link NetworkPolicy} and specific type,
1003 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1004 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001005 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006 final String tag = buildNotificationTag(policy, type);
1007 final Notification.Builder builder = new Notification.Builder(mContext);
1008 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001009 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001010 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001011 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012
1013 final Resources res = mContext.getResources();
1014 switch (type) {
1015 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001016 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001017 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001018
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001019 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 builder.setTicker(title);
1021 builder.setContentTitle(title);
1022 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001023
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001024 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1025 builder.setDeleteIntent(PendingIntent.getBroadcast(
1026 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1027
1028 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001029 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001030 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1031
Jeff Sharkey497e4432011-06-14 17:27:29 -07001032 break;
1033 }
1034 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001035 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1036
1037 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001038 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001039 switch (policy.template.getMatchRule()) {
1040 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001043 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001047 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001049 case MATCH_WIFI:
1050 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001051 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 break;
1053 default:
1054 title = null;
1055 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001056 }
1057
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001058 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001059 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001060 builder.setTicker(title);
1061 builder.setContentTitle(title);
1062 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001063
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1065 builder.setContentIntent(PendingIntent.getActivity(
1066 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1067 break;
1068 }
1069 case TYPE_LIMIT_SNOOZED: {
1070 final long overBytes = totalBytes - policy.limitBytes;
1071 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1072 Formatter.formatFileSize(mContext, overBytes));
1073
1074 final CharSequence title;
1075 switch (policy.template.getMatchRule()) {
1076 case MATCH_MOBILE_3G_LOWER:
1077 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1078 break;
1079 case MATCH_MOBILE_4G:
1080 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1081 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001083 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1084 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001085 case MATCH_WIFI:
1086 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1087 break;
1088 default:
1089 title = null;
1090 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001091 }
1092
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001093 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001094 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 builder.setTicker(title);
1096 builder.setContentTitle(title);
1097 builder.setContentText(body);
1098
1099 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001100 builder.setContentIntent(PendingIntent.getActivity(
1101 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 break;
1103 }
1104 }
1105
1106 // TODO: move to NotificationManager once we can mock it
1107 try {
1108 final String packageName = mContext.getPackageName();
1109 final int[] idReceived = new int[1];
1110 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001111 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001112 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001113 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001115 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 }
1117 }
1118
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001119 private void cancelNotification(String tag) {
1120 // TODO: move to NotificationManager once we can mock it
1121 try {
1122 final String packageName = mContext.getPackageName();
1123 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001124 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001125 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001126 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001127 }
1128 }
1129
1130 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001131 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001132 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001133 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001134 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001135 @Override
1136 public void onReceive(Context context, Intent intent) {
1137 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1138 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001139
1140 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001141 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001142 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001143 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001145 updateNetworkRulesLocked();
1146 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001147 }
1148 }
1149 };
1150
1151 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001152 * Proactively control network data connections when they exceed
1153 * {@link NetworkPolicy#limitBytes}.
1154 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001155 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1157
1158 // TODO: reset any policy-disabled networks when any policy is removed
1159 // completely, which is currently rare case.
1160
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001161 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001162 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1163 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001164 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001165 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001166 setNetworkTemplateEnabled(policy.template, true);
1167 continue;
1168 }
1169
1170 final long start = computeLastCycleBoundary(currentTime, policy);
1171 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001172 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001173
1174 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001175 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1176 && policy.lastLimitSnooze < start;
1177 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001178
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001179 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001180 }
1181 }
1182
1183 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001184 * Proactively disable networks that match the given
1185 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 */
1187 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001188 // TODO: reach into ConnectivityManager to proactively disable bringing
1189 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001190 }
1191
1192 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001193 * Examine all connected {@link NetworkState}, looking for
1194 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1195 * remaining quota based on usage cycle and historical stats.
1196 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001197 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001198 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001199
1200 final NetworkState[] states;
1201 try {
1202 states = mConnManager.getAllNetworkState();
1203 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001204 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 return;
1206 }
1207
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001208 // First, generate identities of all connected networks so we can
1209 // quickly compare them against all defined policies below.
1210 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001211 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001213 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001215
1216 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001217 if (baseIface != null) {
1218 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001219 }
1220
1221 // Stacked interfaces are considered to have same identity as
1222 // their parent network.
1223 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1224 for (LinkProperties stackedLink : stackedLinks) {
1225 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001226 if (stackedIface != null) {
1227 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001228 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001229 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001230 }
1231 }
1232
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001233 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001234 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001235 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001236 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001237 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001238
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001240 for (int j = connIdents.size() - 1; j >= 0; j--) {
1241 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1242 if (policy.template.matches(ident.second)) {
1243 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001244 }
1245 }
1246
1247 if (ifaceList.size() > 0) {
1248 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001249 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001250 }
1251 }
1252
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001253 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001254 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001255
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 // apply each policy that we found ifaces for; compute remaining data
1257 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001258 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001259 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1260 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1261 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001262
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001263 final long start;
1264 final long totalBytes;
1265 if (policy.hasCycle()) {
1266 start = computeLastCycleBoundary(currentTime, policy);
1267 totalBytes = getTotalBytes(policy.template, start, currentTime);
1268 } else {
1269 start = Long.MAX_VALUE;
1270 totalBytes = 0;
1271 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001272
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001273 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001274 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275 }
1276
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001277 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001278 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001279 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001280 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001281 if (!hasLimit) {
1282 // metered network, but no policy limit; we still need to
1283 // restrict apps, so push really high quota.
1284 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001285 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001286 // snoozing past quota, but we still need to restrict apps,
1287 // so push really high quota.
1288 quotaBytes = Long.MAX_VALUE;
1289 } else {
1290 // remaining "quota" bytes are based on total usage in
1291 // current cycle. kernel doesn't like 0-byte rules, so we
1292 // set 1-byte quota and disable the radio later.
1293 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1294 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001295
1296 if (ifaces.length > 1) {
1297 // TODO: switch to shared quota once NMS supports
1298 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001299 }
1300
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001301 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001302 // long quotaBytes split up into two ints to fit in message
1303 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1304 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1305 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001306 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001307 }
1308 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001309
1310 // keep track of lowest warning or limit of active policies
1311 if (hasWarning && policy.warningBytes < lowestRule) {
1312 lowestRule = policy.warningBytes;
1313 }
1314 if (hasLimit && policy.limitBytes < lowestRule) {
1315 lowestRule = policy.limitBytes;
1316 }
1317 }
1318
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001319 for (int i = connIfaces.size()-1; i >= 0; i--) {
1320 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001321 // long quotaBytes split up into two ints to fit in message
1322 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1323 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1324 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001325 newMeteredIfaces.add(iface);
1326 }
1327
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001328 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001329
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001330 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001331 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1332 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001333 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001334 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1335 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001336 }
1337 }
1338 mMeteredIfaces = newMeteredIfaces;
1339
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001340 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001341 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001342 }
1343
1344 /**
1345 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1346 * have at least a default mobile policy defined.
1347 */
1348 private void ensureActiveMobilePolicyLocked() {
1349 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001350 if (mSuppressDefaultPolicy) return;
1351
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001352 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001353 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001354
Jeff Sharkey32566012014-12-02 18:30:14 -08001355 final int[] subIds = sub.getActiveSubscriptionIdList();
1356 for (int subId : subIds) {
1357 final String subscriberId = tele.getSubscriberId(subId);
1358 ensureActiveMobilePolicyLocked(subscriberId);
1359 }
1360 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001361
Jeff Sharkey32566012014-12-02 18:30:14 -08001362 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1363 // Poke around to see if we already have a policy
1364 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001365 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001366 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1367 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1368 if (template.matches(probeIdent)) {
1369 if (LOGD) {
1370 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1371 + NetworkIdentity.scrubSubscriberId(subscriberId));
1372 }
1373 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001374 }
1375 }
1376
Jeff Sharkey32566012014-12-02 18:30:14 -08001377 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1378 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001379
Jeff Sharkey32566012014-12-02 18:30:14 -08001380 // Build default mobile policy, and assume usage cycle starts today
1381 final long warningBytes = mContext.getResources().getInteger(
1382 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001383
Jeff Sharkey32566012014-12-02 18:30:14 -08001384 final Time time = new Time();
1385 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001386
Jeff Sharkey32566012014-12-02 18:30:14 -08001387 final int cycleDay = time.monthDay;
1388 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001389
Jeff Sharkey32566012014-12-02 18:30:14 -08001390 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1391 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1392 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1393 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001394 }
1395
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001396 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001397 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001398
1399 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001400 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001401 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001402
1403 FileInputStream fis = null;
1404 try {
1405 fis = mPolicyFile.openRead();
1406 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001407 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001408
1409 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001410 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001411 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001412 while ((type = in.next()) != END_DOCUMENT) {
1413 final String tag = in.getName();
1414 if (type == START_TAG) {
1415 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001416 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001417 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001418 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1419 mRestrictBackground = readBooleanAttribute(
1420 in, ATTR_RESTRICT_BACKGROUND);
1421 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001422 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001423 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001424 if (mRestrictBackground != oldValue) {
1425 // Some early services may have read the default value,
1426 // so notify them that it's changed
1427 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1428 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1429 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001430
1431 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1432 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1433 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001434 final String networkId;
1435 if (version >= VERSION_ADDED_NETWORK_ID) {
1436 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1437 } else {
1438 networkId = null;
1439 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001440 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001441 final String cycleTimezone;
1442 if (version >= VERSION_ADDED_TIMEZONE) {
1443 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1444 } else {
1445 cycleTimezone = Time.TIMEZONE_UTC;
1446 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001447 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1448 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001449 final long lastLimitSnooze;
1450 if (version >= VERSION_SPLIT_SNOOZE) {
1451 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1452 } else if (version >= VERSION_ADDED_SNOOZE) {
1453 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001454 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001455 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001456 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001457 final boolean metered;
1458 if (version >= VERSION_ADDED_METERED) {
1459 metered = readBooleanAttribute(in, ATTR_METERED);
1460 } else {
1461 switch (networkTemplate) {
1462 case MATCH_MOBILE_3G_LOWER:
1463 case MATCH_MOBILE_4G:
1464 case MATCH_MOBILE_ALL:
1465 metered = true;
1466 break;
1467 default:
1468 metered = false;
1469 }
1470 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001471 final long lastWarningSnooze;
1472 if (version >= VERSION_SPLIT_SNOOZE) {
1473 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1474 } else {
1475 lastWarningSnooze = SNOOZE_NEVER;
1476 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001477 final boolean inferred;
1478 if (version >= VERSION_ADDED_INFERRED) {
1479 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1480 } else {
1481 inferred = false;
1482 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483
Jeff Sharkey32566012014-12-02 18:30:14 -08001484 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1485 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001486 if (template.isPersistable()) {
1487 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1488 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1489 lastLimitSnooze, metered, inferred));
1490 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001491
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001492 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493 final int uid = readIntAttribute(in, ATTR_UID);
1494 final int policy = readIntAttribute(in, ATTR_POLICY);
1495
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001496 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001497 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001498 } else {
1499 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1500 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001501 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001502 final int appId = readIntAttribute(in, ATTR_APP_ID);
1503 final int policy = readIntAttribute(in, ATTR_POLICY);
1504
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001505 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001506 // app policy is deprecated so this is only used in pre system user split.
1507 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001509 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001510 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001511 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001512 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001513 } else if (TAG_WHITELIST.equals(tag)) {
1514 insideWhitelist = true;
1515 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1516 final int uid = readIntAttribute(in, ATTR_UID);
1517 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001518 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1519 final int uid = readIntAttribute(in, ATTR_UID);
1520 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001521 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001522 } else if (type == END_TAG) {
1523 if (TAG_WHITELIST.equals(tag)) {
1524 insideWhitelist = false;
1525 }
1526
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001527 }
1528 }
1529
1530 } catch (FileNotFoundException e) {
1531 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001532 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001533 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001534 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001535 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001536 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001537 } finally {
1538 IoUtils.closeQuietly(fis);
1539 }
1540 }
1541
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001542 /**
1543 * Upgrade legacy background data flags, notifying listeners of one last
1544 * change to always-true.
1545 */
1546 private void upgradeLegacyBackgroundData() {
1547 mRestrictBackground = Settings.Secure.getInt(
1548 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1549
1550 // kick off one last broadcast if restricted
1551 if (mRestrictBackground) {
1552 final Intent broadcast = new Intent(
1553 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001554 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001555 }
1556 }
1557
Dianne Hackborn497175b2014-07-01 12:56:08 -07001558 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001559 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560
1561 FileOutputStream fos = null;
1562 try {
1563 fos = mPolicyFile.startWrite();
1564
1565 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001566 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 out.startDocument(null, true);
1568
1569 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001570 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001571 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001572
1573 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001574 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1575 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001576 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001577 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001578
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001580 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1581 final String subscriberId = template.getSubscriberId();
1582 if (subscriberId != null) {
1583 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001585 final String networkId = template.getNetworkId();
1586 if (networkId != null) {
1587 out.attribute(null, ATTR_NETWORK_ID, networkId);
1588 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001590 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001591 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1592 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001593 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1594 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001595 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001596 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001597 out.endTag(null, TAG_NETWORK_POLICY);
1598 }
1599
1600 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001601 for (int i = 0; i < mUidPolicy.size(); i++) {
1602 final int uid = mUidPolicy.keyAt(i);
1603 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001604
Jeff Sharkey497e4432011-06-14 17:27:29 -07001605 // skip writing empty policies
1606 if (policy == POLICY_NONE) continue;
1607
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001608 out.startTag(null, TAG_UID_POLICY);
1609 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001611 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612 }
1613
1614 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001615
1616 // write all whitelists
1617 out.startTag(null, TAG_WHITELIST);
1618
1619 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001620 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001621 for (int i = 0; i < size; i++) {
1622 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1623 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1624 writeIntAttribute(out, ATTR_UID, uid);
1625 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1626 }
1627
Felipe Lemea9505cc2016-02-26 10:28:41 -08001628 // revoked restrict background whitelist
1629 size = mRestrictBackgroundWhitelistRevokedUids.size();
1630 for (int i = 0; i < size; i++) {
1631 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1632 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1633 writeIntAttribute(out, ATTR_UID, uid);
1634 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1635 }
1636
Felipe Lemeb85a6372016-01-14 16:16:16 -08001637 out.endTag(null, TAG_WHITELIST);
1638
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639 out.endDocument();
1640
1641 mPolicyFile.finishWrite(fos);
1642 } catch (IOException e) {
1643 if (fos != null) {
1644 mPolicyFile.failWrite(fos);
1645 }
1646 }
1647 }
1648
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001649 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001650 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001652
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 if (!UserHandle.isApp(uid)) {
1654 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001655 }
1656
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001657 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001658 final long token = Binder.clearCallingIdentity();
1659 try {
1660 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1661 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001662 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001663 }
1664 } finally {
1665 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001666 }
1667 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001668 }
1669
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001670 @Override
1671 public void addUidPolicy(int uid, int policy) {
1672 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001673
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001674 if (!UserHandle.isApp(uid)) {
1675 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1676 }
1677
1678 synchronized (mRulesLock) {
1679 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1680 policy |= oldPolicy;
1681 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001682 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001683 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001684 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001685 }
1686
1687 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001688 public void removeUidPolicy(int uid, int policy) {
1689 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1690
1691 if (!UserHandle.isApp(uid)) {
1692 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1693 }
1694
1695 synchronized (mRulesLock) {
1696 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1697 policy = oldPolicy & ~policy;
1698 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001699 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001700 }
1701 }
1702 }
1703
Felipe Leme923845f2016-03-02 13:42:48 -08001704 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1705 setUidPolicyUncheckedLocked(uid, policy, persist);
1706
1707 // Checks if app was added or removed to the blacklist.
1708 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1709 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001710 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001711 .sendToTarget();
1712 }
1713 }
1714
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001715 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1716 mUidPolicy.put(uid, policy);
1717
1718 // uid policy changed, recompute rules and persist policy.
Felipe Lemef28983d2016-03-25 12:18:23 -07001719 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001720 if (persist) {
1721 writePolicyLocked();
1722 }
1723 }
1724
1725 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001726 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001727 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1728
Jeff Sharkeya4620792011-05-20 15:29:23 -07001729 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001730 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001731 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001732 }
1733
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001734 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001735 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001736 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1737
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001738 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001739 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001740 for (int i = 0; i < mUidPolicy.size(); i++) {
1741 final int uid = mUidPolicy.keyAt(i);
1742 final int uidPolicy = mUidPolicy.valueAt(i);
1743 if (uidPolicy == policy) {
1744 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001745 }
1746 }
1747 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001748 return uids;
1749 }
1750
1751 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001752 * Removes any persistable state associated with given {@link UserHandle}, persisting
1753 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001754 */
Felipe Lemed17fda42016-04-29 11:12:45 -07001755 boolean removeUserStateLocked(int userId, boolean writePolicy) {
1756
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001757 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001758 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001759
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001760 // Remove entries from restricted background UID whitelist
1761 int[] wlUids = new int[0];
1762 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1763 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1764 if (UserHandle.getUserId(uid) == userId) {
1765 wlUids = appendInt(wlUids, uid);
1766 }
1767 }
1768
1769 if (wlUids.length > 0) {
1770 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001771 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001772 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001773 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001774 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001775
1776 // Remove entries from revoked default restricted background UID whitelist
1777 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1778 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1779 if (UserHandle.getUserId(uid) == userId) {
1780 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001781 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001782 }
1783 }
1784
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001785 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001786 int[] uids = new int[0];
1787 for (int i = 0; i < mUidPolicy.size(); i++) {
1788 final int uid = mUidPolicy.keyAt(i);
1789 if (UserHandle.getUserId(uid) == userId) {
1790 uids = appendInt(uids, uid);
1791 }
1792 }
1793
1794 if (uids.length > 0) {
1795 for (int uid : uids) {
1796 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001797 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001798 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001799 }
1800
Felipe Leme76010a32016-03-17 13:03:11 -07001801 updateRulesForGlobalChangeLocked(true);
1802
Felipe Lemed17fda42016-04-29 11:12:45 -07001803 if (writePolicy && changed) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001804 writePolicyLocked();
1805 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001806 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001807 }
1808
1809 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001810 public void setConnectivityListener(INetworkPolicyListener listener) {
1811 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1812 if (mConnectivityListener != null) {
1813 throw new IllegalStateException("Connectivity listener already registered");
1814 }
1815 mConnectivityListener = listener;
1816 }
1817
1818 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001820 // TODO: create permission for observing network policy
1821 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001822 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001823 }
1824
1825 @Override
1826 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001827 // TODO: create permission for observing network policy
1828 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001829 mListeners.unregister(listener);
1830 }
1831
Jeff Sharkey1b861272011-05-22 00:34:52 -07001832 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001833 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001834 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1835
Felipe Leme6a05eee2016-02-19 14:43:51 -08001836 final long token = Binder.clearCallingIdentity();
1837 try {
1838 maybeRefreshTrustedTime();
1839 synchronized (mRulesLock) {
1840 normalizePoliciesLocked(policies);
1841 updateNetworkEnabledLocked();
1842 updateNetworkRulesLocked();
1843 updateNotificationsLocked();
1844 writePolicyLocked();
1845 }
1846 } finally {
1847 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001848 }
1849 }
1850
Dianne Hackborn497175b2014-07-01 12:56:08 -07001851 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001852 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001853 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1854 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001855 }
1856
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001857 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001858 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001859 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001860 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001861 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1862 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1863 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001864 } catch (SecurityException e) {
1865 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001866
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001867 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1868 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1869 return new NetworkPolicy[0];
1870 }
Svet Ganov16a16892015-04-16 10:32:04 -07001871 }
1872
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001873 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001874 final int size = mNetworkPolicy.size();
1875 final NetworkPolicy[] policies = new NetworkPolicy[size];
1876 for (int i = 0; i < size; i++) {
1877 policies[i] = mNetworkPolicy.valueAt(i);
1878 }
1879 return policies;
1880 }
1881 }
1882
1883 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001884 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001885 }
1886
1887 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1888 final TelephonyManager tele = TelephonyManager.from(mContext);
1889 final String[] merged = tele.getMergedSubscriberIds();
1890
1891 mNetworkPolicy.clear();
1892 for (NetworkPolicy policy : policies) {
1893 // When two normalized templates conflict, prefer the most
1894 // restrictive policy
1895 policy.template = NetworkTemplate.normalize(policy.template, merged);
1896 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1897 if (existing == null || existing.compareTo(policy) > 0) {
1898 if (existing != null) {
1899 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1900 }
1901 mNetworkPolicy.put(policy.template, policy);
1902 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001903 }
1904 }
1905
1906 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001907 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001908 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001909
1910 final long token = Binder.clearCallingIdentity();
1911 try {
1912 performSnooze(template, TYPE_LIMIT);
1913 } finally {
1914 Binder.restoreCallingIdentity(token);
1915 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001916 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001917
Dianne Hackborn497175b2014-07-01 12:56:08 -07001918 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001919 maybeRefreshTrustedTime();
1920 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001921 synchronized (mRulesLock) {
1922 // find and snooze local policy that matches
1923 final NetworkPolicy policy = mNetworkPolicy.get(template);
1924 if (policy == null) {
1925 throw new IllegalArgumentException("unable to find policy for " + template);
1926 }
1927
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001928 switch (type) {
1929 case TYPE_WARNING:
1930 policy.lastWarningSnooze = currentTime;
1931 break;
1932 case TYPE_LIMIT:
1933 policy.lastLimitSnooze = currentTime;
1934 break;
1935 default:
1936 throw new IllegalArgumentException("unexpected type");
1937 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001938
Jeff Sharkey32566012014-12-02 18:30:14 -08001939 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001940 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001941 updateNetworkRulesLocked();
1942 updateNotificationsLocked();
1943 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001944 }
1945 }
1946
1947 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001948 public void onTetheringChanged(String iface, boolean tethering) {
1949 // No need to enforce permission because setRestrictBackground() will do it.
1950 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1951 synchronized (mRulesLock) {
1952 if (mRestrictBackground && tethering) {
1953 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1954 setRestrictBackground(false);
1955 }
1956 }
1957 }
1958
1959 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001960 public void setRestrictBackground(boolean restrictBackground) {
1961 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001962 final long token = Binder.clearCallingIdentity();
1963 try {
1964 maybeRefreshTrustedTime();
1965 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001966 if (restrictBackground == mRestrictBackground) {
1967 // Ideally, UI should never allow this scenario...
1968 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1969 return;
1970 }
1971 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001972 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001973
Felipe Leme6a05eee2016-02-19 14:43:51 -08001974 } finally {
1975 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001976 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001977
1978 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1979 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001980 }
1981
Felipe Leme70c57c22016-03-29 10:45:13 -07001982 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1983 final boolean oldRestrictBackground = mRestrictBackground;
1984 mRestrictBackground = restrictBackground;
1985 // Must whitelist foreground apps before turning data saver mode on.
1986 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1987 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
1988 updateRulesForRestrictBackgroundLocked();
1989 try {
1990 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
1991 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
1992 mRestrictBackground = oldRestrictBackground;
1993 // TODO: if it knew the foreground apps (see TODO above), it could call
1994 // updateRulesForRestrictBackgroundLocked() again to restore state.
1995 return;
1996 }
1997 } catch (RemoteException e) {
1998 // ignored; service lives in system_server
1999 }
2000 updateNotificationsLocked();
2001 writePolicyLocked();
2002 }
2003
Jeff Sharkey46645002011-07-27 21:11:21 -07002004 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002005 public void addRestrictBackgroundWhitelistedUid(int uid) {
2006 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002007 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002008 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002009 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002010 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002011 if (oldStatus) {
2012 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2013 return;
2014 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002015 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002016 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002017 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002018 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2019 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2020 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2021 + " from revoked restrict background whitelist");
2022 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2023 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002024 if (needFirewallRules) {
2025 // Only update firewall rules if necessary...
2026 updateRuleForRestrictBackgroundLocked(uid);
2027 }
2028 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08002029 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002030 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002031 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
2032 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2033 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002034 }
2035
2036 @Override
2037 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2038 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002039 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002040 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002041 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002042 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002043 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2044 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002045 }
2046
Felipe Leme70c57c22016-03-29 10:45:13 -07002047 /**
2048 * Removes a uid from the restricted background whitelist, returning whether its current
2049 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2050 */
2051 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2052 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002053 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002054 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002055 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2056 return false;
2057 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002058 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002059 if (oldStatus) {
2060 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2061 mRestrictBackgroundWhitelistUids.delete(uid);
2062 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002063 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2064 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2065 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2066 + " to revoked restrict background whitelist");
2067 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2068 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002069 if (needFirewallRules) {
2070 // Only update firewall rules if necessary...
2071 updateRuleForRestrictBackgroundLocked(uid, uidDeleted);
2072 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002073 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002074 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002075 writePolicyLocked();
2076 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002077 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2078 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002079 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002080 }
2081
2082 @Override
2083 public int[] getRestrictBackgroundWhitelistedUids() {
2084 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2085 synchronized (mRulesLock) {
2086 final int size = mRestrictBackgroundWhitelistUids.size();
2087 final int[] whitelist = new int[size];
2088 for (int i = 0; i < size; i++) {
2089 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2090 }
2091 if (LOGV) {
2092 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2093 + mRestrictBackgroundWhitelistUids);
2094 }
2095 return whitelist;
2096 }
2097 }
2098
2099 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002100 public int getRestrictBackgroundByCaller() {
2101 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2102 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002103
Felipe Leme1b103232016-01-22 09:44:57 -08002104 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002105 // Must clear identity because getUidPolicy() is restricted to system.
2106 final long token = Binder.clearCallingIdentity();
2107 final int policy;
2108 try {
2109 policy = getUidPolicy(uid);
2110 } finally {
2111 Binder.restoreCallingIdentity(token);
2112 }
2113 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2114 // App is blacklisted.
2115 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2116 }
Felipe Leme1b103232016-01-22 09:44:57 -08002117 if (!mRestrictBackground) {
2118 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2119 }
2120 return mRestrictBackgroundWhitelistUids.get(uid)
2121 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2122 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2123 }
2124 }
2125
2126 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002127 public boolean getRestrictBackground() {
2128 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2129
2130 synchronized (mRulesLock) {
2131 return mRestrictBackground;
2132 }
2133 }
2134
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002135 @Override
2136 public void setDeviceIdleMode(boolean enabled) {
2137 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2138
2139 synchronized (mRulesLock) {
2140 if (mDeviceIdleMode != enabled) {
2141 mDeviceIdleMode = enabled;
2142 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002143 // Device idle change means we need to rebuild rules for all
2144 // known apps, so do a global refresh.
2145 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002146 }
2147 if (enabled) {
2148 EventLogTags.writeDeviceIdleOnPhase("net");
2149 } else {
2150 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002151 }
2152 }
2153 }
2154 }
2155
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002156 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002157 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2158 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002159 if (policy.template.matches(ident)) {
2160 return policy;
2161 }
2162 }
2163 return null;
2164 }
2165
2166 @Override
2167 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2168 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2169
2170 // only returns usage summary, so we don't require caller to have
2171 // READ_NETWORK_USAGE_HISTORY.
2172 final long token = Binder.clearCallingIdentity();
2173 try {
2174 return getNetworkQuotaInfoUnchecked(state);
2175 } finally {
2176 Binder.restoreCallingIdentity(token);
2177 }
2178 }
2179
2180 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2181 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2182
2183 final NetworkPolicy policy;
2184 synchronized (mRulesLock) {
2185 policy = findPolicyForNetworkLocked(ident);
2186 }
2187
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002188 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002189 // missing policy means we can't derive useful quota info
2190 return null;
2191 }
2192
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002193 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002194
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002195 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002196 final long start = computeLastCycleBoundary(currentTime, policy);
2197 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002198 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002199
2200 // report soft and hard limits under policy
2201 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2202 : NetworkQuotaInfo.NO_LIMIT;
2203 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2204 : NetworkQuotaInfo.NO_LIMIT;
2205
2206 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2207 }
2208
Jeff Sharkey46645002011-07-27 21:11:21 -07002209 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002210 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002211 if (state.networkInfo == null) {
2212 return false;
2213 }
2214
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002215 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2216
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002217 // roaming networks are always considered metered
2218 if (ident.getRoaming()) {
2219 return true;
2220 }
2221
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002222 final NetworkPolicy policy;
2223 synchronized (mRulesLock) {
2224 policy = findPolicyForNetworkLocked(ident);
2225 }
2226
2227 if (policy != null) {
2228 return policy.metered;
2229 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002230 final int type = state.networkInfo.getType();
2231 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2232 return true;
2233 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002234 return false;
2235 }
2236 }
2237
2238 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002239 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002240 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002241
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002242 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2243
Dianne Hackborn497175b2014-07-01 12:56:08 -07002244 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002245 for (String arg : args) {
2246 argSet.add(arg);
2247 }
2248
Jeff Sharkey1b861272011-05-22 00:34:52 -07002249 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002250 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002251 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2252 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002253 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002254
Jeff Sharkey32566012014-12-02 18:30:14 -08002255 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002256 updateNetworkEnabledLocked();
2257 updateNetworkRulesLocked();
2258 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002259 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002260
2261 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002262 return;
2263 }
2264
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002265 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002266 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002267 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002268 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002269 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002270 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002271 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2272 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002273 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002274 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002275
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002276 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2277
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002278 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002279 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002280 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002281 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002282 final int uid = mUidPolicy.keyAt(i);
2283 final int policy = mUidPolicy.valueAt(i);
2284 fout.print("UID=");
2285 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002286 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002287 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002288 fout.println();
2289 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002290 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002291
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002292 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2293 if (size > 0) {
2294 fout.println("Power save whitelist (except idle) app ids:");
2295 fout.increaseIndent();
2296 for (int i = 0; i < size; i++) {
2297 fout.print("UID=");
2298 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2299 fout.print(": ");
2300 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2301 fout.println();
2302 }
2303 fout.decreaseIndent();
2304 }
2305
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002306 size = mPowerSaveWhitelistAppIds.size();
2307 if (size > 0) {
2308 fout.println("Power save whitelist app ids:");
2309 fout.increaseIndent();
2310 for (int i = 0; i < size; i++) {
2311 fout.print("UID=");
2312 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2313 fout.print(": ");
2314 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2315 fout.println();
2316 }
2317 fout.decreaseIndent();
2318 }
2319
Felipe Lemeb85a6372016-01-14 16:16:16 -08002320 size = mRestrictBackgroundWhitelistUids.size();
2321 if (size > 0) {
2322 fout.println("Restrict background whitelist uids:");
2323 fout.increaseIndent();
2324 for (int i = 0; i < size; i++) {
2325 fout.print("UID=");
2326 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2327 fout.println();
2328 }
2329 fout.decreaseIndent();
2330 }
2331
Felipe Lemea9505cc2016-02-26 10:28:41 -08002332 size = mDefaultRestrictBackgroundWhitelistUids.size();
2333 if (size > 0) {
2334 fout.println("Default restrict background whitelist uids:");
2335 fout.increaseIndent();
2336 for (int i = 0; i < size; i++) {
2337 fout.print("UID=");
2338 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2339 fout.println();
2340 }
2341 fout.decreaseIndent();
2342 }
2343
2344 size = mRestrictBackgroundWhitelistRevokedUids.size();
2345 if (size > 0) {
2346 fout.println("Default restrict background whitelist uids revoked by users:");
2347 fout.increaseIndent();
2348 for (int i = 0; i < size; i++) {
2349 fout.print("UID=");
2350 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2351 fout.println();
2352 }
2353 fout.decreaseIndent();
2354 }
2355
Jeff Sharkey1b861272011-05-22 00:34:52 -07002356 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002357 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002358 collectKeys(mUidRules, knownUids);
2359
Felipe Leme46c4fc32016-05-04 09:21:43 -07002360 fout.println("Status for all known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002361 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002362 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002363 for (int i = 0; i < size; i++) {
2364 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002365 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002366 fout.print(uid);
2367
Jeff Sharkeydc988062015-09-14 10:09:47 -07002368 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002369 fout.print(" state=");
2370 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002371 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2372 fout.print(" (fg)");
2373 } else {
2374 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2375 ? " (fg svc)" : " (bg)");
2376 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002377
Felipe Leme46c4fc32016-05-04 09:21:43 -07002378 final int uidRules = mUidRules.get(uid, RULE_NONE);
2379 fout.print(" rules=");
2380 fout.print(uidRulesToString(uidRules));
2381 fout.println();
2382 }
2383 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002384
Felipe Leme46c4fc32016-05-04 09:21:43 -07002385 fout.println("Status for just UIDs with rules:");
2386 fout.increaseIndent();
2387 size = mUidRules.size();
2388 for (int i = 0; i < size; i++) {
2389 final int uid = mUidRules.keyAt(i);
2390 fout.print("UID=");
2391 fout.print(uid);
2392 final int uidRules = mUidRules.get(uid, RULE_NONE);
2393 fout.print(" rules=");
2394 fout.print(uidRulesToString(uidRules));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002395 fout.println();
2396 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002397 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002398 }
2399 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002400
2401 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002402 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2403 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002404 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002405 this, in, out, err, args, resultReceiver);
2406 }
2407
2408 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002409 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002410 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2411
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002412 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002413 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002414 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002415 }
2416
Felipe Lemef28983d2016-03-25 12:18:23 -07002417 private boolean isUidForegroundLocked(int uid) {
2418 return isUidStateForegroundLocked(
2419 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2420 }
2421
Felipe Lemeef89c902016-03-30 15:11:31 -07002422 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2423 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2424 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2425 }
2426
Felipe Lemef28983d2016-03-25 12:18:23 -07002427 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002428 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002429 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002430 }
2431
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002432 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002433 * Process state of UID changed; if needed, will trigger
Felipe Leme70c57c22016-03-29 10:45:13 -07002434 * {@link #updateRuleForRestrictBackgroundLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002435 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002436 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002437 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2438 if (oldUidState != uidState) {
2439 // state changed, push updated rules
2440 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002441 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002442 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2443 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2444 if (mDeviceIdleMode) {
2445 updateRuleForDeviceIdleLocked(uid);
2446 }
2447 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002448 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002449 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002450 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002451 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002452 }
2453 }
2454
Felipe Lemef28983d2016-03-25 12:18:23 -07002455 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002456 final int index = mUidState.indexOfKey(uid);
2457 if (index >= 0) {
2458 final int oldUidState = mUidState.valueAt(index);
2459 mUidState.removeAt(index);
2460 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002461 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002462 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002463 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002464 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002465 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002466 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002467 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002468 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002469 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002470 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002471 }
2472 }
2473
Felipe Lemef28983d2016-03-25 12:18:23 -07002474 // adjust stats accounting based on foreground status
2475 private void updateNetworkStats(int uid, boolean uidForeground) {
2476 try {
2477 mNetworkStats.setUidForeground(uid, uidForeground);
2478 } catch (RemoteException e) {
2479 // ignored; service lives in system_server
2480 }
2481 }
2482
2483 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2484 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002485 final boolean oldForeground =
2486 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2487 final boolean newForeground =
2488 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002489 if (oldForeground != newForeground) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002490 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002491 }
2492 }
2493
Jeff Sharkeya4620792011-05-20 15:29:23 -07002494 private void updateScreenOn() {
2495 synchronized (mRulesLock) {
2496 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002497 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002498 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002499 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002500 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002501 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002502 }
2503 }
2504
2505 /**
2506 * Update rules that might be changed by {@link #mScreenOn} value.
2507 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002508 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002509 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002510 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002511 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002512 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002513 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002514 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002515 }
2516 }
2517 }
2518
Felipe Leme011b98f2016-02-10 17:28:31 -08002519 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002520 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2521 }
2522
Felipe Lemeef89c902016-03-30 15:11:31 -07002523 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2524 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2525 }
2526
Felipe Leme011b98f2016-02-10 17:28:31 -08002527 void updateRulesForRestrictPowerLocked() {
2528 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2529 mUidFirewallPowerSaveRules);
2530 }
2531
Felipe Lemef28983d2016-03-25 12:18:23 -07002532 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002533 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2534 }
2535
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002536 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002537 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2538 mUidFirewallDozableRules);
2539 }
2540
2541 void updateRuleForDeviceIdleLocked(int uid) {
2542 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2543 }
2544
Felipe Lemef28983d2016-03-25 12:18:23 -07002545 // NOTE: since both fw_dozable and fw_powersave uses the same map
2546 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002547 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2548 SparseIntArray rules) {
2549 if (enabled) {
2550 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002551 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002552 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002553 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002554 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002555 for (int ui = users.size() - 1; ui >= 0; ui--) {
2556 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002557 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002558 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2559 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2560 int uid = UserHandle.getUid(user.id, appId);
2561 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2562 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002563 }
2564 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2565 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2566 int uid = UserHandle.getUid(user.id, appId);
2567 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2568 }
2569 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002570 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002571 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002572 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2573 }
2574 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002575 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002576 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002577
Felipe Leme011b98f2016-02-10 17:28:31 -08002578 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002579 }
2580
Felipe Leme46c4fc32016-05-04 09:21:43 -07002581 private boolean isWhitelistedBatterySaverLocked(int uid) {
2582 final int appId = UserHandle.getAppId(uid);
2583 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2584 }
2585
Felipe Lemef28983d2016-03-25 12:18:23 -07002586 // NOTE: since both fw_dozable and fw_powersave uses the same map
2587 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002588 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2589 if (enabled) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002590 if (isWhitelistedBatterySaverLocked(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002591 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2592 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002593 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002594 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002595 }
2596 }
2597 }
2598
2599 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002600 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2601 uidRules.clear();
2602
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002603 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002604 final List<UserInfo> users = mUserManager.getUsers();
2605 for (int ui = users.size() - 1; ui >= 0; ui--) {
2606 UserInfo user = users.get(ui);
2607 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2608 for (int uid : idleUids) {
2609 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002610 // quick check: if this uid doesn't have INTERNET permission, it
2611 // doesn't have network access anyway, so it is a waste to mess
2612 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002613 if (hasInternetPermissions(uid)) {
2614 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002615 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002616 }
2617 }
2618 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002619
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002620 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2621 }
2622
2623 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002624 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002625
2626 int appId = UserHandle.getAppId(uid);
2627 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2628 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2629 } else {
2630 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2631 }
2632 }
2633
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002634 void updateRulesForAppIdleParoleLocked() {
2635 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2636 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002637 }
2638
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002639 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002640 * Update rules that might be changed by {@link #mRestrictBackground},
2641 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002642 */
Felipe Leme76010a32016-03-17 13:03:11 -07002643 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002644 long start;
2645 if (LOGD) start = System.currentTimeMillis();
2646
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002647 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002648 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002649 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002650 updateRulesForRestrictBackgroundLocked();
Felipe Leme70c57c22016-03-29 10:45:13 -07002651 setRestrictBackgroundLocked(mRestrictBackground);
Felipe Leme76010a32016-03-17 13:03:11 -07002652
2653 // If the set of restricted networks may have changed, re-evaluate those.
2654 if (restrictedNetworksChanged) {
2655 normalizePoliciesLocked();
2656 updateNetworkRulesLocked();
2657 }
2658 if (LOGD) {
2659 final long delta = System.currentTimeMillis() - start;
2660 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2661 + delta + "ms");
2662 }
2663 }
2664
Felipe Lemef28983d2016-03-25 12:18:23 -07002665 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002666 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002667
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002668 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002669 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002670 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002671 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2672 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2673 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002674
Felipe Leme03e689d2016-03-02 16:17:38 -08002675 final int usersSize = users.size();
2676 final int appsSize = apps.size();
2677 for (int i = 0; i < usersSize; i++) {
2678 final UserInfo user = users.get(i);
2679 for (int j = 0; j < appsSize; j++) {
2680 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002681 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002682 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002683 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002684 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002685 }
2686
Felipe Leme76010a32016-03-17 13:03:11 -07002687 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002688 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002689 for (int i = 0; i < users.size(); i++) {
2690 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002691 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002692 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002693 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002694 updateRuleForAppIdleLocked(uid);
2695 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002696 updateRuleForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002697 }
2698 }
2699 }
2700
Felipe Leme70c57c22016-03-29 10:45:13 -07002701 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2702 // methods below could be merged into a isUidValidForRules() method.
2703 private boolean isUidValidForBlacklistRules(int uid) {
2704 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002705 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002706 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002707 return true;
2708 }
2709
2710 return false;
2711 }
2712
Felipe Leme70c57c22016-03-29 10:45:13 -07002713 private boolean isUidValidForWhitelistRules(int uid) {
2714 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2715 }
2716
Amith Yamasani15e472352015-04-24 19:06:07 -07002717 private boolean isUidIdle(int uid) {
2718 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2719 final int userId = UserHandle.getUserId(uid);
2720
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002721 if (!ArrayUtils.isEmpty(packages)) {
2722 for (String packageName : packages) {
2723 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2724 return false;
2725 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002726 }
2727 }
2728 return true;
2729 }
2730
2731 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002732 * Checks if an uid has INTERNET permissions.
2733 * <p>
2734 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002735 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002736 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002737 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002738 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002739 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002740 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002741 }
2742 } catch (RemoteException e) {
2743 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002744 return true;
2745 }
2746
2747 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002748 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002749 *
Felipe Lemef28983d2016-03-25 12:18:23 -07002750 * <p>There are currently 2 types of restriction rules:
2751 * <ul>
2752 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002753 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002754 * </ul>
Felipe Leme47585ba2016-02-09 16:56:32 -08002755 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002756 private void updateRestrictionRulesForUidLocked(int uid) {
2757 updateRuleForRestrictPowerLocked(uid);
2758 updateRuleForRestrictBackgroundLocked(uid);
2759 }
2760
Felipe Leme70c57c22016-03-29 10:45:13 -07002761 /**
2762 * Applies network rules to bandwidth controllers based on process state and user-defined
2763 * restrictions (blacklist / whitelist).
2764 *
2765 * <p>
2766 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2767 * networks:
2768 * <ul>
2769 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2770 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2771 * also blacklisted.
2772 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2773 * no UIDs other those whitelisted will have access.
2774 * <ul>
2775 *
2776 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2777 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2778 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2779 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
2780 * this ({@link #updateRuleForRestrictBackgroundLocked(int)}) to propagate the rules to
2781 * {@link INetworkManagementService}, but this method should also be called in events (like
2782 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2783 * following rules should also be applied:
2784 *
2785 * <ul>
2786 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2787 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2788 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2789 * {@code bw_penalty_box}.
2790 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2791 * </ul>
2792 *
2793 * <p>For optimization, the rules are only applied on user apps that have internet access
2794 * permission, since there is no need to change the {@code iptables} rule if the app does not
2795 * have permission to use the internet.
2796 *
2797 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
2798 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002799 private void updateRuleForRestrictBackgroundLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002800 updateRuleForRestrictBackgroundLocked(uid, false);
2801 }
2802
2803 /**
2804 * Overloaded version of {@link #updateRuleForRestrictBackgroundLocked(int)} called when an
2805 * app is removed - it ignores the UID validity check.
2806 */
2807 private void updateRuleForRestrictBackgroundLocked(int uid, boolean uidDeleted) {
2808 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2809 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2810 return;
2811 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002812
Dianne Hackborn497175b2014-07-01 12:56:08 -07002813 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002814 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002815 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002816
Felipe Leme46c4fc32016-05-04 09:21:43 -07002817 // Data Saver status.
2818 final boolean isDsBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2819 final boolean isDsWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2820 int newDsRule = RULE_NONE;
2821 final int oldDsRule = oldUidRules & MASK_METERED_NETWORKS;
Felipe Leme76010a32016-03-17 13:03:11 -07002822
Felipe Leme70c57c22016-03-29 10:45:13 -07002823 // First step: define the new rule based on user restrictions and foreground state.
2824 if (isForeground) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002825 if (isDsBlacklisted || (mRestrictBackground && !isDsWhitelisted)) {
2826 newDsRule = RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -07002827 }
2828 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002829 if (isDsBlacklisted) {
2830 newDsRule = RULE_REJECT_METERED;
2831 } else if (isDsWhitelisted) {
2832 newDsRule = RULE_ALLOW_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002833 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002834 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002835
Felipe Leme46c4fc32016-05-04 09:21:43 -07002836 final int newUidRules = newDsRule;
2837
Felipe Lemef28983d2016-03-25 12:18:23 -07002838 if (LOGV) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002839 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + "):"
Felipe Leme46c4fc32016-05-04 09:21:43 -07002840 + " isForeground=" +isForeground + ", isBlacklisted: " + isDsBlacklisted
2841 + ", isDsWhitelisted: " + isDsWhitelisted
2842 + ", newUidRule: " + uidRulesToString(newUidRules)
2843 + ", oldUidRule: " + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002844 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002845
Felipe Leme46c4fc32016-05-04 09:21:43 -07002846 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002847 mUidRules.delete(uid);
2848 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002849 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002850 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002851
Felipe Leme70c57c22016-03-29 10:45:13 -07002852 // Second step: apply bw changes based on change of state.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002853 if (newDsRule != oldDsRule) {
2854 if ((newDsRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002855 // Temporarily whitelist foreground app, removing from blacklist if necessary
2856 // (since bw_penalty_box prevails over bw_happy_box).
2857
2858 setMeteredNetworkWhitelist(uid, true);
2859 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2860 // but ideally it should be just:
2861 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002862 if (isDsBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002863 setMeteredNetworkBlacklist(uid, false);
2864 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07002865 } else if ((oldDsRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002866 // Remove temporary whitelist from app that is not on foreground anymore.
2867
2868 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2869 // but ideally they should be just:
2870 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2871 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002872 if (!isDsWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002873 setMeteredNetworkWhitelist(uid, false);
2874 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07002875 if (isDsBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002876 setMeteredNetworkBlacklist(uid, true);
2877 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07002878 } else if ((newDsRule & RULE_REJECT_METERED) != 0
2879 || (oldDsRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002880 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002881 setMeteredNetworkBlacklist(uid, isDsBlacklisted);
2882 if ((oldDsRule & RULE_REJECT_METERED) != 0 && isDsWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002883 // Since blacklist prevails over whitelist, we need to handle the special case
2884 // where app is whitelisted and blacklisted at the same time (although such
2885 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002886 setMeteredNetworkWhitelist(uid, isDsWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002887 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07002888 } else if ((newDsRule & RULE_ALLOW_METERED) != 0
2889 || (oldDsRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002890 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002891 setMeteredNetworkWhitelist(uid, isDsWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002892 } else {
2893 // All scenarios should have been covered above
Felipe Leme46c4fc32016-05-04 09:21:43 -07002894 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2895 + ": foreground=" + isForeground
2896 + ", whitelisted=" + isDsWhitelisted
2897 + ", blacklisted=" + isDsBlacklisted
2898 + ", newRules=" + uidRulesToString(newUidRules)
2899 + ", oldRules=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07002900 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002901
2902 // dispatch changed rule to existing listeners
Felipe Leme46c4fc32016-05-04 09:21:43 -07002903 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002904 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002905 }
2906
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002907 private class AppIdleStateChangeListener
2908 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2909
2910 @Override
2911 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2912 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002913 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2914 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002915 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002916 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002917 }
2918 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002919 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002920 }
2921
2922 @Override
2923 public void onParoleStateChanged(boolean isParoleOn) {
2924 synchronized (mRulesLock) {
2925 updateRulesForAppIdleParoleLocked();
2926 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002927 }
2928 }
2929
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002930 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
2931 if (listener != null) {
2932 try {
2933 listener.onUidRulesChanged(uid, uidRules);
2934 } catch (RemoteException ignored) {
2935 }
2936 }
2937 }
2938
2939 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
2940 String[] meteredIfaces) {
2941 if (listener != null) {
2942 try {
2943 listener.onMeteredIfacesChanged(meteredIfaces);
2944 } catch (RemoteException ignored) {
2945 }
2946 }
2947 }
2948
2949 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
2950 boolean restrictBackground) {
2951 if (listener != null) {
2952 try {
2953 listener.onRestrictBackgroundChanged(restrictBackground);
2954 } catch (RemoteException ignored) {
2955 }
2956 }
2957 }
2958
2959 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
2960 int uid, boolean whitelisted) {
2961 if (listener != null) {
2962 try {
2963 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
2964 } catch (RemoteException ignored) {
2965 }
2966 }
2967 }
2968
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002969 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002970 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002971 public boolean handleMessage(Message msg) {
2972 switch (msg.what) {
2973 case MSG_RULES_CHANGED: {
2974 final int uid = msg.arg1;
2975 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002976 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002977 final int length = mListeners.beginBroadcast();
2978 for (int i = 0; i < length; i++) {
2979 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002980 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002981 }
2982 mListeners.finishBroadcast();
2983 return true;
2984 }
2985 case MSG_METERED_IFACES_CHANGED: {
2986 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002987 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002988 final int length = mListeners.beginBroadcast();
2989 for (int i = 0; i < length; i++) {
2990 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002991 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002992 }
2993 mListeners.finishBroadcast();
2994 return true;
2995 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002996 case MSG_LIMIT_REACHED: {
2997 final String iface = (String) msg.obj;
2998
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002999 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003000 synchronized (mRulesLock) {
3001 if (mMeteredIfaces.contains(iface)) {
3002 try {
3003 // force stats update to make sure we have
3004 // numbers that caused alert to trigger.
3005 mNetworkStats.forceUpdate();
3006 } catch (RemoteException e) {
3007 // ignored; service lives in system_server
3008 }
3009
3010 updateNetworkEnabledLocked();
3011 updateNotificationsLocked();
3012 }
3013 }
3014 return true;
3015 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003016 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3017 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003018 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003019 final int length = mListeners.beginBroadcast();
3020 for (int i = 0; i < length; i++) {
3021 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003022 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003023 }
3024 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003025 final Intent intent =
3026 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3027 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3028 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3029 return true;
3030 }
3031 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003032 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3033 // - when an app is whitelisted
3034 // - when an app is blacklisted
3035 //
3036 // Whether the internal listeners (INetworkPolicyListener implementations) or
3037 // app broadcast receivers are notified depend on the following rules:
3038 //
3039 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3040 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3041 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003042 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003043 final boolean changed = msg.arg2 == 1;
3044 final Boolean whitelisted = (Boolean) msg.obj;
3045
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003046 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003047 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003048 final boolean whitelistedBool = whitelisted.booleanValue();
3049 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3050 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003051 final int length = mListeners.beginBroadcast();
3052 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003053 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003054 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3055 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003056 }
3057 mListeners.finishBroadcast();
3058 }
3059
Felipe Leme9778f762016-01-27 14:46:39 -08003060 final PackageManager pm = mContext.getPackageManager();
3061 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003062 if (changed && packages != null) {
3063 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003064 final int userId = UserHandle.getUserId(uid);
3065 for (String packageName : packages) {
3066 final Intent intent = new Intent(
3067 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3068 intent.setPackage(packageName);
3069 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3070 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3071 }
Felipe Leme9778f762016-01-27 14:46:39 -08003072 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003073 return true;
3074 }
3075 case MSG_ADVISE_PERSIST_THRESHOLD: {
3076 final long lowestRule = (Long) msg.obj;
3077 try {
3078 // make sure stats are recorded frequently enough; we aim
3079 // for 2MB threshold for 2GB/month rules.
3080 final long persistThreshold = lowestRule / 1000;
3081 mNetworkStats.advisePersistThreshold(persistThreshold);
3082 } catch (RemoteException e) {
3083 // ignored; service lives in system_server
3084 }
3085 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003086 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003087 case MSG_SCREEN_ON_CHANGED: {
3088 updateScreenOn();
3089 return true;
3090 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003091 case MSG_UPDATE_INTERFACE_QUOTA: {
3092 removeInterfaceQuota((String) msg.obj);
3093 // int params need to be stitched back into a long
3094 setInterfaceQuota((String) msg.obj,
3095 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3096 return true;
3097 }
3098 case MSG_REMOVE_INTERFACE_QUOTA: {
3099 removeInterfaceQuota((String) msg.obj);
3100 return true;
3101 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003102 default: {
3103 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003104 }
3105 }
3106 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003107 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003108
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003109 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003110 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003111 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003112 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003113 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003114 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003115 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003116 }
3117 }
3118
3119 private void removeInterfaceQuota(String iface) {
3120 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003121 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003122 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003123 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003124 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003125 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003126 }
3127 }
3128
Felipe Leme70c57c22016-03-29 10:45:13 -07003129 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3130 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003131 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003132 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003133 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003134 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3135 } catch (RemoteException e) {
3136 // ignored; service lives in system_server
3137 }
3138 }
3139
3140 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3141 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3142 try {
3143 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3144 } catch (IllegalStateException e) {
3145 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003146 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003147 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003148 }
3149 }
3150
Amith Yamasani15e472352015-04-24 19:06:07 -07003151 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003152 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3153 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3154 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003155 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003156 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003157 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003158 int size = uidRules.size();
3159 int[] uids = new int[size];
3160 int[] rules = new int[size];
3161 for(int index = size - 1; index >= 0; --index) {
3162 uids[index] = uidRules.keyAt(index);
3163 rules[index] = uidRules.valueAt(index);
3164 }
3165 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003166 } catch (IllegalStateException e) {
3167 Log.wtf(TAG, "problem setting firewall uid rules", e);
3168 } catch (RemoteException e) {
3169 // ignored; service lives in system_server
3170 }
3171 }
3172
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003173 /**
3174 * Add or remove a uid to the firewall blacklist for all network ifaces.
3175 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003176 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003177 if (chain == FIREWALL_CHAIN_DOZABLE) {
3178 mUidFirewallDozableRules.put(uid, rule);
3179 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3180 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003181 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3182 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003183 }
3184
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003185 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003186 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003187 } catch (IllegalStateException e) {
3188 Log.wtf(TAG, "problem setting firewall uid rules", e);
3189 } catch (RemoteException e) {
3190 // ignored; service lives in system_server
3191 }
3192 }
3193
3194 /**
3195 * Add or remove a uid to the firewall blacklist for all network ifaces.
3196 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003197 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003198 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3199 mFirewallChainStates.get(chain) == enable) {
3200 // All is the same, nothing to do.
3201 return;
3202 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003203 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003204 try {
3205 mNetworkManager.setFirewallChainEnabled(chain, enable);
3206 } catch (IllegalStateException e) {
3207 Log.wtf(TAG, "problem enable firewall chain", e);
3208 } catch (RemoteException e) {
3209 // ignored; service lives in system_server
3210 }
3211 }
3212
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003213 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3214 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003215 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003216 } catch (RuntimeException e) {
3217 Slog.w(TAG, "problem reading network stats: " + e);
3218 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003219 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003220 // ignored; service lives in system_server
3221 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003222 }
3223 }
3224
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003225 private boolean isBandwidthControlEnabled() {
3226 final long token = Binder.clearCallingIdentity();
3227 try {
3228 return mNetworkManager.isBandwidthControlEnabled();
3229 } catch (RemoteException e) {
3230 // ignored; service lives in system_server
3231 return false;
3232 } finally {
3233 Binder.restoreCallingIdentity(token);
3234 }
3235 }
3236
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003237 /**
3238 * Try refreshing {@link #mTime} when stale.
3239 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003240 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003241 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003242 mTime.forceRefresh();
3243 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003244 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003245
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003246 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003247 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3248 }
3249
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003250 private static Intent buildAllowBackgroundDataIntent() {
3251 return new Intent(ACTION_ALLOW_BACKGROUND);
3252 }
3253
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003254 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3255 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3256 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3257 return intent;
3258 }
3259
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003260 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3261 final Intent intent = new Intent();
3262 intent.setComponent(new ComponentName(
3263 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3264 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3265 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3266 return intent;
3267 }
3268
3269 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3270 final Intent intent = new Intent();
3271 intent.setComponent(new ComponentName(
3272 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3273 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3274 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3275 return intent;
3276 }
3277
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003278 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003279 public void addIdleHandler(IdleHandler handler) {
3280 mHandler.getLooper().getQueue().addIdleHandler(handler);
3281 }
3282
Jeff Sharkey1b861272011-05-22 00:34:52 -07003283 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3284 final int size = source.size();
3285 for (int i = 0; i < size; i++) {
3286 target.put(source.keyAt(i), true);
3287 }
3288 }
3289
Stuart Scottf1fb3972015-04-02 18:00:02 -07003290 @Override
3291 public void factoryReset(String subscriber) {
3292 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3293
Stuart Scotte3e314d2015-04-20 14:07:45 -07003294 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3295 return;
3296 }
3297
Stuart Scottf1fb3972015-04-02 18:00:02 -07003298 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003299 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003300 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3301 for (NetworkPolicy policy : policies) {
3302 if (policy.template.equals(template)) {
3303 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3304 policy.inferred = false;
3305 policy.clearSnooze();
3306 }
3307 }
3308 setNetworkPolicies(policies);
3309
3310 // Turn restrict background data off
3311 setRestrictBackground(false);
3312
Stuart Scotte3e314d2015-04-20 14:07:45 -07003313 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3314 // Remove app's "restrict background data" flag
3315 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3316 setUidPolicy(uid, POLICY_NONE);
3317 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003318 }
3319 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003320
3321 private class MyPackageMonitor extends PackageMonitor {
3322
3323 @Override
3324 public void onPackageRemoved(String packageName, int uid) {
3325 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3326 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003327 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003328 }
3329 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003330 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003331
3332 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3333
3334 @Override
3335 public void resetUserState(int userId) {
3336 synchronized (mRulesLock) {
3337 boolean changed = removeUserStateLocked(userId, false);
3338 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(userId) || changed;
3339 if (changed) {
3340 writePolicyLocked();
3341 }
3342 }
3343 }
3344 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003345}