blob: a6055c1716f72e068e4822890d3c37b4e4c876b5 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme70c57c22016-03-29 10:45:13 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070052import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeydc988062015-09-14 10:09:47 -070054import static android.net.NetworkPolicyManager.RULE_UNKNOWN;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070055import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070056import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
57import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070058import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
59import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070060import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080061import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070062import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
63import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
64import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
65import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
66import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
67import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
68import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070069import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080070
Jeff Sharkey854b2b12012-04-13 16:03:40 -070071import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070073import static com.android.internal.util.XmlUtils.readBooleanAttribute;
74import static com.android.internal.util.XmlUtils.readIntAttribute;
75import static com.android.internal.util.XmlUtils.readLongAttribute;
76import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
77import static com.android.internal.util.XmlUtils.writeIntAttribute;
78import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070079import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070080import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060081
Jeff Sharkey21c9c452011-06-07 12:26:43 -070082import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080083import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070085
Dianne Hackborn88e98df2015-03-23 13:29:14 -070086import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070087import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070088import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070089import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070090import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070091import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070092import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070093import android.app.Notification;
94import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -070095import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070097import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070098import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -070099import android.content.Intent;
100import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700101import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700102import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700103import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700104import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700105import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700106import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700107import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700108import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700109import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700110import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700111import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700112import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700114import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700115import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700116import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700117import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700118import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.wifi.WifiConfiguration;
122import android.net.wifi.WifiInfo;
123import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.os.Environment;
126import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700127import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700128import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700129import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700130import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700131import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700132import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700134import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700135import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600137import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700139import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700140import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700141import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800142import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700143import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700144import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700145import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700146import android.util.ArrayMap;
147import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700148import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700149import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700150import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700151import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700152import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700153import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700154import android.util.SparseBooleanArray;
155import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.util.TrustedTime;
157import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700158
Jeff Sharkey497e4432011-06-14 17:27:29 -0700159import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800160import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800161import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800162import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700164import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700165import com.android.server.DeviceIdleController;
166import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700167import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800168import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600169
170import libcore.io.IoUtils;
171
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173
174import org.xmlpull.v1.XmlPullParser;
175import org.xmlpull.v1.XmlPullParserException;
176import org.xmlpull.v1.XmlSerializer;
177
178import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700179import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700184import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100185import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import java.util.ArrayList;
187import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700188import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700190/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700191 * Service that maintains low-level network policy rules, using
192 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700193 * <p>
194 * Derives active rules by combining a given policy with other system status,
195 * and delivers to listeners, such as {@link ConnectivityManager}, for
196 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700197 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700198public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800199 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700200 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700201 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700202
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700203 private static final int VERSION_INIT = 1;
204 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700205 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800206 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800207 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800208 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700209 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700210 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700211 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700212 private static final int VERSION_SWITCH_UID = 10;
213 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700214
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800215 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700216 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800217 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700218 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800219 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700220 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700221
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222 private static final String TAG_POLICY_LIST = "policy-list";
223 private static final String TAG_NETWORK_POLICY = "network-policy";
224 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700225 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800226 private static final String TAG_WHITELIST = "whitelist";
227 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800228 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700229
230 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700231 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700232 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
233 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700234 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700235 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800236 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237 private static final String ATTR_WARNING_BYTES = "warningBytes";
238 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700239 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800240 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
241 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800242 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700243 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700245 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700246 private static final String ATTR_POLICY = "policy";
247
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800249 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800250 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800251 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700252
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
254
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700255 private static final int MSG_RULES_CHANGED = 1;
256 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800257 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800258 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700259 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700260 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800261 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700262 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
263 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700264
Jeff Sharkey75279902011-05-24 18:39:45 -0700265 private final Context mContext;
266 private final IActivityManager mActivityManager;
267 private final IPowerManager mPowerManager;
268 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700269 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700270 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700272 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700273
274 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700275 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700276 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700277 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700278
Dianne Hackborn497175b2014-07-01 12:56:08 -0700279 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700280
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700281 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700282 volatile boolean mScreenOn;
283 volatile boolean mRestrictBackground;
284 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700285 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700286
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700287 private final boolean mSuppressDefaultPolicy;
288
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700289 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800290 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700291 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800292 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700293
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700294 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700295 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700296 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800297 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700298
Jeff Sharkeydc988062015-09-14 10:09:47 -0700299 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
300 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800301 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700302
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700303 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700304 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
305
Jeff Sharkey32566012014-12-02 18:30:14 -0800306 /**
307 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700308 * in power save mode, except device idle (doze) still applies.
309 * TODO: An int array might be sufficient
310 */
311 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
312
313 /**
314 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800315 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700316 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800317 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700318 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700319
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700320 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
321
Felipe Lemeb85a6372016-01-14 16:16:16 -0800322 /**
323 * UIDs that have been white-listed to avoid restricted background.
324 */
325 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
326
Felipe Lemea9505cc2016-02-26 10:28:41 -0800327 /**
328 * UIDs that have been initially white-listed by system to avoid restricted background.
329 */
330 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
331 new SparseBooleanArray();
332
333 /**
334 * UIDs that have been initially white-listed by system to avoid restricted background,
335 * but later revoked by user.
336 */
337 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
338 new SparseBooleanArray();
339
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700340 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800341 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700342 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800343 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700344
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700345 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700346 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700347
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700348 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700350
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600351 /** Higher priority listener before general event dispatch */
352 private INetworkPolicyListener mConnectivityListener;
353
Jeff Sharkey32566012014-12-02 18:30:14 -0800354 private final RemoteCallbackList<INetworkPolicyListener>
355 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700356
Dianne Hackborn497175b2014-07-01 12:56:08 -0700357 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700358
359 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700360
Svet Ganov16a16892015-04-16 10:32:04 -0700361 private final AppOpsManager mAppOps;
362
Felipe Lemeb85a6372016-01-14 16:16:16 -0800363 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800364 private final IPackageManager mIPm;
365
Felipe Lemeb85a6372016-01-14 16:16:16 -0800366
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700367 // TODO: keep whitelist of system-critical services that should never have
368 // rules enforced, such as system, phone, and radio UIDs.
369
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700370 // TODO: migrate notifications to SystemUI
371
Jeff Sharkey75279902011-05-24 18:39:45 -0700372 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700373 IPowerManager powerManager, INetworkStatsService networkStats,
374 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700375 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700376 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700377 }
378
379 private static File getSystemDir() {
380 return new File(Environment.getDataDirectory(), "system");
381 }
382
383 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700384 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700385 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
386 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700387 mContext = checkNotNull(context, "missing context");
388 mActivityManager = checkNotNull(activityManager, "missing activityManager");
389 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700390 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700391 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700392 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700393 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700394 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700395 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800396 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397
Amith Yamasani450a16b2013-09-18 16:28:50 -0700398 HandlerThread thread = new HandlerThread(TAG);
399 thread.start();
400 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700402 mSuppressDefaultPolicy = suppressDefaultPolicy;
403
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700405
406 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800407
408 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700409
410 // Expose private service for system components to use.
411 LocalServices.addService(NetworkPolicyManagerInternal.class,
412 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700413 }
414
415 public void bindConnectivityManager(IConnectivityManager connManager) {
416 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700417 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700418
Jeff Sharkey497e4432011-06-14 17:27:29 -0700419 public void bindNotificationManager(INotificationManager notifManager) {
420 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
421 }
422
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700423 void updatePowerSaveWhitelistLocked() {
424 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700425 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
426 mPowerSaveWhitelistExceptIdleAppIds.clear();
427 if (whitelist != null) {
428 for (int uid : whitelist) {
429 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
430 }
431 }
432 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700433 mPowerSaveWhitelistAppIds.clear();
434 if (whitelist != null) {
435 for (int uid : whitelist) {
436 mPowerSaveWhitelistAppIds.put(uid, true);
437 }
438 }
439 } catch (RemoteException e) {
440 }
441 }
442
Felipe Lemea9505cc2016-02-26 10:28:41 -0800443 /**
444 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
445 * revoke the whitelist.
446 *
447 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
448 */
Felipe Lemea110eec2016-04-29 09:58:06 -0700449 boolean addDefaultRestrictBackgroundWhitelistUidsLocked() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800450 final List<UserInfo> users = mUserManager.getUsers();
451 final int numberUsers = users.size();
452
Felipe Lemea110eec2016-04-29 09:58:06 -0700453 boolean changed = false;
454 for (int i = 0; i < numberUsers; i++) {
455 final UserInfo user = users.get(i);
456 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(user.id) || changed;
457 }
458 return changed;
459 }
460
461 private boolean addDefaultRestrictBackgroundWhitelistUidsLocked(int userId) {
462 final SystemConfig sysConfig = SystemConfig.getInstance();
463 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800464 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
465 boolean changed = false;
466 for (int i = 0; i < allowDataUsage.size(); i++) {
467 final String pkg = allowDataUsage.valueAt(i);
468 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700469 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
470 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800471 final ApplicationInfo app;
472 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700473 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800474 } catch (PackageManager.NameNotFoundException e) {
475 // Should not happen
476 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
477 continue;
478 }
479 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700480 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800481 continue;
482 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700483 final int uid = UserHandle.getUid(userId, app.uid);
484 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
485 if (LOGD)
486 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
487 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800488 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700489 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
490 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
491 + userId + ") to restrict background whitelist");
492 mRestrictBackgroundWhitelistUids.append(uid, true);
493 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800494 }
495 }
496 return changed;
497 }
498
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700499 void updatePowerSaveTempWhitelistLocked() {
500 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700501 // Clear the states of the current whitelist
502 final int N = mPowerSaveTempWhitelistAppIds.size();
503 for (int i = 0; i < N; i++) {
504 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
505 }
506 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700507 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700508 if (whitelist != null) {
509 for (int uid : whitelist) {
510 mPowerSaveTempWhitelistAppIds.put(uid, true);
511 }
512 }
513 } catch (RemoteException e) {
514 }
515 }
516
Amith Yamasani06f08062015-06-12 13:23:33 -0700517 /**
518 * Remove unnecessary entries in the temp whitelist
519 */
520 void purgePowerSaveTempWhitelistLocked() {
521 final int N = mPowerSaveTempWhitelistAppIds.size();
522 for (int i = N - 1; i >= 0; i--) {
523 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
524 mPowerSaveTempWhitelistAppIds.removeAt(i);
525 }
526 }
527 }
528
Jeff Sharkeya4620792011-05-20 15:29:23 -0700529 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700530 if (!isBandwidthControlEnabled()) {
531 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
532 return;
533 }
534
Amith Yamasani15e472352015-04-24 19:06:07 -0700535 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
536
Felipe Lemeb85a6372016-01-14 16:16:16 -0800537 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
538
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700539 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700540 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700541 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
542 mPowerManagerInternal.registerLowPowerModeObserver(
543 new PowerManagerInternal.LowPowerModeListener() {
544 @Override
545 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800546 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700547 synchronized (mRulesLock) {
548 if (mRestrictPower != enabled) {
549 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800550 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700551 updateRulesForGlobalChangeLocked(true);
552 }
553 }
554 }
555 });
556 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700557 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700558
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700559 // read policy from disk
560 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700561
Felipe Lemea110eec2016-04-29 09:58:06 -0700562 if (addDefaultRestrictBackgroundWhitelistUidsLocked()) {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800563 writePolicyLocked();
564 }
565
Jeff Sharkeydc988062015-09-14 10:09:47 -0700566 updateRulesForGlobalChangeLocked(false);
567 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700568 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700569
Jeff Sharkeya4620792011-05-20 15:29:23 -0700570 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700571
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700573 mActivityManager.registerUidObserver(mUidObserver,
574 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700575 mNetworkManager.registerObserver(mAlertObserver);
576 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700577 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700578 }
579
Jeff Sharkeya4620792011-05-20 15:29:23 -0700580 // TODO: traverse existing processes to know foreground state, or have
581 // activitymanager dispatch current state when new observer attached.
582
583 final IntentFilter screenFilter = new IntentFilter();
584 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
585 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700586 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700587
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700588 // listen for changes to power save whitelist
589 final IntentFilter whitelistFilter = new IntentFilter(
590 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
591 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
592
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700593 DeviceIdleController.LocalService deviceIdleService
594 = LocalServices.getService(DeviceIdleController.LocalService.class);
595 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
596
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700597 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900598 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700599 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
600
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700601 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700602 final IntentFilter packageFilter = new IntentFilter();
603 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700604 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700605 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700606
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700607 // listen for UID changes to update policy
608 mContext.registerReceiver(
609 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
610
611 // listen for user changes to update policy
612 final IntentFilter userFilter = new IntentFilter();
613 userFilter.addAction(ACTION_USER_ADDED);
614 userFilter.addAction(ACTION_USER_REMOVED);
615 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
616
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700617 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700618 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
619 mContext.registerReceiver(
620 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
621
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700622 // listen for restrict background changes from notifications
623 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
624 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
625
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800626 // listen for snooze warning from notifications
627 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
628 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
629 MANAGE_NETWORK_POLICY, mHandler);
630
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700631 // listen for configured wifi networks to be removed
632 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700633 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700634
635 // listen for wifi state changes to catch metered hint
636 final IntentFilter wifiStateFilter = new IntentFilter(
637 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700638 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700639
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700640 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700641
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700642 }
643
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700644 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700645 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700646 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700647 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700648 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700649 }
650
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700651 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700652 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700653 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700654 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700655 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700656
657 @Override public void onUidActive(int uid) throws RemoteException {
658 }
659
660 @Override public void onUidIdle(int uid) throws RemoteException {
661 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700662 };
663
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700664 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700665 @Override
666 public void onReceive(Context context, Intent intent) {
667 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
668 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700669 updatePowerSaveWhitelistLocked();
670 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700671 }
672 }
673 };
674
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700675 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
676 @Override
677 public void run() {
678 synchronized (mRulesLock) {
679 updatePowerSaveTempWhitelistLocked();
680 updateRulesForTempWhitelistChangeLocked();
681 purgePowerSaveTempWhitelistLocked();
682 }
683 }
684 };
685
686 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700687 @Override
688 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800689 // screen-related broadcasts are protected by system, no need
690 // for permissions check.
691 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700692 }
693 };
694
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700695 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700696 @Override
697 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700698 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700699
700 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700701 final int uid = intent.getIntExtra(EXTRA_UID, -1);
702 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700703
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700704 if (ACTION_PACKAGE_ADDED.equals(action)) {
705 // update rules for UID, since it might be subject to
706 // global background data policy
707 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
708 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700709 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700710 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700711 }
712 }
713 };
714
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700715 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700716 @Override
717 public void onReceive(Context context, Intent intent) {
718 // on background handler thread, and UID_REMOVED is protected
719
720 final int uid = intent.getIntExtra(EXTRA_UID, -1);
721 if (uid == -1) return;
722
723 // remove any policy and update rules to clean up
724 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
725 synchronized (mRulesLock) {
726 mUidPolicy.delete(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -0700727 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700728 writePolicyLocked();
729 }
730 }
731 };
732
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700733 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700734 @Override
735 public void onReceive(Context context, Intent intent) {
736 // on background handler thread, and USER_ADDED and USER_REMOVED
737 // broadcasts are protected
738
739 final String action = intent.getAction();
740 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
741 if (userId == -1) return;
742
Amith Yamasani15e472352015-04-24 19:06:07 -0700743 switch (action) {
744 case ACTION_USER_REMOVED:
745 case ACTION_USER_ADDED:
746 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800747 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700748 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemed17fda42016-04-29 11:12:45 -0700749 removeUserStateLocked(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700750 if (action == ACTION_USER_ADDED) {
751 // Add apps that are whitelisted by default.
752 addDefaultRestrictBackgroundWhitelistUidsLocked(userId);
753 }
754 // Update global restrict for that user
Amith Yamasani15e472352015-04-24 19:06:07 -0700755 updateRulesForGlobalChangeLocked(true);
756 }
757 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700758 }
759 }
760 };
761
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700762 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700763 * Receiver that watches for {@link INetworkStatsService} updates, which we
764 * use to check against {@link NetworkPolicy#warningBytes}.
765 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700766 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700767 @Override
768 public void onReceive(Context context, Intent intent) {
769 // on background handler thread, and verified
770 // READ_NETWORK_USAGE_HISTORY permission above.
771
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800772 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700774 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700775 updateNotificationsLocked();
776 }
777 }
778 };
779
780 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700781 * Receiver that watches for {@link Notification} control of
782 * {@link #mRestrictBackground}.
783 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700784 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700785 @Override
786 public void onReceive(Context context, Intent intent) {
787 // on background handler thread, and verified MANAGE_NETWORK_POLICY
788 // permission above.
789
790 setRestrictBackground(false);
791 }
792 };
793
794 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800795 * Receiver that watches for {@link Notification} control of
796 * {@link NetworkPolicy#lastWarningSnooze}.
797 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700798 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800799 @Override
800 public void onReceive(Context context, Intent intent) {
801 // on background handler thread, and verified MANAGE_NETWORK_POLICY
802 // permission above.
803
804 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
805 performSnooze(template, TYPE_WARNING);
806 }
807 };
808
809 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700810 * Receiver that watches for {@link WifiConfiguration} to be changed.
811 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700812 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700813 @Override
814 public void onReceive(Context context, Intent intent) {
815 // on background handler thread, and verified CONNECTIVITY_INTERNAL
816 // permission above.
817
818 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
819 if (reason == CHANGE_REASON_REMOVED) {
820 final WifiConfiguration config = intent.getParcelableExtra(
821 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700822 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800823 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700824 synchronized (mRulesLock) {
825 if (mNetworkPolicy.containsKey(template)) {
826 mNetworkPolicy.remove(template);
827 writePolicyLocked();
828 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700829 }
830 }
831 }
832 }
833 };
834
835 /**
836 * Receiver that watches {@link WifiInfo} state changes to infer metered
837 * state. Ignores hints when policy is user-defined.
838 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700839 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700840 @Override
841 public void onReceive(Context context, Intent intent) {
842 // on background handler thread, and verified CONNECTIVITY_INTERNAL
843 // permission above.
844
845 // ignore when not connected
846 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
847 if (!netInfo.isConnected()) return;
848
849 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
850 final boolean meteredHint = info.getMeteredHint();
851
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800852 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700853 synchronized (mRulesLock) {
854 NetworkPolicy policy = mNetworkPolicy.get(template);
855 if (policy == null && meteredHint) {
856 // policy doesn't exist, and AP is hinting that it's
857 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800858 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700859 addNetworkPolicyLocked(policy);
860
861 } else if (policy != null && policy.inferred) {
862 // policy exists, and was inferred: update its current
863 // metered state.
864 policy.metered = meteredHint;
865
866 // since this is inferred for each wifi session, just update
867 // rules without persisting.
868 updateNetworkRulesLocked();
869 }
870 }
871 }
872 };
873
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800874 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
875 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
876 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
877 metered, true);
878 }
879
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700880 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700881 * Observer that watches for {@link INetworkManagementService} alerts.
882 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700883 final private INetworkManagementEventObserver mAlertObserver
884 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700885 @Override
886 public void limitReached(String limitName, String iface) {
887 // only someone like NMS should be calling us
888 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
889
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800890 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
891 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700892 }
893 }
894 };
895
896 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700897 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
898 * to show visible notifications as needed.
899 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700900 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700901 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
902
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700903 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700904 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700905 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700906
907 // TODO: when switching to kernel notifications, compute next future
908 // cycle boundary to recompute notifications.
909
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700910 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800911 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700912 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
913 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700914 // ignore policies that aren't relevant to user
915 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700916 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700917
Jeff Sharkey497e4432011-06-14 17:27:29 -0700918 final long start = computeLastCycleBoundary(currentTime, policy);
919 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700921
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700922 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800923 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700924 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
925 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700926 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
927 notifyOverLimitLocked(policy.template);
928 }
929
Jeff Sharkey497e4432011-06-14 17:27:29 -0700930 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700931 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700932
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800933 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700934 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935 }
936 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700937 }
938
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700939 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700940 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
941 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700942 if (!mActiveNotifs.contains(tag)) {
943 cancelNotification(tag);
944 }
945 }
946 }
947
948 /**
949 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700950 * current device state, such as when
951 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
952 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700953 */
954 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800955 if (template.isMatchRuleMobile()) {
956 final TelephonyManager tele = TelephonyManager.from(mContext);
957 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700958
Jeff Sharkey32566012014-12-02 18:30:14 -0800959 // Mobile template is relevant when any active subscriber matches
960 final int[] subIds = sub.getActiveSubscriptionIdList();
961 for (int subId : subIds) {
962 final String subscriberId = tele.getSubscriberId(subId);
963 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700964 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800965 if (template.matches(probeIdent)) {
966 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700967 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800968 }
969 return false;
970 } else {
971 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700973 }
974
975 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700976 * Notify that given {@link NetworkTemplate} is over
977 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
978 */
979 private void notifyOverLimitLocked(NetworkTemplate template) {
980 if (!mOverLimitNotified.contains(template)) {
981 mContext.startActivity(buildNetworkOverLimitIntent(template));
982 mOverLimitNotified.add(template);
983 }
984 }
985
986 private void notifyUnderLimitLocked(NetworkTemplate template) {
987 mOverLimitNotified.remove(template);
988 }
989
990 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700991 * Build unique tag that identifies an active {@link NetworkPolicy}
992 * notification of a specific type, like {@link #TYPE_LIMIT}.
993 */
994 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700995 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996 }
997
998 /**
999 * Show notification for combined {@link NetworkPolicy} and specific type,
1000 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1001 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001002 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001003 final String tag = buildNotificationTag(policy, type);
1004 final Notification.Builder builder = new Notification.Builder(mContext);
1005 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001006 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001007 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001008 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009
1010 final Resources res = mContext.getResources();
1011 switch (type) {
1012 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001014 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001016 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 builder.setTicker(title);
1018 builder.setContentTitle(title);
1019 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001020
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001021 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1022 builder.setDeleteIntent(PendingIntent.getBroadcast(
1023 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1024
1025 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001026 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001027 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1028
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029 break;
1030 }
1031 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1033
1034 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001035 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001036 switch (policy.template.getMatchRule()) {
1037 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001040 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001043 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 case MATCH_WIFI:
1047 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001048 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001049 break;
1050 default:
1051 title = null;
1052 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001053 }
1054
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001055 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001056 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057 builder.setTicker(title);
1058 builder.setContentTitle(title);
1059 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001060
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001061 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1062 builder.setContentIntent(PendingIntent.getActivity(
1063 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1064 break;
1065 }
1066 case TYPE_LIMIT_SNOOZED: {
1067 final long overBytes = totalBytes - policy.limitBytes;
1068 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1069 Formatter.formatFileSize(mContext, overBytes));
1070
1071 final CharSequence title;
1072 switch (policy.template.getMatchRule()) {
1073 case MATCH_MOBILE_3G_LOWER:
1074 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1075 break;
1076 case MATCH_MOBILE_4G:
1077 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1078 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001079 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001080 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1081 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 case MATCH_WIFI:
1083 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1084 break;
1085 default:
1086 title = null;
1087 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001088 }
1089
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001090 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001091 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001092 builder.setTicker(title);
1093 builder.setContentTitle(title);
1094 builder.setContentText(body);
1095
1096 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001097 builder.setContentIntent(PendingIntent.getActivity(
1098 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 break;
1100 }
1101 }
1102
1103 // TODO: move to NotificationManager once we can mock it
1104 try {
1105 final String packageName = mContext.getPackageName();
1106 final int[] idReceived = new int[1];
1107 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001108 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001109 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001110 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001111 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001112 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001113 }
1114 }
1115
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001116 private void cancelNotification(String tag) {
1117 // TODO: move to NotificationManager once we can mock it
1118 try {
1119 final String packageName = mContext.getPackageName();
1120 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001121 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001123 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001124 }
1125 }
1126
1127 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001128 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001129 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001130 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001131 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001132 @Override
1133 public void onReceive(Context context, Intent intent) {
1134 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1135 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001136
1137 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001139 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001140 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001141 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001142 updateNetworkRulesLocked();
1143 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001144 }
1145 }
1146 };
1147
1148 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001149 * Proactively control network data connections when they exceed
1150 * {@link NetworkPolicy#limitBytes}.
1151 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001152 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001153 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1154
1155 // TODO: reset any policy-disabled networks when any policy is removed
1156 // completely, which is currently rare case.
1157
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001158 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001159 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1160 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001161 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001162 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001163 setNetworkTemplateEnabled(policy.template, true);
1164 continue;
1165 }
1166
1167 final long start = computeLastCycleBoundary(currentTime, policy);
1168 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001170
1171 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001172 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1173 && policy.lastLimitSnooze < start;
1174 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001175
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001176 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001177 }
1178 }
1179
1180 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001181 * Proactively disable networks that match the given
1182 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 */
1184 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001185 // TODO: reach into ConnectivityManager to proactively disable bringing
1186 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001187 }
1188
1189 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001190 * Examine all connected {@link NetworkState}, looking for
1191 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1192 * remaining quota based on usage cycle and historical stats.
1193 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001194 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001195 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001196
1197 final NetworkState[] states;
1198 try {
1199 states = mConnManager.getAllNetworkState();
1200 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001201 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001202 return;
1203 }
1204
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001205 // First, generate identities of all connected networks so we can
1206 // quickly compare them against all defined policies below.
1207 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001208 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001210 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001211 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001212
1213 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001214 if (baseIface != null) {
1215 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001216 }
1217
1218 // Stacked interfaces are considered to have same identity as
1219 // their parent network.
1220 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1221 for (LinkProperties stackedLink : stackedLinks) {
1222 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001223 if (stackedIface != null) {
1224 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001225 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001226 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001227 }
1228 }
1229
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001230 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001231 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001232 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001233 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001234 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001235
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001236 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001237 for (int j = connIdents.size() - 1; j >= 0; j--) {
1238 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1239 if (policy.template.matches(ident.second)) {
1240 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 }
1242 }
1243
1244 if (ifaceList.size() > 0) {
1245 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001246 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247 }
1248 }
1249
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001250 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001251 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001252
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 // apply each policy that we found ifaces for; compute remaining data
1254 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001255 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001256 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1257 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1258 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001259
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001260 final long start;
1261 final long totalBytes;
1262 if (policy.hasCycle()) {
1263 start = computeLastCycleBoundary(currentTime, policy);
1264 totalBytes = getTotalBytes(policy.template, start, currentTime);
1265 } else {
1266 start = Long.MAX_VALUE;
1267 totalBytes = 0;
1268 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001269
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001270 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001271 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001272 }
1273
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001274 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001275 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001276 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001277 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001278 if (!hasLimit) {
1279 // metered network, but no policy limit; we still need to
1280 // restrict apps, so push really high quota.
1281 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001282 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001283 // snoozing past quota, but we still need to restrict apps,
1284 // so push really high quota.
1285 quotaBytes = Long.MAX_VALUE;
1286 } else {
1287 // remaining "quota" bytes are based on total usage in
1288 // current cycle. kernel doesn't like 0-byte rules, so we
1289 // set 1-byte quota and disable the radio later.
1290 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1291 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001292
1293 if (ifaces.length > 1) {
1294 // TODO: switch to shared quota once NMS supports
1295 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001296 }
1297
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001298 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001299 // long quotaBytes split up into two ints to fit in message
1300 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1301 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1302 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001303 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001304 }
1305 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001306
1307 // keep track of lowest warning or limit of active policies
1308 if (hasWarning && policy.warningBytes < lowestRule) {
1309 lowestRule = policy.warningBytes;
1310 }
1311 if (hasLimit && policy.limitBytes < lowestRule) {
1312 lowestRule = policy.limitBytes;
1313 }
1314 }
1315
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001316 for (int i = connIfaces.size()-1; i >= 0; i--) {
1317 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001318 // long quotaBytes split up into two ints to fit in message
1319 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1320 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1321 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001322 newMeteredIfaces.add(iface);
1323 }
1324
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001325 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001326
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001327 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001328 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1329 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001330 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001331 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1332 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001333 }
1334 }
1335 mMeteredIfaces = newMeteredIfaces;
1336
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001337 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001338 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001339 }
1340
1341 /**
1342 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1343 * have at least a default mobile policy defined.
1344 */
1345 private void ensureActiveMobilePolicyLocked() {
1346 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001347 if (mSuppressDefaultPolicy) return;
1348
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001349 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001350 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001351
Jeff Sharkey32566012014-12-02 18:30:14 -08001352 final int[] subIds = sub.getActiveSubscriptionIdList();
1353 for (int subId : subIds) {
1354 final String subscriberId = tele.getSubscriberId(subId);
1355 ensureActiveMobilePolicyLocked(subscriberId);
1356 }
1357 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001358
Jeff Sharkey32566012014-12-02 18:30:14 -08001359 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1360 // Poke around to see if we already have a policy
1361 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001362 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001363 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1364 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1365 if (template.matches(probeIdent)) {
1366 if (LOGD) {
1367 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1368 + NetworkIdentity.scrubSubscriberId(subscriberId));
1369 }
1370 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001371 }
1372 }
1373
Jeff Sharkey32566012014-12-02 18:30:14 -08001374 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1375 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001376
Jeff Sharkey32566012014-12-02 18:30:14 -08001377 // Build default mobile policy, and assume usage cycle starts today
1378 final long warningBytes = mContext.getResources().getInteger(
1379 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001380
Jeff Sharkey32566012014-12-02 18:30:14 -08001381 final Time time = new Time();
1382 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001383
Jeff Sharkey32566012014-12-02 18:30:14 -08001384 final int cycleDay = time.monthDay;
1385 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001386
Jeff Sharkey32566012014-12-02 18:30:14 -08001387 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1388 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1389 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1390 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001391 }
1392
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001393 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001394 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001395
1396 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001397 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001398 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399
1400 FileInputStream fis = null;
1401 try {
1402 fis = mPolicyFile.openRead();
1403 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001404 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405
1406 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001407 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001408 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001409 while ((type = in.next()) != END_DOCUMENT) {
1410 final String tag = in.getName();
1411 if (type == START_TAG) {
1412 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001413 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001414 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001415 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1416 mRestrictBackground = readBooleanAttribute(
1417 in, ATTR_RESTRICT_BACKGROUND);
1418 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001419 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001420 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001421 if (mRestrictBackground != oldValue) {
1422 // Some early services may have read the default value,
1423 // so notify them that it's changed
1424 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1425 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1426 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001427
1428 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1429 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1430 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001431 final String networkId;
1432 if (version >= VERSION_ADDED_NETWORK_ID) {
1433 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1434 } else {
1435 networkId = null;
1436 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001438 final String cycleTimezone;
1439 if (version >= VERSION_ADDED_TIMEZONE) {
1440 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1441 } else {
1442 cycleTimezone = Time.TIMEZONE_UTC;
1443 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001444 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1445 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001446 final long lastLimitSnooze;
1447 if (version >= VERSION_SPLIT_SNOOZE) {
1448 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1449 } else if (version >= VERSION_ADDED_SNOOZE) {
1450 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001451 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001452 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001453 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001454 final boolean metered;
1455 if (version >= VERSION_ADDED_METERED) {
1456 metered = readBooleanAttribute(in, ATTR_METERED);
1457 } else {
1458 switch (networkTemplate) {
1459 case MATCH_MOBILE_3G_LOWER:
1460 case MATCH_MOBILE_4G:
1461 case MATCH_MOBILE_ALL:
1462 metered = true;
1463 break;
1464 default:
1465 metered = false;
1466 }
1467 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001468 final long lastWarningSnooze;
1469 if (version >= VERSION_SPLIT_SNOOZE) {
1470 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1471 } else {
1472 lastWarningSnooze = SNOOZE_NEVER;
1473 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001474 final boolean inferred;
1475 if (version >= VERSION_ADDED_INFERRED) {
1476 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1477 } else {
1478 inferred = false;
1479 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480
Jeff Sharkey32566012014-12-02 18:30:14 -08001481 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1482 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001483 if (template.isPersistable()) {
1484 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1485 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1486 lastLimitSnooze, metered, inferred));
1487 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001488
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001489 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490 final int uid = readIntAttribute(in, ATTR_UID);
1491 final int policy = readIntAttribute(in, ATTR_POLICY);
1492
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001493 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001494 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001495 } else {
1496 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1497 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001498 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001499 final int appId = readIntAttribute(in, ATTR_APP_ID);
1500 final int policy = readIntAttribute(in, ATTR_POLICY);
1501
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001502 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001503 // app policy is deprecated so this is only used in pre system user split.
1504 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001505 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001506 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001507 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001509 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001510 } else if (TAG_WHITELIST.equals(tag)) {
1511 insideWhitelist = true;
1512 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1513 final int uid = readIntAttribute(in, ATTR_UID);
1514 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001515 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1516 final int uid = readIntAttribute(in, ATTR_UID);
1517 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001518 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001519 } else if (type == END_TAG) {
1520 if (TAG_WHITELIST.equals(tag)) {
1521 insideWhitelist = false;
1522 }
1523
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001524 }
1525 }
1526
1527 } catch (FileNotFoundException e) {
1528 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001529 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001530 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001531 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001533 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001534 } finally {
1535 IoUtils.closeQuietly(fis);
1536 }
1537 }
1538
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001539 /**
1540 * Upgrade legacy background data flags, notifying listeners of one last
1541 * change to always-true.
1542 */
1543 private void upgradeLegacyBackgroundData() {
1544 mRestrictBackground = Settings.Secure.getInt(
1545 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1546
1547 // kick off one last broadcast if restricted
1548 if (mRestrictBackground) {
1549 final Intent broadcast = new Intent(
1550 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001551 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001552 }
1553 }
1554
Dianne Hackborn497175b2014-07-01 12:56:08 -07001555 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001556 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001557
1558 FileOutputStream fos = null;
1559 try {
1560 fos = mPolicyFile.startWrite();
1561
1562 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001563 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001564 out.startDocument(null, true);
1565
1566 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001567 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001568 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001569
1570 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001571 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1572 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001573 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001574 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001575
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001576 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001577 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1578 final String subscriberId = template.getSubscriberId();
1579 if (subscriberId != null) {
1580 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001582 final String networkId = template.getNetworkId();
1583 if (networkId != null) {
1584 out.attribute(null, ATTR_NETWORK_ID, networkId);
1585 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001587 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001588 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1589 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001590 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1591 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001592 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001593 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001594 out.endTag(null, TAG_NETWORK_POLICY);
1595 }
1596
1597 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001598 for (int i = 0; i < mUidPolicy.size(); i++) {
1599 final int uid = mUidPolicy.keyAt(i);
1600 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001601
Jeff Sharkey497e4432011-06-14 17:27:29 -07001602 // skip writing empty policies
1603 if (policy == POLICY_NONE) continue;
1604
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001605 out.startTag(null, TAG_UID_POLICY);
1606 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001608 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 }
1610
1611 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001612
1613 // write all whitelists
1614 out.startTag(null, TAG_WHITELIST);
1615
1616 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001617 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001618 for (int i = 0; i < size; i++) {
1619 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1620 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1621 writeIntAttribute(out, ATTR_UID, uid);
1622 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1623 }
1624
Felipe Lemea9505cc2016-02-26 10:28:41 -08001625 // revoked restrict background whitelist
1626 size = mRestrictBackgroundWhitelistRevokedUids.size();
1627 for (int i = 0; i < size; i++) {
1628 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1629 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1630 writeIntAttribute(out, ATTR_UID, uid);
1631 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1632 }
1633
Felipe Lemeb85a6372016-01-14 16:16:16 -08001634 out.endTag(null, TAG_WHITELIST);
1635
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001636 out.endDocument();
1637
1638 mPolicyFile.finishWrite(fos);
1639 } catch (IOException e) {
1640 if (fos != null) {
1641 mPolicyFile.failWrite(fos);
1642 }
1643 }
1644 }
1645
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001646 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001647 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001649
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001650 if (!UserHandle.isApp(uid)) {
1651 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001652 }
1653
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001654 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001655 final long token = Binder.clearCallingIdentity();
1656 try {
1657 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1658 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001659 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001660 }
1661 } finally {
1662 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001663 }
1664 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001665 }
1666
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001667 @Override
1668 public void addUidPolicy(int uid, int policy) {
1669 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001670
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001671 if (!UserHandle.isApp(uid)) {
1672 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1673 }
1674
1675 synchronized (mRulesLock) {
1676 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1677 policy |= oldPolicy;
1678 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001679 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001680 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001681 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001682 }
1683
1684 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001685 public void removeUidPolicy(int uid, int policy) {
1686 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1687
1688 if (!UserHandle.isApp(uid)) {
1689 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1690 }
1691
1692 synchronized (mRulesLock) {
1693 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1694 policy = oldPolicy & ~policy;
1695 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001696 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001697 }
1698 }
1699 }
1700
Felipe Leme923845f2016-03-02 13:42:48 -08001701 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1702 setUidPolicyUncheckedLocked(uid, policy, persist);
1703
1704 // Checks if app was added or removed to the blacklist.
1705 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1706 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001707 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001708 .sendToTarget();
1709 }
1710 }
1711
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001712 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1713 mUidPolicy.put(uid, policy);
1714
1715 // uid policy changed, recompute rules and persist policy.
Felipe Lemef28983d2016-03-25 12:18:23 -07001716 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001717 if (persist) {
1718 writePolicyLocked();
1719 }
1720 }
1721
1722 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001723 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001724 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1725
Jeff Sharkeya4620792011-05-20 15:29:23 -07001726 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001727 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001728 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001729 }
1730
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001731 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001732 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001733 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1734
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001735 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001736 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001737 for (int i = 0; i < mUidPolicy.size(); i++) {
1738 final int uid = mUidPolicy.keyAt(i);
1739 final int uidPolicy = mUidPolicy.valueAt(i);
1740 if (uidPolicy == policy) {
1741 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001742 }
1743 }
1744 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001745 return uids;
1746 }
1747
1748 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001749 * Removes any persistable state associated with given {@link UserHandle}, persisting
1750 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001751 */
Felipe Lemed17fda42016-04-29 11:12:45 -07001752 boolean removeUserStateLocked(int userId, boolean writePolicy) {
1753
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001754 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001755 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001756
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001757 // Remove entries from restricted background UID whitelist
1758 int[] wlUids = new int[0];
1759 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1760 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1761 if (UserHandle.getUserId(uid) == userId) {
1762 wlUids = appendInt(wlUids, uid);
1763 }
1764 }
1765
1766 if (wlUids.length > 0) {
1767 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001768 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001769 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001770 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001771 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001772
1773 // Remove entries from revoked default restricted background UID whitelist
1774 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1775 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1776 if (UserHandle.getUserId(uid) == userId) {
1777 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001778 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001779 }
1780 }
1781
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001782 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001783 int[] uids = new int[0];
1784 for (int i = 0; i < mUidPolicy.size(); i++) {
1785 final int uid = mUidPolicy.keyAt(i);
1786 if (UserHandle.getUserId(uid) == userId) {
1787 uids = appendInt(uids, uid);
1788 }
1789 }
1790
1791 if (uids.length > 0) {
1792 for (int uid : uids) {
1793 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001794 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001795 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001796 }
1797
Felipe Leme76010a32016-03-17 13:03:11 -07001798 updateRulesForGlobalChangeLocked(true);
1799
Felipe Lemed17fda42016-04-29 11:12:45 -07001800 if (writePolicy && changed) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001801 writePolicyLocked();
1802 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001803 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001804 }
1805
1806 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001807 public void setConnectivityListener(INetworkPolicyListener listener) {
1808 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1809 if (mConnectivityListener != null) {
1810 throw new IllegalStateException("Connectivity listener already registered");
1811 }
1812 mConnectivityListener = listener;
1813 }
1814
1815 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001816 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001817 // TODO: create permission for observing network policy
1818 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001820 }
1821
1822 @Override
1823 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001824 // TODO: create permission for observing network policy
1825 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001826 mListeners.unregister(listener);
1827 }
1828
Jeff Sharkey1b861272011-05-22 00:34:52 -07001829 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001830 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001831 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1832
Felipe Leme6a05eee2016-02-19 14:43:51 -08001833 final long token = Binder.clearCallingIdentity();
1834 try {
1835 maybeRefreshTrustedTime();
1836 synchronized (mRulesLock) {
1837 normalizePoliciesLocked(policies);
1838 updateNetworkEnabledLocked();
1839 updateNetworkRulesLocked();
1840 updateNotificationsLocked();
1841 writePolicyLocked();
1842 }
1843 } finally {
1844 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001845 }
1846 }
1847
Dianne Hackborn497175b2014-07-01 12:56:08 -07001848 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001849 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001850 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1851 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001852 }
1853
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001854 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001855 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001856 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001857 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001858 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1859 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1860 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001861 } catch (SecurityException e) {
1862 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001863
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001864 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1865 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1866 return new NetworkPolicy[0];
1867 }
Svet Ganov16a16892015-04-16 10:32:04 -07001868 }
1869
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001870 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001871 final int size = mNetworkPolicy.size();
1872 final NetworkPolicy[] policies = new NetworkPolicy[size];
1873 for (int i = 0; i < size; i++) {
1874 policies[i] = mNetworkPolicy.valueAt(i);
1875 }
1876 return policies;
1877 }
1878 }
1879
1880 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001881 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001882 }
1883
1884 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1885 final TelephonyManager tele = TelephonyManager.from(mContext);
1886 final String[] merged = tele.getMergedSubscriberIds();
1887
1888 mNetworkPolicy.clear();
1889 for (NetworkPolicy policy : policies) {
1890 // When two normalized templates conflict, prefer the most
1891 // restrictive policy
1892 policy.template = NetworkTemplate.normalize(policy.template, merged);
1893 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1894 if (existing == null || existing.compareTo(policy) > 0) {
1895 if (existing != null) {
1896 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1897 }
1898 mNetworkPolicy.put(policy.template, policy);
1899 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001900 }
1901 }
1902
1903 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001904 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001905 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001906
1907 final long token = Binder.clearCallingIdentity();
1908 try {
1909 performSnooze(template, TYPE_LIMIT);
1910 } finally {
1911 Binder.restoreCallingIdentity(token);
1912 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001913 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001914
Dianne Hackborn497175b2014-07-01 12:56:08 -07001915 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001916 maybeRefreshTrustedTime();
1917 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001918 synchronized (mRulesLock) {
1919 // find and snooze local policy that matches
1920 final NetworkPolicy policy = mNetworkPolicy.get(template);
1921 if (policy == null) {
1922 throw new IllegalArgumentException("unable to find policy for " + template);
1923 }
1924
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001925 switch (type) {
1926 case TYPE_WARNING:
1927 policy.lastWarningSnooze = currentTime;
1928 break;
1929 case TYPE_LIMIT:
1930 policy.lastLimitSnooze = currentTime;
1931 break;
1932 default:
1933 throw new IllegalArgumentException("unexpected type");
1934 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001935
Jeff Sharkey32566012014-12-02 18:30:14 -08001936 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001937 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001938 updateNetworkRulesLocked();
1939 updateNotificationsLocked();
1940 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001941 }
1942 }
1943
1944 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001945 public void onTetheringChanged(String iface, boolean tethering) {
1946 // No need to enforce permission because setRestrictBackground() will do it.
1947 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1948 synchronized (mRulesLock) {
1949 if (mRestrictBackground && tethering) {
1950 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1951 setRestrictBackground(false);
1952 }
1953 }
1954 }
1955
1956 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001957 public void setRestrictBackground(boolean restrictBackground) {
1958 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001959 final long token = Binder.clearCallingIdentity();
1960 try {
1961 maybeRefreshTrustedTime();
1962 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001963 if (restrictBackground == mRestrictBackground) {
1964 // Ideally, UI should never allow this scenario...
1965 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1966 return;
1967 }
1968 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001969 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001970
Felipe Leme6a05eee2016-02-19 14:43:51 -08001971 } finally {
1972 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001973 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001974
1975 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1976 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001977 }
1978
Felipe Leme70c57c22016-03-29 10:45:13 -07001979 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1980 final boolean oldRestrictBackground = mRestrictBackground;
1981 mRestrictBackground = restrictBackground;
1982 // Must whitelist foreground apps before turning data saver mode on.
1983 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1984 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
1985 updateRulesForRestrictBackgroundLocked();
1986 try {
1987 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
1988 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
1989 mRestrictBackground = oldRestrictBackground;
1990 // TODO: if it knew the foreground apps (see TODO above), it could call
1991 // updateRulesForRestrictBackgroundLocked() again to restore state.
1992 return;
1993 }
1994 } catch (RemoteException e) {
1995 // ignored; service lives in system_server
1996 }
1997 updateNotificationsLocked();
1998 writePolicyLocked();
1999 }
2000
Jeff Sharkey46645002011-07-27 21:11:21 -07002001 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002002 public void addRestrictBackgroundWhitelistedUid(int uid) {
2003 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002004 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002005 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002006 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002007 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002008 if (oldStatus) {
2009 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2010 return;
2011 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002012 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002013 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002014 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002015 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2016 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2017 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2018 + " from revoked restrict background whitelist");
2019 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2020 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002021 if (needFirewallRules) {
2022 // Only update firewall rules if necessary...
2023 updateRuleForRestrictBackgroundLocked(uid);
2024 }
2025 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08002026 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002027 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002028 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
2029 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2030 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002031 }
2032
2033 @Override
2034 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2035 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002036 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002037 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002038 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002039 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002040 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2041 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002042 }
2043
Felipe Leme70c57c22016-03-29 10:45:13 -07002044 /**
2045 * Removes a uid from the restricted background whitelist, returning whether its current
2046 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2047 */
2048 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2049 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002050 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
2051 if (!oldStatus) {
2052 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2053 return false;
2054 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002055 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002056 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002057 mRestrictBackgroundWhitelistUids.delete(uid);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002058 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2059 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2060 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2061 + " to revoked restrict background whitelist");
2062 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2063 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002064 if (needFirewallRules) {
2065 // Only update firewall rules if necessary...
2066 updateRuleForRestrictBackgroundLocked(uid, uidDeleted);
2067 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002068 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002069 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002070 writePolicyLocked();
2071 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002072 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2073 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002074 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002075 }
2076
2077 @Override
2078 public int[] getRestrictBackgroundWhitelistedUids() {
2079 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2080 synchronized (mRulesLock) {
2081 final int size = mRestrictBackgroundWhitelistUids.size();
2082 final int[] whitelist = new int[size];
2083 for (int i = 0; i < size; i++) {
2084 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2085 }
2086 if (LOGV) {
2087 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2088 + mRestrictBackgroundWhitelistUids);
2089 }
2090 return whitelist;
2091 }
2092 }
2093
2094 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002095 public int getRestrictBackgroundByCaller() {
2096 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2097 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002098
Felipe Leme1b103232016-01-22 09:44:57 -08002099 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002100 // Must clear identity because getUidPolicy() is restricted to system.
2101 final long token = Binder.clearCallingIdentity();
2102 final int policy;
2103 try {
2104 policy = getUidPolicy(uid);
2105 } finally {
2106 Binder.restoreCallingIdentity(token);
2107 }
2108 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2109 // App is blacklisted.
2110 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2111 }
Felipe Leme1b103232016-01-22 09:44:57 -08002112 if (!mRestrictBackground) {
2113 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2114 }
2115 return mRestrictBackgroundWhitelistUids.get(uid)
2116 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2117 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2118 }
2119 }
2120
2121 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002122 public boolean getRestrictBackground() {
2123 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2124
2125 synchronized (mRulesLock) {
2126 return mRestrictBackground;
2127 }
2128 }
2129
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002130 @Override
2131 public void setDeviceIdleMode(boolean enabled) {
2132 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2133
2134 synchronized (mRulesLock) {
2135 if (mDeviceIdleMode != enabled) {
2136 mDeviceIdleMode = enabled;
2137 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002138 // Device idle change means we need to rebuild rules for all
2139 // known apps, so do a global refresh.
2140 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002141 }
2142 if (enabled) {
2143 EventLogTags.writeDeviceIdleOnPhase("net");
2144 } else {
2145 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002146 }
2147 }
2148 }
2149 }
2150
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002151 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002152 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2153 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002154 if (policy.template.matches(ident)) {
2155 return policy;
2156 }
2157 }
2158 return null;
2159 }
2160
2161 @Override
2162 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2163 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2164
2165 // only returns usage summary, so we don't require caller to have
2166 // READ_NETWORK_USAGE_HISTORY.
2167 final long token = Binder.clearCallingIdentity();
2168 try {
2169 return getNetworkQuotaInfoUnchecked(state);
2170 } finally {
2171 Binder.restoreCallingIdentity(token);
2172 }
2173 }
2174
2175 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2176 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2177
2178 final NetworkPolicy policy;
2179 synchronized (mRulesLock) {
2180 policy = findPolicyForNetworkLocked(ident);
2181 }
2182
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002183 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002184 // missing policy means we can't derive useful quota info
2185 return null;
2186 }
2187
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002188 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002189
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002190 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002191 final long start = computeLastCycleBoundary(currentTime, policy);
2192 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002193 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002194
2195 // report soft and hard limits under policy
2196 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2197 : NetworkQuotaInfo.NO_LIMIT;
2198 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2199 : NetworkQuotaInfo.NO_LIMIT;
2200
2201 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2202 }
2203
Jeff Sharkey46645002011-07-27 21:11:21 -07002204 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002205 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002206 if (state.networkInfo == null) {
2207 return false;
2208 }
2209
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002210 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2211
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002212 // roaming networks are always considered metered
2213 if (ident.getRoaming()) {
2214 return true;
2215 }
2216
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002217 final NetworkPolicy policy;
2218 synchronized (mRulesLock) {
2219 policy = findPolicyForNetworkLocked(ident);
2220 }
2221
2222 if (policy != null) {
2223 return policy.metered;
2224 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002225 final int type = state.networkInfo.getType();
2226 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2227 return true;
2228 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002229 return false;
2230 }
2231 }
2232
2233 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002234 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002235 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002236
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002237 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2238
Dianne Hackborn497175b2014-07-01 12:56:08 -07002239 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002240 for (String arg : args) {
2241 argSet.add(arg);
2242 }
2243
Jeff Sharkey1b861272011-05-22 00:34:52 -07002244 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002245 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002246 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2247 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002248 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002249
Jeff Sharkey32566012014-12-02 18:30:14 -08002250 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002251 updateNetworkEnabledLocked();
2252 updateNetworkRulesLocked();
2253 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002254 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002255
2256 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002257 return;
2258 }
2259
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002260 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002261 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002262 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002263 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002264 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002265 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002266 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2267 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002268 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002269 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002270
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002271 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2272
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002273 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002274 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002275 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002276 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002277 final int uid = mUidPolicy.keyAt(i);
2278 final int policy = mUidPolicy.valueAt(i);
2279 fout.print("UID=");
2280 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002281 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002282 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002283 fout.println();
2284 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002285 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002286
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002287 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2288 if (size > 0) {
2289 fout.println("Power save whitelist (except idle) app ids:");
2290 fout.increaseIndent();
2291 for (int i = 0; i < size; i++) {
2292 fout.print("UID=");
2293 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2294 fout.print(": ");
2295 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2296 fout.println();
2297 }
2298 fout.decreaseIndent();
2299 }
2300
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002301 size = mPowerSaveWhitelistAppIds.size();
2302 if (size > 0) {
2303 fout.println("Power save whitelist app ids:");
2304 fout.increaseIndent();
2305 for (int i = 0; i < size; i++) {
2306 fout.print("UID=");
2307 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2308 fout.print(": ");
2309 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2310 fout.println();
2311 }
2312 fout.decreaseIndent();
2313 }
2314
Felipe Lemeb85a6372016-01-14 16:16:16 -08002315 size = mRestrictBackgroundWhitelistUids.size();
2316 if (size > 0) {
2317 fout.println("Restrict background whitelist uids:");
2318 fout.increaseIndent();
2319 for (int i = 0; i < size; i++) {
2320 fout.print("UID=");
2321 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2322 fout.println();
2323 }
2324 fout.decreaseIndent();
2325 }
2326
Felipe Lemea9505cc2016-02-26 10:28:41 -08002327 size = mDefaultRestrictBackgroundWhitelistUids.size();
2328 if (size > 0) {
2329 fout.println("Default restrict background whitelist uids:");
2330 fout.increaseIndent();
2331 for (int i = 0; i < size; i++) {
2332 fout.print("UID=");
2333 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2334 fout.println();
2335 }
2336 fout.decreaseIndent();
2337 }
2338
2339 size = mRestrictBackgroundWhitelistRevokedUids.size();
2340 if (size > 0) {
2341 fout.println("Default restrict background whitelist uids revoked by users:");
2342 fout.increaseIndent();
2343 for (int i = 0; i < size; i++) {
2344 fout.print("UID=");
2345 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2346 fout.println();
2347 }
2348 fout.decreaseIndent();
2349 }
2350
Jeff Sharkey1b861272011-05-22 00:34:52 -07002351 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002352 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002353 collectKeys(mUidRules, knownUids);
2354
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002355 fout.println("Status for known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002356 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002357 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002358 for (int i = 0; i < size; i++) {
2359 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002360 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002361 fout.print(uid);
2362
Jeff Sharkeydc988062015-09-14 10:09:47 -07002363 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002364 fout.print(" state=");
2365 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002366 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2367 fout.print(" (fg)");
2368 } else {
2369 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2370 ? " (fg svc)" : " (bg)");
2371 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002372
Jeff Sharkeydc988062015-09-14 10:09:47 -07002373 final int rule = mUidRules.get(uid, RULE_UNKNOWN);
2374 fout.print(" rule=");
Felipe Lemef28983d2016-03-25 12:18:23 -07002375 fout.print(ruleToString(rule));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002376
2377 fout.println();
2378 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002379 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002380 }
2381 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002382
Felipe Lemef28983d2016-03-25 12:18:23 -07002383 private String ruleToString(int rule) {
2384 return DebugUtils.valueToString(NetworkPolicyManager.class, "RULE_", rule);
2385 }
2386
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002387 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002388 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2389 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002390 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002391 this, in, out, err, args, resultReceiver);
2392 }
2393
2394 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002395 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002396 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2397
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002398 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002399 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002400 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002401 }
2402
Felipe Lemef28983d2016-03-25 12:18:23 -07002403 private boolean isUidForegroundLocked(int uid) {
2404 return isUidStateForegroundLocked(
2405 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2406 }
2407
Felipe Lemeef89c902016-03-30 15:11:31 -07002408 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2409 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2410 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2411 }
2412
Felipe Lemef28983d2016-03-25 12:18:23 -07002413 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002414 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002415 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002416 }
2417
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002418 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002419 * Process state of UID changed; if needed, will trigger
Felipe Leme70c57c22016-03-29 10:45:13 -07002420 * {@link #updateRuleForRestrictBackgroundLocked(int)}.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002421 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002422 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002423 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2424 if (oldUidState != uidState) {
2425 // state changed, push updated rules
2426 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002427 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002428 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2429 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2430 if (mDeviceIdleMode) {
2431 updateRuleForDeviceIdleLocked(uid);
2432 }
2433 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002434 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002435 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002436 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002437 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002438 }
2439 }
2440
Felipe Lemef28983d2016-03-25 12:18:23 -07002441 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002442 final int index = mUidState.indexOfKey(uid);
2443 if (index >= 0) {
2444 final int oldUidState = mUidState.valueAt(index);
2445 mUidState.removeAt(index);
2446 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002447 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002448 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002449 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002450 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002451 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002452 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002453 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002454 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002455 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002456 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002457 }
2458 }
2459
Felipe Lemef28983d2016-03-25 12:18:23 -07002460 // adjust stats accounting based on foreground status
2461 private void updateNetworkStats(int uid, boolean uidForeground) {
2462 try {
2463 mNetworkStats.setUidForeground(uid, uidForeground);
2464 } catch (RemoteException e) {
2465 // ignored; service lives in system_server
2466 }
2467 }
2468
2469 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2470 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002471 final boolean oldForeground =
2472 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2473 final boolean newForeground =
2474 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002475 if (oldForeground != newForeground) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002476 updateRuleForRestrictBackgroundLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002477 }
2478 }
2479
Jeff Sharkeya4620792011-05-20 15:29:23 -07002480 private void updateScreenOn() {
2481 synchronized (mRulesLock) {
2482 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002483 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002484 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002485 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002486 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002487 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002488 }
2489 }
2490
2491 /**
2492 * Update rules that might be changed by {@link #mScreenOn} value.
2493 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002494 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002495 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002496 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002497 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002498 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002499 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002500 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002501 }
2502 }
2503 }
2504
Felipe Leme011b98f2016-02-10 17:28:31 -08002505 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002506 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2507 }
2508
Felipe Lemeef89c902016-03-30 15:11:31 -07002509 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2510 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2511 }
2512
Felipe Leme011b98f2016-02-10 17:28:31 -08002513 void updateRulesForRestrictPowerLocked() {
2514 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2515 mUidFirewallPowerSaveRules);
2516 }
2517
Felipe Lemef28983d2016-03-25 12:18:23 -07002518 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002519 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2520 }
2521
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002522 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002523 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2524 mUidFirewallDozableRules);
2525 }
2526
2527 void updateRuleForDeviceIdleLocked(int uid) {
2528 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2529 }
2530
Felipe Lemef28983d2016-03-25 12:18:23 -07002531 // NOTE: since both fw_dozable and fw_powersave uses the same map
2532 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002533 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2534 SparseIntArray rules) {
2535 if (enabled) {
2536 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002537 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002538 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002539 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002540 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002541 for (int ui = users.size() - 1; ui >= 0; ui--) {
2542 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002543 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002544 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2545 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2546 int uid = UserHandle.getUid(user.id, appId);
2547 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2548 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002549 }
2550 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2551 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2552 int uid = UserHandle.getUid(user.id, appId);
2553 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2554 }
2555 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002556 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002557 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002558 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2559 }
2560 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002561 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002562 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002563
Felipe Leme011b98f2016-02-10 17:28:31 -08002564 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002565 }
2566
Felipe Lemef28983d2016-03-25 12:18:23 -07002567 // NOTE: since both fw_dozable and fw_powersave uses the same map
2568 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002569 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2570 if (enabled) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002571 int appId = UserHandle.getAppId(uid);
2572 if (mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId)
Felipe Leme011b98f2016-02-10 17:28:31 -08002573 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2574 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002575 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002576 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002577 }
2578 }
2579 }
2580
2581 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002582 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2583 uidRules.clear();
2584
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002585 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002586 final List<UserInfo> users = mUserManager.getUsers();
2587 for (int ui = users.size() - 1; ui >= 0; ui--) {
2588 UserInfo user = users.get(ui);
2589 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2590 for (int uid : idleUids) {
2591 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002592 // quick check: if this uid doesn't have INTERNET permission, it
2593 // doesn't have network access anyway, so it is a waste to mess
2594 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002595 if (hasInternetPermissions(uid)) {
2596 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002597 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002598 }
2599 }
2600 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002601
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002602 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2603 }
2604
2605 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002606 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002607
2608 int appId = UserHandle.getAppId(uid);
2609 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)) {
2610 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2611 } else {
2612 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2613 }
2614 }
2615
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002616 void updateRulesForAppIdleParoleLocked() {
2617 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2618 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002619 }
2620
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002621 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002622 * Update rules that might be changed by {@link #mRestrictBackground},
2623 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002624 */
Felipe Leme76010a32016-03-17 13:03:11 -07002625 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002626 long start;
2627 if (LOGD) start = System.currentTimeMillis();
2628
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002629 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002630 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002631 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002632 updateRulesForRestrictBackgroundLocked();
Felipe Leme70c57c22016-03-29 10:45:13 -07002633 setRestrictBackgroundLocked(mRestrictBackground);
Felipe Leme76010a32016-03-17 13:03:11 -07002634
2635 // If the set of restricted networks may have changed, re-evaluate those.
2636 if (restrictedNetworksChanged) {
2637 normalizePoliciesLocked();
2638 updateNetworkRulesLocked();
2639 }
2640 if (LOGD) {
2641 final long delta = System.currentTimeMillis() - start;
2642 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2643 + delta + "ms");
2644 }
2645 }
2646
Felipe Lemef28983d2016-03-25 12:18:23 -07002647 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002648 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002649
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002650 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002651 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002652 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002653 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2654 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2655 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002656
Felipe Leme03e689d2016-03-02 16:17:38 -08002657 final int usersSize = users.size();
2658 final int appsSize = apps.size();
2659 for (int i = 0; i < usersSize; i++) {
2660 final UserInfo user = users.get(i);
2661 for (int j = 0; j < appsSize; j++) {
2662 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002663 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002664 updateRuleForRestrictBackgroundLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002665 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002666 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002667 }
2668
Felipe Leme76010a32016-03-17 13:03:11 -07002669 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002670 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002671 for (int i = 0; i < users.size(); i++) {
2672 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002673 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002674 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002675 int uid = UserHandle.getUid(user.id, appId);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002676 updateRuleForAppIdleLocked(uid);
2677 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002678 updateRuleForRestrictPowerLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002679 }
2680 }
2681 }
2682
Felipe Leme70c57c22016-03-29 10:45:13 -07002683 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2684 // methods below could be merged into a isUidValidForRules() method.
2685 private boolean isUidValidForBlacklistRules(int uid) {
2686 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002687 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002688 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002689 return true;
2690 }
2691
2692 return false;
2693 }
2694
Felipe Leme70c57c22016-03-29 10:45:13 -07002695 private boolean isUidValidForWhitelistRules(int uid) {
2696 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2697 }
2698
Amith Yamasani15e472352015-04-24 19:06:07 -07002699 private boolean isUidIdle(int uid) {
2700 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2701 final int userId = UserHandle.getUserId(uid);
2702
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002703 if (!ArrayUtils.isEmpty(packages)) {
2704 for (String packageName : packages) {
2705 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2706 return false;
2707 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002708 }
2709 }
2710 return true;
2711 }
2712
2713 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002714 * Checks if an uid has INTERNET permissions.
2715 * <p>
2716 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002717 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002718 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002719 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002720 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002721 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002722 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002723 }
2724 } catch (RemoteException e) {
2725 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002726 return true;
2727 }
2728
2729 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002730 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002731 *
Felipe Lemef28983d2016-03-25 12:18:23 -07002732 * <p>There are currently 2 types of restriction rules:
2733 * <ul>
2734 * <li>Battery Saver Mode (also referred as power save).
2735 * <li>Data Saver Mode (formerly known as restrict background data).
2736 * </ul>
Felipe Leme47585ba2016-02-09 16:56:32 -08002737 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002738 private void updateRestrictionRulesForUidLocked(int uid) {
2739 updateRuleForRestrictPowerLocked(uid);
2740 updateRuleForRestrictBackgroundLocked(uid);
2741 }
2742
Felipe Leme70c57c22016-03-29 10:45:13 -07002743 /**
2744 * Applies network rules to bandwidth controllers based on process state and user-defined
2745 * restrictions (blacklist / whitelist).
2746 *
2747 * <p>
2748 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2749 * networks:
2750 * <ul>
2751 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2752 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2753 * also blacklisted.
2754 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2755 * no UIDs other those whitelisted will have access.
2756 * <ul>
2757 *
2758 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2759 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2760 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2761 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
2762 * this ({@link #updateRuleForRestrictBackgroundLocked(int)}) to propagate the rules to
2763 * {@link INetworkManagementService}, but this method should also be called in events (like
2764 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2765 * following rules should also be applied:
2766 *
2767 * <ul>
2768 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2769 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2770 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2771 * {@code bw_penalty_box}.
2772 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2773 * </ul>
2774 *
2775 * <p>For optimization, the rules are only applied on user apps that have internet access
2776 * permission, since there is no need to change the {@code iptables} rule if the app does not
2777 * have permission to use the internet.
2778 *
2779 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
2780 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002781 private void updateRuleForRestrictBackgroundLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002782 updateRuleForRestrictBackgroundLocked(uid, false);
2783 }
2784
2785 /**
2786 * Overloaded version of {@link #updateRuleForRestrictBackgroundLocked(int)} called when an
2787 * app is removed - it ignores the UID validity check.
2788 */
2789 private void updateRuleForRestrictBackgroundLocked(int uid, boolean uidDeleted) {
2790 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2791 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2792 return;
2793 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002794
Dianne Hackborn497175b2014-07-01 12:56:08 -07002795 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002796 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Felipe Leme70c57c22016-03-29 10:45:13 -07002797 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2798 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002799
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002800 int newRule = RULE_UNKNOWN;
2801 final int oldRule = mUidRules.get(uid, RULE_UNKNOWN);
Felipe Leme76010a32016-03-17 13:03:11 -07002802
Felipe Leme70c57c22016-03-29 10:45:13 -07002803 // First step: define the new rule based on user restrictions and foreground state.
2804 if (isForeground) {
2805 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2806 newRule = RULE_TEMPORARY_ALLOW_METERED;
2807 }
2808 } else {
2809 if (isBlacklisted) {
Felipe Leme76010a32016-03-17 13:03:11 -07002810 newRule = RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -07002811 } else if (isWhitelisted) {
2812 newRule = RULE_ALLOW_METERED;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002813 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002814 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002815
Felipe Lemef28983d2016-03-25 12:18:23 -07002816 if (LOGV) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002817 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + "):"
2818 + " isForeground=" +isForeground + ", isBlacklisted: " + isBlacklisted
2819 + ", isWhitelisted: " + isWhitelisted + ", newRule: " + ruleToString(newRule)
2820 + ", oldRule: " + ruleToString(oldRule));
Felipe Lemef28983d2016-03-25 12:18:23 -07002821 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002822
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002823 if (newRule == RULE_UNKNOWN) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002824 mUidRules.delete(uid);
2825 } else {
Felipe Leme76010a32016-03-17 13:03:11 -07002826 mUidRules.put(uid, newRule);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002827 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002828
Felipe Leme70c57c22016-03-29 10:45:13 -07002829 // Second step: apply bw changes based on change of state.
2830 if (newRule != oldRule) {
2831 if (newRule == RULE_TEMPORARY_ALLOW_METERED) {
2832 // Temporarily whitelist foreground app, removing from blacklist if necessary
2833 // (since bw_penalty_box prevails over bw_happy_box).
2834
2835 setMeteredNetworkWhitelist(uid, true);
2836 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2837 // but ideally it should be just:
2838 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2839 if (isBlacklisted) {
2840 setMeteredNetworkBlacklist(uid, false);
2841 }
2842 } else if (oldRule == RULE_TEMPORARY_ALLOW_METERED) {
2843 // Remove temporary whitelist from app that is not on foreground anymore.
2844
2845 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2846 // but ideally they should be just:
2847 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2848 // setMeteredNetworkBlacklist(uid, isBlacklisted);
2849 if (!isWhitelisted) {
2850 setMeteredNetworkWhitelist(uid, false);
2851 }
2852 if (isBlacklisted) {
2853 setMeteredNetworkBlacklist(uid, true);
2854 }
2855 } else if (newRule == RULE_REJECT_METERED || oldRule == RULE_REJECT_METERED) {
2856 // Flip state because app was explicitly added or removed to blacklist.
2857 setMeteredNetworkBlacklist(uid, isBlacklisted);
2858 if (oldRule == RULE_REJECT_METERED && isWhitelisted) {
2859 // Since blacklist prevails over whitelist, we need to handle the special case
2860 // where app is whitelisted and blacklisted at the same time (although such
2861 // scenario should be blocked by the UI), then blacklist is removed.
2862 setMeteredNetworkWhitelist(uid, isWhitelisted);
2863 }
2864 } else if (newRule == RULE_ALLOW_METERED || oldRule == RULE_ALLOW_METERED) {
2865 // Flip state because app was explicitly added or removed to whitelist.
2866 setMeteredNetworkWhitelist(uid, isWhitelisted);
2867 } else {
2868 // All scenarios should have been covered above
2869 Log.wtf(TAG, "Unexpected change of state for " + uid
2870 + ": foreground=" + isForeground + ", whitelisted=" + isWhitelisted
2871 + ", blacklisted=" + isBlacklisted + ", newRule="
2872 + ruleToString(newRule) + ", oldRule=" + ruleToString(oldRule));
2873 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002874
2875 // dispatch changed rule to existing listeners
Felipe Leme76010a32016-03-17 13:03:11 -07002876 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newRule).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07002877 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002878 }
2879
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002880 private class AppIdleStateChangeListener
2881 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
2882
2883 @Override
2884 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
2885 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07002886 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
2887 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002888 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002889 updateRuleForAppIdleLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002890 }
2891 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07002892 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002893 }
2894
2895 @Override
2896 public void onParoleStateChanged(boolean isParoleOn) {
2897 synchronized (mRulesLock) {
2898 updateRulesForAppIdleParoleLocked();
2899 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002900 }
2901 }
2902
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002903 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
2904 if (listener != null) {
2905 try {
2906 listener.onUidRulesChanged(uid, uidRules);
2907 } catch (RemoteException ignored) {
2908 }
2909 }
2910 }
2911
2912 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
2913 String[] meteredIfaces) {
2914 if (listener != null) {
2915 try {
2916 listener.onMeteredIfacesChanged(meteredIfaces);
2917 } catch (RemoteException ignored) {
2918 }
2919 }
2920 }
2921
2922 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
2923 boolean restrictBackground) {
2924 if (listener != null) {
2925 try {
2926 listener.onRestrictBackgroundChanged(restrictBackground);
2927 } catch (RemoteException ignored) {
2928 }
2929 }
2930 }
2931
2932 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
2933 int uid, boolean whitelisted) {
2934 if (listener != null) {
2935 try {
2936 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
2937 } catch (RemoteException ignored) {
2938 }
2939 }
2940 }
2941
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002942 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07002943 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002944 public boolean handleMessage(Message msg) {
2945 switch (msg.what) {
2946 case MSG_RULES_CHANGED: {
2947 final int uid = msg.arg1;
2948 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002949 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002950 final int length = mListeners.beginBroadcast();
2951 for (int i = 0; i < length; i++) {
2952 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002953 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002954 }
2955 mListeners.finishBroadcast();
2956 return true;
2957 }
2958 case MSG_METERED_IFACES_CHANGED: {
2959 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002960 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002961 final int length = mListeners.beginBroadcast();
2962 for (int i = 0; i < length; i++) {
2963 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002964 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07002965 }
2966 mListeners.finishBroadcast();
2967 return true;
2968 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002969 case MSG_LIMIT_REACHED: {
2970 final String iface = (String) msg.obj;
2971
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002972 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08002973 synchronized (mRulesLock) {
2974 if (mMeteredIfaces.contains(iface)) {
2975 try {
2976 // force stats update to make sure we have
2977 // numbers that caused alert to trigger.
2978 mNetworkStats.forceUpdate();
2979 } catch (RemoteException e) {
2980 // ignored; service lives in system_server
2981 }
2982
2983 updateNetworkEnabledLocked();
2984 updateNotificationsLocked();
2985 }
2986 }
2987 return true;
2988 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002989 case MSG_RESTRICT_BACKGROUND_CHANGED: {
2990 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002991 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002992 final int length = mListeners.beginBroadcast();
2993 for (int i = 0; i < length; i++) {
2994 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002995 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002996 }
2997 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08002998 final Intent intent =
2999 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3000 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3001 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3002 return true;
3003 }
3004 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003005 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3006 // - when an app is whitelisted
3007 // - when an app is blacklisted
3008 //
3009 // Whether the internal listeners (INetworkPolicyListener implementations) or
3010 // app broadcast receivers are notified depend on the following rules:
3011 //
3012 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3013 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3014 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003015 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003016 final boolean changed = msg.arg2 == 1;
3017 final Boolean whitelisted = (Boolean) msg.obj;
3018
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003019 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003020 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003021 final boolean whitelistedBool = whitelisted.booleanValue();
3022 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3023 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003024 final int length = mListeners.beginBroadcast();
3025 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003026 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003027 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3028 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003029 }
3030 mListeners.finishBroadcast();
3031 }
3032
Felipe Leme9778f762016-01-27 14:46:39 -08003033 final PackageManager pm = mContext.getPackageManager();
3034 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003035 if (changed && packages != null) {
3036 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003037 final int userId = UserHandle.getUserId(uid);
3038 for (String packageName : packages) {
3039 final Intent intent = new Intent(
3040 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3041 intent.setPackage(packageName);
3042 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3043 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3044 }
Felipe Leme9778f762016-01-27 14:46:39 -08003045 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003046 return true;
3047 }
3048 case MSG_ADVISE_PERSIST_THRESHOLD: {
3049 final long lowestRule = (Long) msg.obj;
3050 try {
3051 // make sure stats are recorded frequently enough; we aim
3052 // for 2MB threshold for 2GB/month rules.
3053 final long persistThreshold = lowestRule / 1000;
3054 mNetworkStats.advisePersistThreshold(persistThreshold);
3055 } catch (RemoteException e) {
3056 // ignored; service lives in system_server
3057 }
3058 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003059 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003060 case MSG_SCREEN_ON_CHANGED: {
3061 updateScreenOn();
3062 return true;
3063 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003064 case MSG_UPDATE_INTERFACE_QUOTA: {
3065 removeInterfaceQuota((String) msg.obj);
3066 // int params need to be stitched back into a long
3067 setInterfaceQuota((String) msg.obj,
3068 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3069 return true;
3070 }
3071 case MSG_REMOVE_INTERFACE_QUOTA: {
3072 removeInterfaceQuota((String) msg.obj);
3073 return true;
3074 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003075 default: {
3076 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003077 }
3078 }
3079 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003080 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003081
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003082 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003083 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003084 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003085 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003086 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003087 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003088 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003089 }
3090 }
3091
3092 private void removeInterfaceQuota(String iface) {
3093 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003094 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003095 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003096 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003097 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003098 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003099 }
3100 }
3101
Felipe Leme70c57c22016-03-29 10:45:13 -07003102 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3103 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003104 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003105 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003106 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003107 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3108 } catch (RemoteException e) {
3109 // ignored; service lives in system_server
3110 }
3111 }
3112
3113 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3114 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3115 try {
3116 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3117 } catch (IllegalStateException e) {
3118 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003119 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003120 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003121 }
3122 }
3123
Amith Yamasani15e472352015-04-24 19:06:07 -07003124 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003125 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3126 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3127 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003128 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003129 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003130 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003131 int size = uidRules.size();
3132 int[] uids = new int[size];
3133 int[] rules = new int[size];
3134 for(int index = size - 1; index >= 0; --index) {
3135 uids[index] = uidRules.keyAt(index);
3136 rules[index] = uidRules.valueAt(index);
3137 }
3138 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003139 } catch (IllegalStateException e) {
3140 Log.wtf(TAG, "problem setting firewall uid rules", e);
3141 } catch (RemoteException e) {
3142 // ignored; service lives in system_server
3143 }
3144 }
3145
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003146 /**
3147 * Add or remove a uid to the firewall blacklist for all network ifaces.
3148 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003149 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003150 if (chain == FIREWALL_CHAIN_DOZABLE) {
3151 mUidFirewallDozableRules.put(uid, rule);
3152 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3153 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003154 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3155 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003156 }
3157
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003158 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003159 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003160 } catch (IllegalStateException e) {
3161 Log.wtf(TAG, "problem setting firewall uid rules", e);
3162 } catch (RemoteException e) {
3163 // ignored; service lives in system_server
3164 }
3165 }
3166
3167 /**
3168 * Add or remove a uid to the firewall blacklist for all network ifaces.
3169 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003170 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003171 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3172 mFirewallChainStates.get(chain) == enable) {
3173 // All is the same, nothing to do.
3174 return;
3175 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003176 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003177 try {
3178 mNetworkManager.setFirewallChainEnabled(chain, enable);
3179 } catch (IllegalStateException e) {
3180 Log.wtf(TAG, "problem enable firewall chain", e);
3181 } catch (RemoteException e) {
3182 // ignored; service lives in system_server
3183 }
3184 }
3185
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003186 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3187 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003188 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003189 } catch (RuntimeException e) {
3190 Slog.w(TAG, "problem reading network stats: " + e);
3191 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003192 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003193 // ignored; service lives in system_server
3194 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003195 }
3196 }
3197
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003198 private boolean isBandwidthControlEnabled() {
3199 final long token = Binder.clearCallingIdentity();
3200 try {
3201 return mNetworkManager.isBandwidthControlEnabled();
3202 } catch (RemoteException e) {
3203 // ignored; service lives in system_server
3204 return false;
3205 } finally {
3206 Binder.restoreCallingIdentity(token);
3207 }
3208 }
3209
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003210 /**
3211 * Try refreshing {@link #mTime} when stale.
3212 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003213 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003214 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003215 mTime.forceRefresh();
3216 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003217 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003218
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003219 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003220 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3221 }
3222
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003223 private static Intent buildAllowBackgroundDataIntent() {
3224 return new Intent(ACTION_ALLOW_BACKGROUND);
3225 }
3226
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003227 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3228 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3229 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3230 return intent;
3231 }
3232
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003233 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3234 final Intent intent = new Intent();
3235 intent.setComponent(new ComponentName(
3236 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3237 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3238 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3239 return intent;
3240 }
3241
3242 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3243 final Intent intent = new Intent();
3244 intent.setComponent(new ComponentName(
3245 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3246 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3247 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3248 return intent;
3249 }
3250
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003251 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003252 public void addIdleHandler(IdleHandler handler) {
3253 mHandler.getLooper().getQueue().addIdleHandler(handler);
3254 }
3255
Jeff Sharkey1b861272011-05-22 00:34:52 -07003256 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3257 final int size = source.size();
3258 for (int i = 0; i < size; i++) {
3259 target.put(source.keyAt(i), true);
3260 }
3261 }
3262
Stuart Scottf1fb3972015-04-02 18:00:02 -07003263 @Override
3264 public void factoryReset(String subscriber) {
3265 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3266
Stuart Scotte3e314d2015-04-20 14:07:45 -07003267 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3268 return;
3269 }
3270
Stuart Scottf1fb3972015-04-02 18:00:02 -07003271 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003272 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003273 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3274 for (NetworkPolicy policy : policies) {
3275 if (policy.template.equals(template)) {
3276 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3277 policy.inferred = false;
3278 policy.clearSnooze();
3279 }
3280 }
3281 setNetworkPolicies(policies);
3282
3283 // Turn restrict background data off
3284 setRestrictBackground(false);
3285
Stuart Scotte3e314d2015-04-20 14:07:45 -07003286 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3287 // Remove app's "restrict background data" flag
3288 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3289 setUidPolicy(uid, POLICY_NONE);
3290 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003291 }
3292 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003293
3294 private class MyPackageMonitor extends PackageMonitor {
3295
3296 @Override
3297 public void onPackageRemoved(String packageName, int uid) {
3298 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3299 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003300 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003301 }
3302 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003303 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003304
3305 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3306
3307 @Override
3308 public void resetUserState(int userId) {
3309 synchronized (mRulesLock) {
3310 boolean changed = removeUserStateLocked(userId, false);
3311 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(userId) || changed;
3312 if (changed) {
3313 writePolicyLocked();
3314 }
3315 }
3316 }
3317 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003318}