blob: 4bdc23730fbefe2fae0c2768e8185a495e7bb3f7 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Dianne Hackborn497175b2014-07-01 12:56:08 -070092import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070093import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070094import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070095import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070097import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.Notification;
99import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700100import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700101import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700102import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700103import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.Intent;
105import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700106import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700107import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700109import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700110import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700111import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700112import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700113import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700114import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700116import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700117import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700118import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700119import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700120import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700121import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700122import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700123import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700126import android.net.wifi.WifiConfiguration;
127import android.net.wifi.WifiInfo;
128import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700129import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.os.Environment;
131import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700132import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700134import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700135import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700136import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700137import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700141import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600142import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700144import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700145import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700146import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800147import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700148import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700149import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700150import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700151import android.util.ArrayMap;
152import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700153import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700154import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700155import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700157import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700158import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700159import android.util.SparseBooleanArray;
160import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161import android.util.TrustedTime;
162import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700163
Jeff Sharkey497e4432011-06-14 17:27:29 -0700164import com.android.internal.R;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800165import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800166import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800167import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700168import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700169import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700170import com.android.server.DeviceIdleController;
171import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700172import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800173import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600174
175import libcore.io.IoUtils;
176
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178
179import org.xmlpull.v1.XmlPullParser;
180import org.xmlpull.v1.XmlPullParserException;
181import org.xmlpull.v1.XmlSerializer;
182
183import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700184import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import java.io.FileInputStream;
186import java.io.FileNotFoundException;
187import java.io.FileOutputStream;
188import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700189import java.io.PrintWriter;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100190import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700191import java.util.ArrayList;
192import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700193import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700195/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700196 * Service that maintains low-level network policy rules, using
197 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700198 * <p>
199 * Derives active rules by combining a given policy with other system status,
200 * and delivers to listeners, such as {@link ConnectivityManager}, for
201 * enforcement.
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700202 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700203public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800204 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700205 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700206 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700207
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700208 private static final int VERSION_INIT = 1;
209 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700210 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800211 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800212 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800213 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700214 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700215 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700216 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700217 private static final int VERSION_SWITCH_UID = 10;
218 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800220 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700221 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800222 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700223 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800224 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700225 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700226
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700227 private static final String TAG_POLICY_LIST = "policy-list";
228 private static final String TAG_NETWORK_POLICY = "network-policy";
229 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700230 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800231 private static final String TAG_WHITELIST = "whitelist";
232 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800233 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700234
235 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700236 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700237 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
238 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700239 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700240 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800241 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242 private static final String ATTR_WARNING_BYTES = "warningBytes";
243 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700244 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800245 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
246 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800247 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700248 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700249 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700250 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251 private static final String ATTR_POLICY = "policy";
252
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800253 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800254 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800255 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800256 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700257
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700258 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
259
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700260 private static final int MSG_RULES_CHANGED = 1;
261 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800262 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800263 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700264 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700265 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800266 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700267 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
268 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700269
Jeff Sharkey75279902011-05-24 18:39:45 -0700270 private final Context mContext;
271 private final IActivityManager mActivityManager;
272 private final IPowerManager mPowerManager;
273 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700274 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700275 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700277 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700278
279 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700280 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700281 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700282 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700283
Dianne Hackborn497175b2014-07-01 12:56:08 -0700284 final Object mRulesLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700285
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700286 volatile boolean mSystemReady;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700287 volatile boolean mScreenOn;
288 volatile boolean mRestrictBackground;
289 volatile boolean mRestrictPower;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700290 volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700291
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700292 private final boolean mSuppressDefaultPolicy;
293
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700294 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800295 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700296 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800297 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700298
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700299 /** Defined UID policies. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700300 final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 /** Currently derived rules for each UID. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800302 final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700303
Jeff Sharkeydc988062015-09-14 10:09:47 -0700304 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
305 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Leme011b98f2016-02-10 17:28:31 -0800306 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700307
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700308 /** Set of states for the child firewall chains. True if the chain is active. */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700309 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
310
Jeff Sharkey32566012014-12-02 18:30:14 -0800311 /**
312 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700313 * in power save mode, except device idle (doze) still applies.
314 * TODO: An int array might be sufficient
315 */
316 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
317
318 /**
319 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800320 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700321 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 */
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700323 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700324
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700325 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
326
Felipe Lemeb85a6372016-01-14 16:16:16 -0800327 /**
328 * UIDs that have been white-listed to avoid restricted background.
329 */
330 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
331
Felipe Lemea9505cc2016-02-26 10:28:41 -0800332 /**
333 * UIDs that have been initially white-listed by system to avoid restricted background.
334 */
335 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
336 new SparseBooleanArray();
337
338 /**
339 * UIDs that have been initially white-listed by system to avoid restricted background,
340 * but later revoked by user.
341 */
342 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
343 new SparseBooleanArray();
344
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700345 /** Set of ifaces that are metered. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800346 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700347 /** Set of over-limit templates that have been notified. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800348 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700349
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700350 /** Set of currently active {@link Notification} tags. */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700351 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700352
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700353 /** Foreground at UID granularity. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800354 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700355
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600356 /** Higher priority listener before general event dispatch */
357 private INetworkPolicyListener mConnectivityListener;
358
Jeff Sharkey32566012014-12-02 18:30:14 -0800359 private final RemoteCallbackList<INetworkPolicyListener>
360 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700361
Dianne Hackborn497175b2014-07-01 12:56:08 -0700362 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700363
364 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700365
Svet Ganov16a16892015-04-16 10:32:04 -0700366 private final AppOpsManager mAppOps;
367
Felipe Lemeb85a6372016-01-14 16:16:16 -0800368 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800369 private final IPackageManager mIPm;
370
Felipe Lemeb85a6372016-01-14 16:16:16 -0800371
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700372 // TODO: keep whitelist of system-critical services that should never have
373 // rules enforced, such as system, phone, and radio UIDs.
374
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700375 // TODO: migrate notifications to SystemUI
376
Jeff Sharkey75279902011-05-24 18:39:45 -0700377 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700378 IPowerManager powerManager, INetworkStatsService networkStats,
379 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700380 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700381 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700382 }
383
384 private static File getSystemDir() {
385 return new File(Environment.getDataDirectory(), "system");
386 }
387
388 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700389 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700390 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
391 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700392 mContext = checkNotNull(context, "missing context");
393 mActivityManager = checkNotNull(activityManager, "missing activityManager");
394 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700395 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700396 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700397 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700398 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700400 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800401 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
Amith Yamasani450a16b2013-09-18 16:28:50 -0700403 HandlerThread thread = new HandlerThread(TAG);
404 thread.start();
405 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700406
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700407 mSuppressDefaultPolicy = suppressDefaultPolicy;
408
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700409 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700410
411 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800412
413 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700414
415 // Expose private service for system components to use.
416 LocalServices.addService(NetworkPolicyManagerInternal.class,
417 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700418 }
419
420 public void bindConnectivityManager(IConnectivityManager connManager) {
421 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700422 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700423
Jeff Sharkey497e4432011-06-14 17:27:29 -0700424 public void bindNotificationManager(INotificationManager notifManager) {
425 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
426 }
427
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700428 void updatePowerSaveWhitelistLocked() {
429 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700430 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
431 mPowerSaveWhitelistExceptIdleAppIds.clear();
432 if (whitelist != null) {
433 for (int uid : whitelist) {
434 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
435 }
436 }
437 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700438 mPowerSaveWhitelistAppIds.clear();
439 if (whitelist != null) {
440 for (int uid : whitelist) {
441 mPowerSaveWhitelistAppIds.put(uid, true);
442 }
443 }
444 } catch (RemoteException e) {
445 }
446 }
447
Felipe Lemea9505cc2016-02-26 10:28:41 -0800448 /**
449 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
450 * revoke the whitelist.
451 *
452 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
453 */
Felipe Lemea110eec2016-04-29 09:58:06 -0700454 boolean addDefaultRestrictBackgroundWhitelistUidsLocked() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800455 final List<UserInfo> users = mUserManager.getUsers();
456 final int numberUsers = users.size();
457
Felipe Lemea110eec2016-04-29 09:58:06 -0700458 boolean changed = false;
459 for (int i = 0; i < numberUsers; i++) {
460 final UserInfo user = users.get(i);
461 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(user.id) || changed;
462 }
463 return changed;
464 }
465
466 private boolean addDefaultRestrictBackgroundWhitelistUidsLocked(int userId) {
467 final SystemConfig sysConfig = SystemConfig.getInstance();
468 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800469 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
470 boolean changed = false;
471 for (int i = 0; i < allowDataUsage.size(); i++) {
472 final String pkg = allowDataUsage.valueAt(i);
473 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700474 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
475 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800476 final ApplicationInfo app;
477 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700478 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800479 } catch (PackageManager.NameNotFoundException e) {
480 // Should not happen
481 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
482 continue;
483 }
484 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700485 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800486 continue;
487 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700488 final int uid = UserHandle.getUid(userId, app.uid);
489 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
490 if (LOGD)
491 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
492 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800493 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700494 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
495 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
496 + userId + ") to restrict background whitelist");
497 mRestrictBackgroundWhitelistUids.append(uid, true);
498 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800499 }
500 }
501 return changed;
502 }
503
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700504 void updatePowerSaveTempWhitelistLocked() {
505 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700506 // Clear the states of the current whitelist
507 final int N = mPowerSaveTempWhitelistAppIds.size();
508 for (int i = 0; i < N; i++) {
509 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
510 }
511 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700512 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700513 if (whitelist != null) {
514 for (int uid : whitelist) {
515 mPowerSaveTempWhitelistAppIds.put(uid, true);
516 }
517 }
518 } catch (RemoteException e) {
519 }
520 }
521
Amith Yamasani06f08062015-06-12 13:23:33 -0700522 /**
523 * Remove unnecessary entries in the temp whitelist
524 */
525 void purgePowerSaveTempWhitelistLocked() {
526 final int N = mPowerSaveTempWhitelistAppIds.size();
527 for (int i = N - 1; i >= 0; i--) {
528 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
529 mPowerSaveTempWhitelistAppIds.removeAt(i);
530 }
531 }
532 }
533
Jeff Sharkeya4620792011-05-20 15:29:23 -0700534 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700535 if (!isBandwidthControlEnabled()) {
536 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
537 return;
538 }
539
Amith Yamasani15e472352015-04-24 19:06:07 -0700540 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
541
Felipe Lemeb85a6372016-01-14 16:16:16 -0800542 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
543
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700544 synchronized (mRulesLock) {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700545 updatePowerSaveWhitelistLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700546 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
547 mPowerManagerInternal.registerLowPowerModeObserver(
548 new PowerManagerInternal.LowPowerModeListener() {
549 @Override
550 public void onLowPowerModeChanged(boolean enabled) {
Felipe Leme011b98f2016-02-10 17:28:31 -0800551 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700552 synchronized (mRulesLock) {
553 if (mRestrictPower != enabled) {
554 mRestrictPower = enabled;
Felipe Leme011b98f2016-02-10 17:28:31 -0800555 updateRulesForRestrictPowerLocked();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700556 updateRulesForGlobalChangeLocked(true);
557 }
558 }
559 }
560 });
561 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
Felipe Lemed31a97f2016-05-06 14:53:50 -0700562
Dianne Hackborn8ad2af72015-03-17 17:00:24 -0700563 mSystemReady = true;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700564
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700565 // read policy from disk
566 readPolicyLocked();
Jeff Sharkey46645002011-07-27 21:11:21 -0700567
Felipe Lemea110eec2016-04-29 09:58:06 -0700568 if (addDefaultRestrictBackgroundWhitelistUidsLocked()) {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800569 writePolicyLocked();
570 }
571
Jeff Sharkeydc988062015-09-14 10:09:47 -0700572 updateRulesForGlobalChangeLocked(false);
573 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700574 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700575
Jeff Sharkeya4620792011-05-20 15:29:23 -0700576 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700577
Jeff Sharkeya4620792011-05-20 15:29:23 -0700578 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700579 mActivityManager.registerUidObserver(mUidObserver,
580 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700581 mNetworkManager.registerObserver(mAlertObserver);
582 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700583 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700584 }
585
Jeff Sharkeya4620792011-05-20 15:29:23 -0700586 // TODO: traverse existing processes to know foreground state, or have
587 // activitymanager dispatch current state when new observer attached.
588
589 final IntentFilter screenFilter = new IntentFilter();
590 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
591 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700592 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700593
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700594 // listen for changes to power save whitelist
595 final IntentFilter whitelistFilter = new IntentFilter(
596 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
597 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
598
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700599 DeviceIdleController.LocalService deviceIdleService
600 = LocalServices.getService(DeviceIdleController.LocalService.class);
601 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
602
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700603 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900604 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700605 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
606
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700607 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700608 final IntentFilter packageFilter = new IntentFilter();
609 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700610 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700611 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700612
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700613 // listen for UID changes to update policy
614 mContext.registerReceiver(
615 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
616
617 // listen for user changes to update policy
618 final IntentFilter userFilter = new IntentFilter();
619 userFilter.addAction(ACTION_USER_ADDED);
620 userFilter.addAction(ACTION_USER_REMOVED);
621 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
622
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700623 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700624 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
625 mContext.registerReceiver(
626 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
627
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700628 // listen for restrict background changes from notifications
629 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
630 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
631
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800632 // listen for snooze warning from notifications
633 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
634 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
635 MANAGE_NETWORK_POLICY, mHandler);
636
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700637 // listen for configured wifi networks to be removed
638 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700639 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700640
641 // listen for wifi state changes to catch metered hint
642 final IntentFilter wifiStateFilter = new IntentFilter(
643 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700644 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700645
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700646 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700647
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700648 }
649
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700650 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700651 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700652 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700653 updateUidStateLocked(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700654 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700655 }
656
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700657 @Override public void onUidGone(int uid) throws RemoteException {
Dianne Hackborn497175b2014-07-01 12:56:08 -0700658 synchronized (mRulesLock) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700659 removeUidStateLocked(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700660 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700661 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700662
663 @Override public void onUidActive(int uid) throws RemoteException {
664 }
665
666 @Override public void onUidIdle(int uid) throws RemoteException {
667 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700668 };
669
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700670 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700671 @Override
672 public void onReceive(Context context, Intent intent) {
673 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
674 synchronized (mRulesLock) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700675 updatePowerSaveWhitelistLocked();
676 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700677 }
678 }
679 };
680
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700681 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
682 @Override
683 public void run() {
684 synchronized (mRulesLock) {
685 updatePowerSaveTempWhitelistLocked();
686 updateRulesForTempWhitelistChangeLocked();
687 purgePowerSaveTempWhitelistLocked();
688 }
689 }
690 };
691
692 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700693 @Override
694 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800695 // screen-related broadcasts are protected by system, no need
696 // for permissions check.
697 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700698 }
699 };
700
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700701 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700702 @Override
703 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700704 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700705
706 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700707 final int uid = intent.getIntExtra(EXTRA_UID, -1);
708 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700709
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700710 if (ACTION_PACKAGE_ADDED.equals(action)) {
711 // update rules for UID, since it might be subject to
712 // global background data policy
713 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
714 synchronized (mRulesLock) {
Felipe Lemef28983d2016-03-25 12:18:23 -0700715 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700716 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700717 }
718 }
719 };
720
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700721 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700722 @Override
723 public void onReceive(Context context, Intent intent) {
724 // on background handler thread, and UID_REMOVED is protected
725
726 final int uid = intent.getIntExtra(EXTRA_UID, -1);
727 if (uid == -1) return;
728
729 // remove any policy and update rules to clean up
730 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
731 synchronized (mRulesLock) {
732 mUidPolicy.delete(uid);
Felipe Leme781ba142016-05-09 16:24:48 -0700733 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700734 writePolicyLocked();
735 }
736 }
737 };
738
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700739 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700740 @Override
741 public void onReceive(Context context, Intent intent) {
742 // on background handler thread, and USER_ADDED and USER_REMOVED
743 // broadcasts are protected
744
745 final String action = intent.getAction();
746 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
747 if (userId == -1) return;
748
Amith Yamasani15e472352015-04-24 19:06:07 -0700749 switch (action) {
750 case ACTION_USER_REMOVED:
751 case ACTION_USER_ADDED:
752 synchronized (mRulesLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800753 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700754 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemed17fda42016-04-29 11:12:45 -0700755 removeUserStateLocked(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700756 if (action == ACTION_USER_ADDED) {
757 // Add apps that are whitelisted by default.
758 addDefaultRestrictBackgroundWhitelistUidsLocked(userId);
759 }
760 // Update global restrict for that user
Amith Yamasani15e472352015-04-24 19:06:07 -0700761 updateRulesForGlobalChangeLocked(true);
762 }
763 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700764 }
765 }
766 };
767
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700768 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700769 * Receiver that watches for {@link INetworkStatsService} updates, which we
770 * use to check against {@link NetworkPolicy#warningBytes}.
771 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700772 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700773 @Override
774 public void onReceive(Context context, Intent intent) {
775 // on background handler thread, and verified
776 // READ_NETWORK_USAGE_HISTORY permission above.
777
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800778 maybeRefreshTrustedTime();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700779 synchronized (mRulesLock) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700780 updateNetworkEnabledLocked();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700781 updateNotificationsLocked();
782 }
783 }
784 };
785
786 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700787 * Receiver that watches for {@link Notification} control of
788 * {@link #mRestrictBackground}.
789 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700790 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700791 @Override
792 public void onReceive(Context context, Intent intent) {
793 // on background handler thread, and verified MANAGE_NETWORK_POLICY
794 // permission above.
795
796 setRestrictBackground(false);
797 }
798 };
799
800 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800801 * Receiver that watches for {@link Notification} control of
802 * {@link NetworkPolicy#lastWarningSnooze}.
803 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700804 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800805 @Override
806 public void onReceive(Context context, Intent intent) {
807 // on background handler thread, and verified MANAGE_NETWORK_POLICY
808 // permission above.
809
810 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
811 performSnooze(template, TYPE_WARNING);
812 }
813 };
814
815 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700816 * Receiver that watches for {@link WifiConfiguration} to be changed.
817 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700818 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700819 @Override
820 public void onReceive(Context context, Intent intent) {
821 // on background handler thread, and verified CONNECTIVITY_INTERNAL
822 // permission above.
823
824 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
825 if (reason == CHANGE_REASON_REMOVED) {
826 final WifiConfiguration config = intent.getParcelableExtra(
827 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700828 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800829 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700830 synchronized (mRulesLock) {
831 if (mNetworkPolicy.containsKey(template)) {
832 mNetworkPolicy.remove(template);
833 writePolicyLocked();
834 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700835 }
836 }
837 }
838 }
839 };
840
841 /**
842 * Receiver that watches {@link WifiInfo} state changes to infer metered
843 * state. Ignores hints when policy is user-defined.
844 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700845 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700846 @Override
847 public void onReceive(Context context, Intent intent) {
848 // on background handler thread, and verified CONNECTIVITY_INTERNAL
849 // permission above.
850
851 // ignore when not connected
852 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
853 if (!netInfo.isConnected()) return;
854
855 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
856 final boolean meteredHint = info.getMeteredHint();
857
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800858 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700859 synchronized (mRulesLock) {
860 NetworkPolicy policy = mNetworkPolicy.get(template);
861 if (policy == null && meteredHint) {
862 // policy doesn't exist, and AP is hinting that it's
863 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800864 policy = newWifiPolicy(template, meteredHint);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700865 addNetworkPolicyLocked(policy);
866
867 } else if (policy != null && policy.inferred) {
868 // policy exists, and was inferred: update its current
869 // metered state.
870 policy.metered = meteredHint;
871
872 // since this is inferred for each wifi session, just update
873 // rules without persisting.
874 updateNetworkRulesLocked();
875 }
876 }
877 }
878 };
879
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800880 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
881 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
882 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
883 metered, true);
884 }
885
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700886 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700887 * Observer that watches for {@link INetworkManagementService} alerts.
888 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700889 final private INetworkManagementEventObserver mAlertObserver
890 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700891 @Override
892 public void limitReached(String limitName, String iface) {
893 // only someone like NMS should be calling us
894 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
895
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800896 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
897 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700898 }
899 }
900 };
901
902 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700903 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
904 * to show visible notifications as needed.
905 */
Dianne Hackborn497175b2014-07-01 12:56:08 -0700906 void updateNotificationsLocked() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700907 if (LOGV) Slog.v(TAG, "updateNotificationsLocked()");
908
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700909 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700910 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700911 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700912
913 // TODO: when switching to kernel notifications, compute next future
914 // cycle boundary to recompute notifications.
915
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700916 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800917 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700918 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
919 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700920 // ignore policies that aren't relevant to user
921 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700922 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700923
Jeff Sharkey497e4432011-06-14 17:27:29 -0700924 final long start = computeLastCycleBoundary(currentTime, policy);
925 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700926 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700928 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800929 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700930 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
931 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700932 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
933 notifyOverLimitLocked(policy.template);
934 }
935
Jeff Sharkey497e4432011-06-14 17:27:29 -0700936 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700937 notifyUnderLimitLocked(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800939 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700940 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700941 }
942 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700943 }
944
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700946 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
947 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700948 if (!mActiveNotifs.contains(tag)) {
949 cancelNotification(tag);
950 }
951 }
952 }
953
954 /**
955 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700956 * current device state, such as when
957 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
958 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700959 */
960 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800961 if (template.isMatchRuleMobile()) {
962 final TelephonyManager tele = TelephonyManager.from(mContext);
963 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700964
Jeff Sharkey32566012014-12-02 18:30:14 -0800965 // Mobile template is relevant when any active subscriber matches
966 final int[] subIds = sub.getActiveSubscriptionIdList();
967 for (int subId : subIds) {
968 final String subscriberId = tele.getSubscriberId(subId);
969 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700970 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800971 if (template.matches(probeIdent)) {
972 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700973 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800974 }
975 return false;
976 } else {
977 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700978 }
Jeff Sharkey497e4432011-06-14 17:27:29 -0700979 }
980
981 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700982 * Notify that given {@link NetworkTemplate} is over
983 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
984 */
985 private void notifyOverLimitLocked(NetworkTemplate template) {
986 if (!mOverLimitNotified.contains(template)) {
987 mContext.startActivity(buildNetworkOverLimitIntent(template));
988 mOverLimitNotified.add(template);
989 }
990 }
991
992 private void notifyUnderLimitLocked(NetworkTemplate template) {
993 mOverLimitNotified.remove(template);
994 }
995
996 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700997 * Build unique tag that identifies an active {@link NetworkPolicy}
998 * notification of a specific type, like {@link #TYPE_LIMIT}.
999 */
1000 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001001 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001002 }
1003
1004 /**
1005 * Show notification for combined {@link NetworkPolicy} and specific type,
1006 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1007 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001008 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009 final String tag = buildNotificationTag(policy, type);
1010 final Notification.Builder builder = new Notification.Builder(mContext);
1011 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001012 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001013 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001014 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015
1016 final Resources res = mContext.getResources();
1017 switch (type) {
1018 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001020 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001021
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001022 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 builder.setTicker(title);
1024 builder.setContentTitle(title);
1025 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001026
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001027 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1028 builder.setDeleteIntent(PendingIntent.getBroadcast(
1029 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1030
1031 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001032 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001033 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1034
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035 break;
1036 }
1037 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1039
1040 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001041 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001042 switch (policy.template.getMatchRule()) {
1043 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001046 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001047 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001049 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001050 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001051 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001052 case MATCH_WIFI:
1053 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001054 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 break;
1056 default:
1057 title = null;
1058 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059 }
1060
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001062 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063 builder.setTicker(title);
1064 builder.setContentTitle(title);
1065 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001066
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1068 builder.setContentIntent(PendingIntent.getActivity(
1069 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1070 break;
1071 }
1072 case TYPE_LIMIT_SNOOZED: {
1073 final long overBytes = totalBytes - policy.limitBytes;
1074 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1075 Formatter.formatFileSize(mContext, overBytes));
1076
1077 final CharSequence title;
1078 switch (policy.template.getMatchRule()) {
1079 case MATCH_MOBILE_3G_LOWER:
1080 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1081 break;
1082 case MATCH_MOBILE_4G:
1083 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1084 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001085 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001086 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1087 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001088 case MATCH_WIFI:
1089 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1090 break;
1091 default:
1092 title = null;
1093 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001094 }
1095
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001096 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001097 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 builder.setTicker(title);
1099 builder.setContentTitle(title);
1100 builder.setContentText(body);
1101
1102 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001103 builder.setContentIntent(PendingIntent.getActivity(
1104 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001105 break;
1106 }
1107 }
1108
1109 // TODO: move to NotificationManager once we can mock it
1110 try {
1111 final String packageName = mContext.getPackageName();
1112 final int[] idReceived = new int[1];
1113 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001114 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001115 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001116 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001117 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001118 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001119 }
1120 }
1121
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001122 private void cancelNotification(String tag) {
1123 // TODO: move to NotificationManager once we can mock it
1124 try {
1125 final String packageName = mContext.getPackageName();
1126 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001127 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001128 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001129 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130 }
1131 }
1132
1133 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001134 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001135 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001136 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001137 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001138 @Override
1139 public void onReceive(Context context, Intent intent) {
1140 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1141 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001142
1143 maybeRefreshTrustedTime();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001144 synchronized (mRulesLock) {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001145 ensureActiveMobilePolicyLocked();
Jeff Sharkey32566012014-12-02 18:30:14 -08001146 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 updateNetworkEnabledLocked();
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001148 updateNetworkRulesLocked();
1149 updateNotificationsLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001150 }
1151 }
1152 };
1153
1154 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 * Proactively control network data connections when they exceed
1156 * {@link NetworkPolicy#limitBytes}.
1157 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001158 void updateNetworkEnabledLocked() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159 if (LOGV) Slog.v(TAG, "updateNetworkEnabledLocked()");
1160
1161 // TODO: reset any policy-disabled networks when any policy is removed
1162 // completely, which is currently rare case.
1163
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001164 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001165 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1166 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001167 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001168 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 setNetworkTemplateEnabled(policy.template, true);
1170 continue;
1171 }
1172
1173 final long start = computeLastCycleBoundary(currentTime, policy);
1174 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001175 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001176
1177 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001178 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1179 && policy.lastLimitSnooze < start;
1180 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001181
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001182 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 }
1184 }
1185
1186 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001187 * Proactively disable networks that match the given
1188 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 */
1190 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001191 // TODO: reach into ConnectivityManager to proactively disable bringing
1192 // up this network, since we know that traffic will be blocked.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001193 }
1194
1195 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001196 * Examine all connected {@link NetworkState}, looking for
1197 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1198 * remaining quota based on usage cycle and historical stats.
1199 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07001200 void updateNetworkRulesLocked() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001201 if (LOGV) Slog.v(TAG, "updateNetworkRulesLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001202
1203 final NetworkState[] states;
1204 try {
1205 states = mConnManager.getAllNetworkState();
1206 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001207 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001208 return;
1209 }
1210
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001211 // First, generate identities of all connected networks so we can
1212 // quickly compare them against all defined policies below.
1213 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001214 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001215 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001216 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001217 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001218
1219 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001220 if (baseIface != null) {
1221 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001222 }
1223
1224 // Stacked interfaces are considered to have same identity as
1225 // their parent network.
1226 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1227 for (LinkProperties stackedLink : stackedLinks) {
1228 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001229 if (stackedIface != null) {
1230 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001231 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001232 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001233 }
1234 }
1235
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001236 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001237 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001238 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001239 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001240 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001242 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001243 for (int j = connIdents.size() - 1; j >= 0; j--) {
1244 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1245 if (policy.template.matches(ident.second)) {
1246 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001247 }
1248 }
1249
1250 if (ifaceList.size() > 0) {
1251 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001252 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001253 }
1254 }
1255
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001256 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001257 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001258
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001259 // apply each policy that we found ifaces for; compute remaining data
1260 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001261 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001262 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1263 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1264 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001265
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001266 final long start;
1267 final long totalBytes;
1268 if (policy.hasCycle()) {
1269 start = computeLastCycleBoundary(currentTime, policy);
1270 totalBytes = getTotalBytes(policy.template, start, currentTime);
1271 } else {
1272 start = Long.MAX_VALUE;
1273 totalBytes = 0;
1274 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001277 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278 }
1279
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001280 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001281 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001282 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001283 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001284 if (!hasLimit) {
1285 // metered network, but no policy limit; we still need to
1286 // restrict apps, so push really high quota.
1287 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001288 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001289 // snoozing past quota, but we still need to restrict apps,
1290 // so push really high quota.
1291 quotaBytes = Long.MAX_VALUE;
1292 } else {
1293 // remaining "quota" bytes are based on total usage in
1294 // current cycle. kernel doesn't like 0-byte rules, so we
1295 // set 1-byte quota and disable the radio later.
1296 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1297 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001298
1299 if (ifaces.length > 1) {
1300 // TODO: switch to shared quota once NMS supports
1301 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001302 }
1303
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001304 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001305 // long quotaBytes split up into two ints to fit in message
1306 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1307 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1308 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001309 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001310 }
1311 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001312
1313 // keep track of lowest warning or limit of active policies
1314 if (hasWarning && policy.warningBytes < lowestRule) {
1315 lowestRule = policy.warningBytes;
1316 }
1317 if (hasLimit && policy.limitBytes < lowestRule) {
1318 lowestRule = policy.limitBytes;
1319 }
1320 }
1321
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001322 for (int i = connIfaces.size()-1; i >= 0; i--) {
1323 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001324 // long quotaBytes split up into two ints to fit in message
1325 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1326 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1327 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001328 newMeteredIfaces.add(iface);
1329 }
1330
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001331 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001332
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001333 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001334 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1335 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001336 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001337 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1338 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001339 }
1340 }
1341 mMeteredIfaces = newMeteredIfaces;
1342
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001343 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001344 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001345 }
1346
1347 /**
1348 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1349 * have at least a default mobile policy defined.
1350 */
1351 private void ensureActiveMobilePolicyLocked() {
1352 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyLocked()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001353 if (mSuppressDefaultPolicy) return;
1354
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001355 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001357
Jeff Sharkey32566012014-12-02 18:30:14 -08001358 final int[] subIds = sub.getActiveSubscriptionIdList();
1359 for (int subId : subIds) {
1360 final String subscriberId = tele.getSubscriberId(subId);
1361 ensureActiveMobilePolicyLocked(subscriberId);
1362 }
1363 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001364
Jeff Sharkey32566012014-12-02 18:30:14 -08001365 private void ensureActiveMobilePolicyLocked(String subscriberId) {
1366 // Poke around to see if we already have a policy
1367 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001368 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001369 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1370 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1371 if (template.matches(probeIdent)) {
1372 if (LOGD) {
1373 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1374 + NetworkIdentity.scrubSubscriberId(subscriberId));
1375 }
1376 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001377 }
1378 }
1379
Jeff Sharkey32566012014-12-02 18:30:14 -08001380 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1381 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001382
Jeff Sharkey32566012014-12-02 18:30:14 -08001383 // Build default mobile policy, and assume usage cycle starts today
1384 final long warningBytes = mContext.getResources().getInteger(
1385 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001386
Jeff Sharkey32566012014-12-02 18:30:14 -08001387 final Time time = new Time();
1388 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001389
Jeff Sharkey32566012014-12-02 18:30:14 -08001390 final int cycleDay = time.monthDay;
1391 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001392
Jeff Sharkey32566012014-12-02 18:30:14 -08001393 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1394 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1395 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1396 addNetworkPolicyLocked(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397 }
1398
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399 private void readPolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001400 if (LOGV) Slog.v(TAG, "readPolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001401
1402 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001403 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001404 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001405
1406 FileInputStream fis = null;
1407 try {
1408 fis = mPolicyFile.openRead();
1409 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001410 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001411
1412 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001413 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001414 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001415 while ((type = in.next()) != END_DOCUMENT) {
1416 final String tag = in.getName();
1417 if (type == START_TAG) {
1418 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001419 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001420 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001421 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1422 mRestrictBackground = readBooleanAttribute(
1423 in, ATTR_RESTRICT_BACKGROUND);
1424 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001425 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001426 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001427 if (mRestrictBackground != oldValue) {
1428 // Some early services may have read the default value,
1429 // so notify them that it's changed
1430 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1431 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1432 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001433
1434 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1435 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1436 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001437 final String networkId;
1438 if (version >= VERSION_ADDED_NETWORK_ID) {
1439 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1440 } else {
1441 networkId = null;
1442 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001443 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001444 final String cycleTimezone;
1445 if (version >= VERSION_ADDED_TIMEZONE) {
1446 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1447 } else {
1448 cycleTimezone = Time.TIMEZONE_UTC;
1449 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1451 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001452 final long lastLimitSnooze;
1453 if (version >= VERSION_SPLIT_SNOOZE) {
1454 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1455 } else if (version >= VERSION_ADDED_SNOOZE) {
1456 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001457 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001458 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001459 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001460 final boolean metered;
1461 if (version >= VERSION_ADDED_METERED) {
1462 metered = readBooleanAttribute(in, ATTR_METERED);
1463 } else {
1464 switch (networkTemplate) {
1465 case MATCH_MOBILE_3G_LOWER:
1466 case MATCH_MOBILE_4G:
1467 case MATCH_MOBILE_ALL:
1468 metered = true;
1469 break;
1470 default:
1471 metered = false;
1472 }
1473 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001474 final long lastWarningSnooze;
1475 if (version >= VERSION_SPLIT_SNOOZE) {
1476 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1477 } else {
1478 lastWarningSnooze = SNOOZE_NEVER;
1479 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001480 final boolean inferred;
1481 if (version >= VERSION_ADDED_INFERRED) {
1482 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1483 } else {
1484 inferred = false;
1485 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486
Jeff Sharkey32566012014-12-02 18:30:14 -08001487 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1488 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001489 if (template.isPersistable()) {
1490 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1491 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1492 lastLimitSnooze, metered, inferred));
1493 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001494
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001495 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496 final int uid = readIntAttribute(in, ATTR_UID);
1497 final int policy = readIntAttribute(in, ATTR_POLICY);
1498
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001499 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001500 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001501 } else {
1502 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1503 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001504 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001505 final int appId = readIntAttribute(in, ATTR_APP_ID);
1506 final int policy = readIntAttribute(in, ATTR_POLICY);
1507
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001508 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001509 // app policy is deprecated so this is only used in pre system user split.
1510 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001511 if (UserHandle.isApp(uid)) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001512 setUidPolicyUncheckedLocked(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001513 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001514 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001515 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001516 } else if (TAG_WHITELIST.equals(tag)) {
1517 insideWhitelist = true;
1518 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1519 final int uid = readIntAttribute(in, ATTR_UID);
1520 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001521 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1522 final int uid = readIntAttribute(in, ATTR_UID);
1523 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001524 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001525 } else if (type == END_TAG) {
1526 if (TAG_WHITELIST.equals(tag)) {
1527 insideWhitelist = false;
1528 }
1529
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001530 }
1531 }
1532
1533 } catch (FileNotFoundException e) {
1534 // missing policy is okay, probably first boot
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001535 upgradeLegacyBackgroundData();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001536 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001537 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001538 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001539 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001540 } finally {
1541 IoUtils.closeQuietly(fis);
1542 }
1543 }
1544
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001545 /**
1546 * Upgrade legacy background data flags, notifying listeners of one last
1547 * change to always-true.
1548 */
1549 private void upgradeLegacyBackgroundData() {
1550 mRestrictBackground = Settings.Secure.getInt(
1551 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1552
1553 // kick off one last broadcast if restricted
1554 if (mRestrictBackground) {
1555 final Intent broadcast = new Intent(
1556 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001557 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001558 }
1559 }
1560
Dianne Hackborn497175b2014-07-01 12:56:08 -07001561 void writePolicyLocked() {
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001562 if (LOGV) Slog.v(TAG, "writePolicyLocked()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563
1564 FileOutputStream fos = null;
1565 try {
1566 fos = mPolicyFile.startWrite();
1567
1568 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001569 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001570 out.startDocument(null, true);
1571
1572 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001573 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001574 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001575
1576 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001577 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1578 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001579 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001580 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001581
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001583 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1584 final String subscriberId = template.getSubscriberId();
1585 if (subscriberId != null) {
1586 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001588 final String networkId = template.getNetworkId();
1589 if (networkId != null) {
1590 out.attribute(null, ATTR_NETWORK_ID, networkId);
1591 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001592 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001593 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001594 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1595 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001596 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1597 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001598 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001599 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001600 out.endTag(null, TAG_NETWORK_POLICY);
1601 }
1602
1603 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001604 for (int i = 0; i < mUidPolicy.size(); i++) {
1605 final int uid = mUidPolicy.keyAt(i);
1606 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607
Jeff Sharkey497e4432011-06-14 17:27:29 -07001608 // skip writing empty policies
1609 if (policy == POLICY_NONE) continue;
1610
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001611 out.startTag(null, TAG_UID_POLICY);
1612 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001614 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001615 }
1616
1617 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001618
1619 // write all whitelists
1620 out.startTag(null, TAG_WHITELIST);
1621
1622 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001623 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001624 for (int i = 0; i < size; i++) {
1625 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1626 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1627 writeIntAttribute(out, ATTR_UID, uid);
1628 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1629 }
1630
Felipe Lemea9505cc2016-02-26 10:28:41 -08001631 // revoked restrict background whitelist
1632 size = mRestrictBackgroundWhitelistRevokedUids.size();
1633 for (int i = 0; i < size; i++) {
1634 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1635 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1636 writeIntAttribute(out, ATTR_UID, uid);
1637 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1638 }
1639
Felipe Lemeb85a6372016-01-14 16:16:16 -08001640 out.endTag(null, TAG_WHITELIST);
1641
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642 out.endDocument();
1643
1644 mPolicyFile.finishWrite(fos);
1645 } catch (IOException e) {
1646 if (fos != null) {
1647 mPolicyFile.failWrite(fos);
1648 }
1649 }
1650 }
1651
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001652 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001655
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001656 if (!UserHandle.isApp(uid)) {
1657 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001658 }
1659
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001660 synchronized (mRulesLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001661 final long token = Binder.clearCallingIdentity();
1662 try {
1663 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1664 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001665 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001666 }
1667 } finally {
1668 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001669 }
1670 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001671 }
1672
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001673 @Override
1674 public void addUidPolicy(int uid, int policy) {
1675 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001676
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001677 if (!UserHandle.isApp(uid)) {
1678 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1679 }
1680
1681 synchronized (mRulesLock) {
1682 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1683 policy |= oldPolicy;
1684 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001685 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001686 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001687 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001688 }
1689
1690 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001691 public void removeUidPolicy(int uid, int policy) {
1692 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1693
1694 if (!UserHandle.isApp(uid)) {
1695 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1696 }
1697
1698 synchronized (mRulesLock) {
1699 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1700 policy = oldPolicy & ~policy;
1701 if (oldPolicy != policy) {
Felipe Leme923845f2016-03-02 13:42:48 -08001702 setUidPolicyUncheckedLocked(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001703 }
1704 }
1705 }
1706
Felipe Leme923845f2016-03-02 13:42:48 -08001707 private void setUidPolicyUncheckedLocked(int uid, int oldPolicy, int policy, boolean persist) {
1708 setUidPolicyUncheckedLocked(uid, policy, persist);
1709
1710 // Checks if app was added or removed to the blacklist.
1711 if ((oldPolicy == POLICY_NONE && policy == POLICY_REJECT_METERED_BACKGROUND)
1712 || (oldPolicy == POLICY_REJECT_METERED_BACKGROUND && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001713 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001714 .sendToTarget();
1715 }
1716 }
1717
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001718 private void setUidPolicyUncheckedLocked(int uid, int policy, boolean persist) {
1719 mUidPolicy.put(uid, policy);
1720
1721 // uid policy changed, recompute rules and persist policy.
Felipe Leme781ba142016-05-09 16:24:48 -07001722 updateRulesForDataUsageRestrictionsLocked(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001723 if (persist) {
1724 writePolicyLocked();
1725 }
1726 }
1727
1728 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001729 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001730 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1731
Jeff Sharkeya4620792011-05-20 15:29:23 -07001732 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001733 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001734 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001735 }
1736
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001737 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001738 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001739 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1740
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001741 int[] uids = new int[0];
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001742 synchronized (mRulesLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001743 for (int i = 0; i < mUidPolicy.size(); i++) {
1744 final int uid = mUidPolicy.keyAt(i);
1745 final int uidPolicy = mUidPolicy.valueAt(i);
1746 if (uidPolicy == policy) {
1747 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001748 }
1749 }
1750 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001751 return uids;
1752 }
1753
1754 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001755 * Removes any persistable state associated with given {@link UserHandle}, persisting
1756 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001757 */
Felipe Lemed17fda42016-04-29 11:12:45 -07001758 boolean removeUserStateLocked(int userId, boolean writePolicy) {
1759
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001760 if (LOGV) Slog.v(TAG, "removeUserStateLocked()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001761 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001762
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001763 // Remove entries from restricted background UID whitelist
1764 int[] wlUids = new int[0];
1765 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1766 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1767 if (UserHandle.getUserId(uid) == userId) {
1768 wlUids = appendInt(wlUids, uid);
1769 }
1770 }
1771
1772 if (wlUids.length > 0) {
1773 for (int uid : wlUids) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001774 removeRestrictBackgroundWhitelistedUidLocked(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001775 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001776 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001777 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001778
1779 // Remove entries from revoked default restricted background UID whitelist
1780 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1781 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1782 if (UserHandle.getUserId(uid) == userId) {
1783 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001784 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001785 }
1786 }
1787
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001788 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001789 int[] uids = new int[0];
1790 for (int i = 0; i < mUidPolicy.size(); i++) {
1791 final int uid = mUidPolicy.keyAt(i);
1792 if (UserHandle.getUserId(uid) == userId) {
1793 uids = appendInt(uids, uid);
1794 }
1795 }
1796
1797 if (uids.length > 0) {
1798 for (int uid : uids) {
1799 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001800 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001801 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001802 }
1803
Felipe Leme76010a32016-03-17 13:03:11 -07001804 updateRulesForGlobalChangeLocked(true);
1805
Felipe Lemed17fda42016-04-29 11:12:45 -07001806 if (writePolicy && changed) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001807 writePolicyLocked();
1808 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001809 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001810 }
1811
1812 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001813 public void setConnectivityListener(INetworkPolicyListener listener) {
1814 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1815 if (mConnectivityListener != null) {
1816 throw new IllegalStateException("Connectivity listener already registered");
1817 }
1818 mConnectivityListener = listener;
1819 }
1820
1821 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001822 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001823 // TODO: create permission for observing network policy
1824 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001825 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001826 }
1827
1828 @Override
1829 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001830 // TODO: create permission for observing network policy
1831 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001832 mListeners.unregister(listener);
1833 }
1834
Jeff Sharkey1b861272011-05-22 00:34:52 -07001835 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001836 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001837 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1838
Felipe Leme6a05eee2016-02-19 14:43:51 -08001839 final long token = Binder.clearCallingIdentity();
1840 try {
1841 maybeRefreshTrustedTime();
1842 synchronized (mRulesLock) {
1843 normalizePoliciesLocked(policies);
1844 updateNetworkEnabledLocked();
1845 updateNetworkRulesLocked();
1846 updateNotificationsLocked();
1847 writePolicyLocked();
1848 }
1849 } finally {
1850 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001851 }
1852 }
1853
Dianne Hackborn497175b2014-07-01 12:56:08 -07001854 void addNetworkPolicyLocked(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001855 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001856 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1857 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001858 }
1859
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001860 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001861 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001862 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001863 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001864 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1865 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1866 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001867 } catch (SecurityException e) {
1868 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001869
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001870 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1871 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1872 return new NetworkPolicy[0];
1873 }
Svet Ganov16a16892015-04-16 10:32:04 -07001874 }
1875
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001876 synchronized (mRulesLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001877 final int size = mNetworkPolicy.size();
1878 final NetworkPolicy[] policies = new NetworkPolicy[size];
1879 for (int i = 0; i < size; i++) {
1880 policies[i] = mNetworkPolicy.valueAt(i);
1881 }
1882 return policies;
1883 }
1884 }
1885
1886 private void normalizePoliciesLocked() {
Svet Ganov16a16892015-04-16 10:32:04 -07001887 normalizePoliciesLocked(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001888 }
1889
1890 private void normalizePoliciesLocked(NetworkPolicy[] policies) {
1891 final TelephonyManager tele = TelephonyManager.from(mContext);
1892 final String[] merged = tele.getMergedSubscriberIds();
1893
1894 mNetworkPolicy.clear();
1895 for (NetworkPolicy policy : policies) {
1896 // When two normalized templates conflict, prefer the most
1897 // restrictive policy
1898 policy.template = NetworkTemplate.normalize(policy.template, merged);
1899 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1900 if (existing == null || existing.compareTo(policy) > 0) {
1901 if (existing != null) {
1902 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1903 }
1904 mNetworkPolicy.put(policy.template, policy);
1905 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001906 }
1907 }
1908
1909 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001910 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001911 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001912
1913 final long token = Binder.clearCallingIdentity();
1914 try {
1915 performSnooze(template, TYPE_LIMIT);
1916 } finally {
1917 Binder.restoreCallingIdentity(token);
1918 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001919 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001920
Dianne Hackborn497175b2014-07-01 12:56:08 -07001921 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001922 maybeRefreshTrustedTime();
1923 final long currentTime = currentTimeMillis();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001924 synchronized (mRulesLock) {
1925 // find and snooze local policy that matches
1926 final NetworkPolicy policy = mNetworkPolicy.get(template);
1927 if (policy == null) {
1928 throw new IllegalArgumentException("unable to find policy for " + template);
1929 }
1930
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001931 switch (type) {
1932 case TYPE_WARNING:
1933 policy.lastWarningSnooze = currentTime;
1934 break;
1935 case TYPE_LIMIT:
1936 policy.lastLimitSnooze = currentTime;
1937 break;
1938 default:
1939 throw new IllegalArgumentException("unexpected type");
1940 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001941
Jeff Sharkey32566012014-12-02 18:30:14 -08001942 normalizePoliciesLocked();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001943 updateNetworkEnabledLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001944 updateNetworkRulesLocked();
1945 updateNotificationsLocked();
1946 writePolicyLocked();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001947 }
1948 }
1949
1950 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001951 public void onTetheringChanged(String iface, boolean tethering) {
1952 // No need to enforce permission because setRestrictBackground() will do it.
1953 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
1954 synchronized (mRulesLock) {
1955 if (mRestrictBackground && tethering) {
1956 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
1957 setRestrictBackground(false);
1958 }
1959 }
1960 }
1961
1962 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07001963 public void setRestrictBackground(boolean restrictBackground) {
1964 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001965 final long token = Binder.clearCallingIdentity();
1966 try {
1967 maybeRefreshTrustedTime();
1968 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07001969 if (restrictBackground == mRestrictBackground) {
1970 // Ideally, UI should never allow this scenario...
1971 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
1972 return;
1973 }
1974 setRestrictBackgroundLocked(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08001975 }
Jeff Sharkey46645002011-07-27 21:11:21 -07001976
Felipe Leme6a05eee2016-02-19 14:43:51 -08001977 } finally {
1978 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07001979 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001980
1981 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
1982 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07001983 }
1984
Felipe Leme70c57c22016-03-29 10:45:13 -07001985 private void setRestrictBackgroundLocked(boolean restrictBackground) {
1986 final boolean oldRestrictBackground = mRestrictBackground;
1987 mRestrictBackground = restrictBackground;
1988 // Must whitelist foreground apps before turning data saver mode on.
1989 // TODO: there is no need to iterate through all apps here, just those in the foreground,
1990 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
1991 updateRulesForRestrictBackgroundLocked();
1992 try {
1993 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
1994 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
1995 mRestrictBackground = oldRestrictBackground;
1996 // TODO: if it knew the foreground apps (see TODO above), it could call
1997 // updateRulesForRestrictBackgroundLocked() again to restore state.
1998 return;
1999 }
2000 } catch (RemoteException e) {
2001 // ignored; service lives in system_server
2002 }
2003 updateNotificationsLocked();
2004 writePolicyLocked();
2005 }
2006
Jeff Sharkey46645002011-07-27 21:11:21 -07002007 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002008 public void addRestrictBackgroundWhitelistedUid(int uid) {
2009 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002010 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002011 final boolean needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002012 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002013 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002014 if (oldStatus) {
2015 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2016 return;
2017 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002018 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002019 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002020 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002021 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2022 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2023 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2024 + " from revoked restrict background whitelist");
2025 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2026 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002027 if (needFirewallRules) {
2028 // Only update firewall rules if necessary...
Felipe Leme781ba142016-05-09 16:24:48 -07002029 updateRulesForDataUsageRestrictionsLocked(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002030 }
2031 // ...but always persists the whitelist request.
Felipe Lemeb85a6372016-01-14 16:16:16 -08002032 writePolicyLocked();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002033 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002034 int changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
2035 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2036 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002037 }
2038
2039 @Override
2040 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2041 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002042 final boolean changed;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002043 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002044 changed = removeRestrictBackgroundWhitelistedUidLocked(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002045 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002046 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2047 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002048 }
2049
Felipe Leme70c57c22016-03-29 10:45:13 -07002050 /**
2051 * Removes a uid from the restricted background whitelist, returning whether its current
2052 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2053 */
2054 private boolean removeRestrictBackgroundWhitelistedUidLocked(int uid, boolean uidDeleted,
2055 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002056 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002057 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002058 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2059 return false;
2060 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002061 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002062 if (oldStatus) {
2063 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2064 mRestrictBackgroundWhitelistUids.delete(uid);
2065 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002066 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2067 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2068 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2069 + " to revoked restrict background whitelist");
2070 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2071 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002072 if (needFirewallRules) {
2073 // Only update firewall rules if necessary...
Felipe Leme781ba142016-05-09 16:24:48 -07002074 updateRulesForDataUsageRestrictionsLocked(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002075 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002076 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002077 // ...but always persists the whitelist request.
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002078 writePolicyLocked();
2079 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002080 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2081 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002082 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002083 }
2084
2085 @Override
2086 public int[] getRestrictBackgroundWhitelistedUids() {
2087 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2088 synchronized (mRulesLock) {
2089 final int size = mRestrictBackgroundWhitelistUids.size();
2090 final int[] whitelist = new int[size];
2091 for (int i = 0; i < size; i++) {
2092 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2093 }
2094 if (LOGV) {
2095 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2096 + mRestrictBackgroundWhitelistUids);
2097 }
2098 return whitelist;
2099 }
2100 }
2101
2102 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002103 public int getRestrictBackgroundByCaller() {
2104 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2105 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002106
Felipe Leme1b103232016-01-22 09:44:57 -08002107 synchronized (mRulesLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002108 // Must clear identity because getUidPolicy() is restricted to system.
2109 final long token = Binder.clearCallingIdentity();
2110 final int policy;
2111 try {
2112 policy = getUidPolicy(uid);
2113 } finally {
2114 Binder.restoreCallingIdentity(token);
2115 }
2116 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2117 // App is blacklisted.
2118 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2119 }
Felipe Leme1b103232016-01-22 09:44:57 -08002120 if (!mRestrictBackground) {
2121 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2122 }
2123 return mRestrictBackgroundWhitelistUids.get(uid)
2124 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2125 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2126 }
2127 }
2128
2129 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002130 public boolean getRestrictBackground() {
2131 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2132
2133 synchronized (mRulesLock) {
2134 return mRestrictBackground;
2135 }
2136 }
2137
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002138 @Override
2139 public void setDeviceIdleMode(boolean enabled) {
2140 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2141
2142 synchronized (mRulesLock) {
2143 if (mDeviceIdleMode != enabled) {
2144 mDeviceIdleMode = enabled;
2145 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002146 // Device idle change means we need to rebuild rules for all
2147 // known apps, so do a global refresh.
2148 updateRulesForGlobalChangeLocked(false);
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002149 }
2150 if (enabled) {
2151 EventLogTags.writeDeviceIdleOnPhase("net");
2152 } else {
2153 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002154 }
2155 }
2156 }
2157 }
2158
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002159 private NetworkPolicy findPolicyForNetworkLocked(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002160 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2161 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002162 if (policy.template.matches(ident)) {
2163 return policy;
2164 }
2165 }
2166 return null;
2167 }
2168
2169 @Override
2170 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2171 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2172
2173 // only returns usage summary, so we don't require caller to have
2174 // READ_NETWORK_USAGE_HISTORY.
2175 final long token = Binder.clearCallingIdentity();
2176 try {
2177 return getNetworkQuotaInfoUnchecked(state);
2178 } finally {
2179 Binder.restoreCallingIdentity(token);
2180 }
2181 }
2182
2183 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2184 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2185
2186 final NetworkPolicy policy;
2187 synchronized (mRulesLock) {
2188 policy = findPolicyForNetworkLocked(ident);
2189 }
2190
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002191 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002192 // missing policy means we can't derive useful quota info
2193 return null;
2194 }
2195
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002196 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002197
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002198 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002199 final long start = computeLastCycleBoundary(currentTime, policy);
2200 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002201 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002202
2203 // report soft and hard limits under policy
2204 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2205 : NetworkQuotaInfo.NO_LIMIT;
2206 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2207 : NetworkQuotaInfo.NO_LIMIT;
2208
2209 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2210 }
2211
Jeff Sharkey46645002011-07-27 21:11:21 -07002212 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002213 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002214 if (state.networkInfo == null) {
2215 return false;
2216 }
2217
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002218 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2219
Jeff Sharkeyf166f482012-04-30 15:59:21 -07002220 // roaming networks are always considered metered
2221 if (ident.getRoaming()) {
2222 return true;
2223 }
2224
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002225 final NetworkPolicy policy;
2226 synchronized (mRulesLock) {
2227 policy = findPolicyForNetworkLocked(ident);
2228 }
2229
2230 if (policy != null) {
2231 return policy.metered;
2232 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002233 final int type = state.networkInfo.getType();
2234 if (isNetworkTypeMobile(type) || type == TYPE_WIMAX) {
2235 return true;
2236 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002237 return false;
2238 }
2239 }
2240
2241 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002242 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002243 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002244
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002245 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2246
Dianne Hackborn497175b2014-07-01 12:56:08 -07002247 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002248 for (String arg : args) {
2249 argSet.add(arg);
2250 }
2251
Jeff Sharkey1b861272011-05-22 00:34:52 -07002252 synchronized (mRulesLock) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002253 if (argSet.contains("--unsnooze")) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002254 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2255 mNetworkPolicy.valueAt(i).clearSnooze();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002256 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002257
Jeff Sharkey32566012014-12-02 18:30:14 -08002258 normalizePoliciesLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002259 updateNetworkEnabledLocked();
2260 updateNetworkRulesLocked();
2261 updateNotificationsLocked();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002262 writePolicyLocked();
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002263
2264 fout.println("Cleared snooze timestamps");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002265 return;
2266 }
2267
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002268 fout.print("System ready: "); fout.println(mSystemReady);
Jeff Sharkey46645002011-07-27 21:11:21 -07002269 fout.print("Restrict background: "); fout.println(mRestrictBackground);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002270 fout.print("Restrict power: "); fout.println(mRestrictPower);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002271 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002272 fout.println("Network policies:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002273 fout.increaseIndent();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002274 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2275 fout.println(mNetworkPolicy.valueAt(i).toString());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002276 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002277 fout.decreaseIndent();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002278
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07002279 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2280
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002281 fout.println("Policy for UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002282 fout.increaseIndent();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002283 int size = mUidPolicy.size();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002284 for (int i = 0; i < size; i++) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002285 final int uid = mUidPolicy.keyAt(i);
2286 final int policy = mUidPolicy.valueAt(i);
2287 fout.print("UID=");
2288 fout.print(uid);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002289 fout.print(" policy=");
Jeff Sharkeydc988062015-09-14 10:09:47 -07002290 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002291 fout.println();
2292 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002293 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002294
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002295 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2296 if (size > 0) {
2297 fout.println("Power save whitelist (except idle) app ids:");
2298 fout.increaseIndent();
2299 for (int i = 0; i < size; i++) {
2300 fout.print("UID=");
2301 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2302 fout.print(": ");
2303 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2304 fout.println();
2305 }
2306 fout.decreaseIndent();
2307 }
2308
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002309 size = mPowerSaveWhitelistAppIds.size();
2310 if (size > 0) {
2311 fout.println("Power save whitelist app ids:");
2312 fout.increaseIndent();
2313 for (int i = 0; i < size; i++) {
2314 fout.print("UID=");
2315 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2316 fout.print(": ");
2317 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2318 fout.println();
2319 }
2320 fout.decreaseIndent();
2321 }
2322
Felipe Lemeb85a6372016-01-14 16:16:16 -08002323 size = mRestrictBackgroundWhitelistUids.size();
2324 if (size > 0) {
2325 fout.println("Restrict background whitelist uids:");
2326 fout.increaseIndent();
2327 for (int i = 0; i < size; i++) {
2328 fout.print("UID=");
2329 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2330 fout.println();
2331 }
2332 fout.decreaseIndent();
2333 }
2334
Felipe Lemea9505cc2016-02-26 10:28:41 -08002335 size = mDefaultRestrictBackgroundWhitelistUids.size();
2336 if (size > 0) {
2337 fout.println("Default restrict background whitelist uids:");
2338 fout.increaseIndent();
2339 for (int i = 0; i < size; i++) {
2340 fout.print("UID=");
2341 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2342 fout.println();
2343 }
2344 fout.decreaseIndent();
2345 }
2346
2347 size = mRestrictBackgroundWhitelistRevokedUids.size();
2348 if (size > 0) {
2349 fout.println("Default restrict background whitelist uids revoked by users:");
2350 fout.increaseIndent();
2351 for (int i = 0; i < size; i++) {
2352 fout.print("UID=");
2353 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2354 fout.println();
2355 }
2356 fout.decreaseIndent();
2357 }
2358
Jeff Sharkey1b861272011-05-22 00:34:52 -07002359 final SparseBooleanArray knownUids = new SparseBooleanArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -07002360 collectKeys(mUidState, knownUids);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002361 collectKeys(mUidRules, knownUids);
2362
Felipe Leme46c4fc32016-05-04 09:21:43 -07002363 fout.println("Status for all known UIDs:");
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002364 fout.increaseIndent();
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07002365 size = knownUids.size();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002366 for (int i = 0; i < size; i++) {
2367 final int uid = knownUids.keyAt(i);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002368 fout.print("UID=");
Jeff Sharkey1b861272011-05-22 00:34:52 -07002369 fout.print(uid);
2370
Jeff Sharkeydc988062015-09-14 10:09:47 -07002371 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002372 fout.print(" state=");
2373 fout.print(state);
Felipe Lemeef89c902016-03-30 15:11:31 -07002374 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2375 fout.print(" (fg)");
2376 } else {
2377 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2378 ? " (fg svc)" : " (bg)");
2379 }
Dianne Hackborn497175b2014-07-01 12:56:08 -07002380
Felipe Leme46c4fc32016-05-04 09:21:43 -07002381 final int uidRules = mUidRules.get(uid, RULE_NONE);
2382 fout.print(" rules=");
2383 fout.print(uidRulesToString(uidRules));
2384 fout.println();
2385 }
2386 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002387
Felipe Leme46c4fc32016-05-04 09:21:43 -07002388 fout.println("Status for just UIDs with rules:");
2389 fout.increaseIndent();
2390 size = mUidRules.size();
2391 for (int i = 0; i < size; i++) {
2392 final int uid = mUidRules.keyAt(i);
2393 fout.print("UID=");
2394 fout.print(uid);
2395 final int uidRules = mUidRules.get(uid, RULE_NONE);
2396 fout.print(" rules=");
2397 fout.print(uidRulesToString(uidRules));
Jeff Sharkey1b861272011-05-22 00:34:52 -07002398 fout.println();
2399 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002400 fout.decreaseIndent();
Jeff Sharkey1b861272011-05-22 00:34:52 -07002401 }
2402 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002403
2404 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002405 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2406 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002407 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002408 this, in, out, err, args, resultReceiver);
2409 }
2410
2411 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002412 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002413 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2414
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002415 synchronized (mRulesLock) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002416 return isUidForegroundLocked(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002417 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002418 }
2419
Felipe Lemef28983d2016-03-25 12:18:23 -07002420 private boolean isUidForegroundLocked(int uid) {
2421 return isUidStateForegroundLocked(
2422 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2423 }
2424
Felipe Lemeef89c902016-03-30 15:11:31 -07002425 private boolean isUidForegroundOnRestrictBackgroundLocked(int uid) {
2426 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2427 return isProcStateAllowedWhileOnRestrictBackgroundLocked(procState);
2428 }
2429
Felipe Leme781ba142016-05-09 16:24:48 -07002430 private boolean isUidForegroundOnRestrictPowerLocked(int uid) {
2431 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2432 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2433 }
2434
Felipe Lemef28983d2016-03-25 12:18:23 -07002435 private boolean isUidStateForegroundLocked(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002436 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002437 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002438 }
2439
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002440 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002441 * Process state of UID changed; if needed, will trigger
Felipe Leme781ba142016-05-09 16:24:48 -07002442 * {@link #updateRulesForDataUsageRestrictionsLocked(int)} and
2443 * {@link #updateRulesForPowerRestrictionsLocked(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002444 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002445 private void updateUidStateLocked(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002446 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2447 if (oldUidState != uidState) {
2448 // state changed, push updated rules
2449 mUidState.put(uid, uidState);
Felipe Lemef28983d2016-03-25 12:18:23 -07002450 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002451 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2452 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002453 if (isUidIdle(uid)) {
2454 updateRuleForAppIdleLocked(uid);
2455 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002456 if (mDeviceIdleMode) {
2457 updateRuleForDeviceIdleLocked(uid);
2458 }
2459 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002460 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002461 }
Felipe Leme781ba142016-05-09 16:24:48 -07002462 updateRulesForPowerRestrictionsLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002463 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002464 updateNetworkStats(uid, isUidStateForegroundLocked(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002465 }
2466 }
2467
Felipe Lemef28983d2016-03-25 12:18:23 -07002468 private void removeUidStateLocked(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002469 final int index = mUidState.indexOfKey(uid);
2470 if (index >= 0) {
2471 final int oldUidState = mUidState.valueAt(index);
2472 mUidState.removeAt(index);
2473 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002474 updateRestrictBackgroundRulesOnUidStatusChangedLocked(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002475 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002476 if (mDeviceIdleMode) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002477 updateRuleForDeviceIdleLocked(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002478 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002479 if (mRestrictPower) {
Felipe Lemef28983d2016-03-25 12:18:23 -07002480 updateRuleForRestrictPowerLocked(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002481 }
Felipe Leme781ba142016-05-09 16:24:48 -07002482 updateRulesForPowerRestrictionsLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002483 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002484 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002485 }
2486 }
2487
Felipe Lemef28983d2016-03-25 12:18:23 -07002488 // adjust stats accounting based on foreground status
2489 private void updateNetworkStats(int uid, boolean uidForeground) {
2490 try {
2491 mNetworkStats.setUidForeground(uid, uidForeground);
2492 } catch (RemoteException e) {
2493 // ignored; service lives in system_server
2494 }
2495 }
2496
2497 private void updateRestrictBackgroundRulesOnUidStatusChangedLocked(int uid, int oldUidState,
2498 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002499 final boolean oldForeground =
2500 isProcStateAllowedWhileOnRestrictBackgroundLocked(oldUidState);
2501 final boolean newForeground =
2502 isProcStateAllowedWhileOnRestrictBackgroundLocked(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002503 if (oldForeground != newForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002504 updateRulesForDataUsageRestrictionsLocked(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002505 }
2506 }
2507
Jeff Sharkeya4620792011-05-20 15:29:23 -07002508 private void updateScreenOn() {
2509 synchronized (mRulesLock) {
2510 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002511 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002512 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002513 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002514 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002515 updateRulesForScreenLocked();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002516 }
2517 }
2518
2519 /**
2520 * Update rules that might be changed by {@link #mScreenOn} value.
2521 */
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002522 private void updateRulesForScreenLocked() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002523 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002524 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002525 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002526 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002527 final int uid = mUidState.keyAt(i);
Felipe Lemef28983d2016-03-25 12:18:23 -07002528 updateRestrictionRulesForUidLocked(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002529 }
2530 }
2531 }
2532
Felipe Leme011b98f2016-02-10 17:28:31 -08002533 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002534 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2535 }
2536
Felipe Lemeef89c902016-03-30 15:11:31 -07002537 static boolean isProcStateAllowedWhileOnRestrictBackgroundLocked(int procState) {
2538 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2539 }
2540
Felipe Leme011b98f2016-02-10 17:28:31 -08002541 void updateRulesForRestrictPowerLocked() {
2542 updateRulesForWhitelistedPowerSaveLocked(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2543 mUidFirewallPowerSaveRules);
2544 }
2545
Felipe Lemef28983d2016-03-25 12:18:23 -07002546 void updateRuleForRestrictPowerLocked(int uid) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002547 updateRulesForWhitelistedPowerSaveLocked(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
2548 }
2549
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002550 void updateRulesForDeviceIdleLocked() {
Felipe Leme011b98f2016-02-10 17:28:31 -08002551 updateRulesForWhitelistedPowerSaveLocked(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2552 mUidFirewallDozableRules);
2553 }
2554
2555 void updateRuleForDeviceIdleLocked(int uid) {
2556 updateRulesForWhitelistedPowerSaveLocked(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
2557 }
2558
Felipe Lemef28983d2016-03-25 12:18:23 -07002559 // NOTE: since both fw_dozable and fw_powersave uses the same map
2560 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002561 private void updateRulesForWhitelistedPowerSaveLocked(boolean enabled, int chain,
2562 SparseIntArray rules) {
2563 if (enabled) {
2564 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002565 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002566 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002567 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002568 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002569 for (int ui = users.size() - 1; ui >= 0; ui--) {
2570 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002571 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002572 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2573 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2574 int uid = UserHandle.getUid(user.id, appId);
2575 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2576 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002577 }
2578 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2579 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2580 int uid = UserHandle.getUid(user.id, appId);
2581 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2582 }
2583 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002584 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002585 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002586 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2587 }
2588 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002589 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002590 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002591
Felipe Leme011b98f2016-02-10 17:28:31 -08002592 enableFirewallChainLocked(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002593 }
2594
Felipe Leme781ba142016-05-09 16:24:48 -07002595 private void updateRulesForNonMeteredNetworksLocked() {
2596
2597 }
2598
Felipe Leme46c4fc32016-05-04 09:21:43 -07002599 private boolean isWhitelistedBatterySaverLocked(int uid) {
2600 final int appId = UserHandle.getAppId(uid);
2601 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2602 }
2603
Felipe Lemef28983d2016-03-25 12:18:23 -07002604 // NOTE: since both fw_dozable and fw_powersave uses the same map
2605 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Leme011b98f2016-02-10 17:28:31 -08002606 private void updateRulesForWhitelistedPowerSaveLocked(int uid, boolean enabled, int chain) {
2607 if (enabled) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002608 if (isWhitelistedBatterySaverLocked(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002609 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2610 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002611 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002612 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002613 }
2614 }
2615 }
2616
2617 void updateRulesForAppIdleLocked() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002618 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2619 uidRules.clear();
2620
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002621 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002622 final List<UserInfo> users = mUserManager.getUsers();
2623 for (int ui = users.size() - 1; ui >= 0; ui--) {
2624 UserInfo user = users.get(ui);
2625 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2626 for (int uid : idleUids) {
2627 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002628 // quick check: if this uid doesn't have INTERNET permission, it
2629 // doesn't have network access anyway, so it is a waste to mess
2630 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002631 if (hasInternetPermissions(uid)) {
2632 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002633 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002634 }
2635 }
2636 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002637
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002638 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2639 }
2640
2641 void updateRuleForAppIdleLocked(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002642 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002643
2644 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002645 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2646 && !isUidForegroundOnRestrictPowerLocked(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002647 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2648 } else {
2649 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2650 }
2651 }
2652
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002653 void updateRulesForAppIdleParoleLocked() {
2654 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
2655 enableFirewallChainLocked(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002656 }
2657
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002658 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002659 * Update rules that might be changed by {@link #mRestrictBackground},
2660 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002661 */
Felipe Leme76010a32016-03-17 13:03:11 -07002662 private void updateRulesForGlobalChangeLocked(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002663 long start;
2664 if (LOGD) start = System.currentTimeMillis();
2665
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002666 updateRulesForDeviceIdleLocked();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002667 updateRulesForAppIdleLocked();
Felipe Leme011b98f2016-02-10 17:28:31 -08002668 updateRulesForRestrictPowerLocked();
Felipe Lemef28983d2016-03-25 12:18:23 -07002669 updateRulesForRestrictBackgroundLocked();
Felipe Leme70c57c22016-03-29 10:45:13 -07002670 setRestrictBackgroundLocked(mRestrictBackground);
Felipe Leme76010a32016-03-17 13:03:11 -07002671
2672 // If the set of restricted networks may have changed, re-evaluate those.
2673 if (restrictedNetworksChanged) {
2674 normalizePoliciesLocked();
2675 updateNetworkRulesLocked();
2676 }
2677 if (LOGD) {
2678 final long delta = System.currentTimeMillis() - start;
2679 Slog.d(TAG, "updateRulesForGlobalChangeLocked(" + restrictedNetworksChanged + ") took "
2680 + delta + "ms");
2681 }
2682 }
2683
Felipe Lemef28983d2016-03-25 12:18:23 -07002684 private void updateRulesForRestrictBackgroundLocked() {
Felipe Leme76010a32016-03-17 13:03:11 -07002685 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002686
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002687 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002688 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002689 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002690 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2691 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2692 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002693
Felipe Leme03e689d2016-03-02 16:17:38 -08002694 final int usersSize = users.size();
2695 final int appsSize = apps.size();
2696 for (int i = 0; i < usersSize; i++) {
2697 final UserInfo user = users.get(i);
2698 for (int j = 0; j < appsSize; j++) {
2699 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002700 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002701 updateRulesForDataUsageRestrictionsLocked(uid);
2702 updateRulesForPowerRestrictionsLocked(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002703 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002704 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002705 }
2706
Felipe Leme76010a32016-03-17 13:03:11 -07002707 private void updateRulesForTempWhitelistChangeLocked() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002708 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002709 for (int i = 0; i < users.size(); i++) {
2710 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002711 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002712 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002713 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002714 // Update external firewall rules.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002715 updateRuleForAppIdleLocked(uid);
2716 updateRuleForDeviceIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002717 updateRuleForRestrictPowerLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002718 // Update internal rules.
2719 updateRulesForPowerRestrictionsLocked(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002720 }
2721 }
2722 }
2723
Felipe Leme70c57c22016-03-29 10:45:13 -07002724 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2725 // methods below could be merged into a isUidValidForRules() method.
2726 private boolean isUidValidForBlacklistRules(int uid) {
2727 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002728 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002729 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002730 return true;
2731 }
2732
2733 return false;
2734 }
2735
Felipe Leme70c57c22016-03-29 10:45:13 -07002736 private boolean isUidValidForWhitelistRules(int uid) {
2737 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2738 }
2739
Amith Yamasani15e472352015-04-24 19:06:07 -07002740 private boolean isUidIdle(int uid) {
2741 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2742 final int userId = UserHandle.getUserId(uid);
2743
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002744 if (!ArrayUtils.isEmpty(packages)) {
2745 for (String packageName : packages) {
2746 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2747 return false;
2748 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002749 }
2750 }
2751 return true;
2752 }
2753
2754 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002755 * Checks if an uid has INTERNET permissions.
2756 * <p>
2757 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002758 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002759 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002760 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002761 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002762 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002763 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002764 }
2765 } catch (RemoteException e) {
2766 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002767 return true;
2768 }
2769
2770 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002771 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002772 *
Felipe Leme781ba142016-05-09 16:24:48 -07002773 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002774 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002775 * <li>Doze mode
2776 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002777 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002778 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002779 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002780 *
2781 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002782 */
Felipe Lemef28983d2016-03-25 12:18:23 -07002783 private void updateRestrictionRulesForUidLocked(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002784 // Methods below only changes the firewall rules for the power-related modes.
2785 updateRuleForDeviceIdleLocked(uid);
2786 updateRuleForAppIdleLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002787 updateRuleForRestrictPowerLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002788
2789 // Update internal state for power-related modes.
2790 updateRulesForPowerRestrictionsLocked(uid);
2791
2792 // Update firewall and internal rules for Data Saver Mode.
2793 updateRulesForDataUsageRestrictionsLocked(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002794 }
2795
Felipe Leme70c57c22016-03-29 10:45:13 -07002796 /**
2797 * Applies network rules to bandwidth controllers based on process state and user-defined
2798 * restrictions (blacklist / whitelist).
2799 *
2800 * <p>
2801 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2802 * networks:
2803 * <ul>
2804 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2805 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2806 * also blacklisted.
2807 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2808 * no UIDs other those whitelisted will have access.
2809 * <ul>
2810 *
2811 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2812 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2813 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2814 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Leme781ba142016-05-09 16:24:48 -07002815 * this ({@link #updateRulesForDataUsageRestrictionsLocked(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002816 * {@link INetworkManagementService}, but this method should also be called in events (like
2817 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2818 * following rules should also be applied:
2819 *
2820 * <ul>
2821 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2822 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2823 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2824 * {@code bw_penalty_box}.
2825 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2826 * </ul>
2827 *
2828 * <p>For optimization, the rules are only applied on user apps that have internet access
2829 * permission, since there is no need to change the {@code iptables} rule if the app does not
2830 * have permission to use the internet.
2831 *
2832 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002833 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002834 */
Felipe Leme781ba142016-05-09 16:24:48 -07002835 private void updateRulesForDataUsageRestrictionsLocked(int uid) {
2836 updateRulesForDataUsageRestrictionsLocked(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002837 }
2838
2839 /**
Felipe Leme781ba142016-05-09 16:24:48 -07002840 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsLocked(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002841 * app is removed - it ignores the UID validity check.
2842 */
Felipe Leme781ba142016-05-09 16:24:48 -07002843 private void updateRulesForDataUsageRestrictionsLocked(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002844 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2845 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2846 return;
2847 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002848
Dianne Hackborn497175b2014-07-01 12:56:08 -07002849 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002850 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemeef89c902016-03-30 15:11:31 -07002851 final boolean isForeground = isUidForegroundOnRestrictBackgroundLocked(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002852
Felipe Leme781ba142016-05-09 16:24:48 -07002853 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2854 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2855 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2856 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002857
Felipe Leme70c57c22016-03-29 10:45:13 -07002858 // First step: define the new rule based on user restrictions and foreground state.
2859 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002860 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2861 newRule = RULE_TEMPORARY_ALLOW_METERED;
2862 } else if (isWhitelisted) {
2863 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002864 }
2865 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002866 if (isBlacklisted) {
2867 newRule = RULE_REJECT_METERED;
2868 } else if (mRestrictBackground && isWhitelisted) {
2869 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002870 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002871 }
Felipe Leme781ba142016-05-09 16:24:48 -07002872 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002873
Felipe Lemef28983d2016-03-25 12:18:23 -07002874 if (LOGV) {
Felipe Leme781ba142016-05-09 16:24:48 -07002875 Log.v(TAG, "updateRuleForRestrictBackgroundLocked(" + uid + ")"
2876 + ": isForeground=" +isForeground
2877 + ", isBlacklisted=" + isBlacklisted
2878 + ", isWhitelisted=" + isWhitelisted
2879 + ", oldRule=" + uidRulesToString(oldRule)
2880 + ", newRule=" + uidRulesToString(newRule)
2881 + ", newUidRules=" + uidRulesToString(newUidRules)
2882 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002883 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002884
Felipe Leme46c4fc32016-05-04 09:21:43 -07002885 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002886 mUidRules.delete(uid);
2887 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002888 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002889 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002890
Felipe Lemed31a97f2016-05-06 14:53:50 -07002891 boolean changed = false;
2892
Felipe Leme70c57c22016-03-29 10:45:13 -07002893 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002894 if (newRule != oldRule) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07002895 changed = true;
2896
Felipe Leme781ba142016-05-09 16:24:48 -07002897 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002898 // Temporarily whitelist foreground app, removing from blacklist if necessary
2899 // (since bw_penalty_box prevails over bw_happy_box).
2900
2901 setMeteredNetworkWhitelist(uid, true);
2902 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2903 // but ideally it should be just:
2904 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002905 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002906 setMeteredNetworkBlacklist(uid, false);
2907 }
Felipe Leme781ba142016-05-09 16:24:48 -07002908 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002909 // Remove temporary whitelist from app that is not on foreground anymore.
2910
2911 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2912 // but ideally they should be just:
2913 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2914 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002915 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002916 setMeteredNetworkWhitelist(uid, false);
2917 }
Felipe Leme781ba142016-05-09 16:24:48 -07002918 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002919 setMeteredNetworkBlacklist(uid, true);
2920 }
Felipe Leme781ba142016-05-09 16:24:48 -07002921 } else if ((newRule & RULE_REJECT_METERED) != 0
2922 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002923 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002924 setMeteredNetworkBlacklist(uid, isBlacklisted);
2925 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002926 // Since blacklist prevails over whitelist, we need to handle the special case
2927 // where app is whitelisted and blacklisted at the same time (although such
2928 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07002929 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002930 }
Felipe Leme781ba142016-05-09 16:24:48 -07002931 } else if ((newRule & RULE_ALLOW_METERED) != 0
2932 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002933 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07002934 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002935 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002936 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002937 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2938 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07002939 + ", whitelisted=" + isWhitelisted
2940 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07002941 + ", newRule=" + uidRulesToString(newUidRules)
2942 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07002943 }
Felipe Leme781ba142016-05-09 16:24:48 -07002944
2945 // Dispatch changed rule to existing listeners.
2946 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
2947 }
2948 }
2949
2950 /**
2951 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
2952 * listeners in case of change.
2953 * <p>
2954 * There are 3 power-related rules that affects whether an app has background access on
2955 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
2956 * restriction, it's added to the equivalent firewall chain:
2957 * <ul>
2958 * <li>App is idle: {@code fw_standby} firewall chain.
2959 * <li>Device is idle: {@code fw_dozable} firewall chain.
2960 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
2961 * </ul>
2962 * <p>
2963 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
2964 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
2965 * <p>
2966 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
2967 */
2968 private void updateRulesForPowerRestrictionsLocked(int uid) {
2969 if (!isUidValidForBlacklistRules(uid)) {
2970 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
2971 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002972 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002973
Felipe Leme781ba142016-05-09 16:24:48 -07002974 final boolean isIdle = isUidIdle(uid);
2975 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
2976 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2977 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
2978 final boolean isForeground = isUidForegroundOnRestrictPowerLocked(uid);
2979
2980 final boolean isWhitelisted = isWhitelistedBatterySaverLocked(uid);
2981 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
2982 int newRule = RULE_NONE;
2983
2984 // First step: define the new rule based on user restrictions and foreground state.
2985
2986 // NOTE: if statements below could be inlined, but it's easier to understand the logic
2987 // by considering the foreground and non-foreground states.
2988 if (isForeground) {
2989 if (restrictMode) {
2990 newRule = RULE_ALLOW_ALL;
2991 }
2992 } else if (restrictMode) {
2993 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
2994 }
2995
2996 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
2997
2998 if (LOGV) {
2999 Log.v(TAG, "updateRulesForNonMeteredNetworksLocked(" + uid + ")"
3000 + ", isIdle: " + isIdle
3001 + ", mRestrictPower: " + mRestrictPower
3002 + ", mDeviceIdleMode: " + mDeviceIdleMode
3003 + ", isForeground=" + isForeground
3004 + ", isWhitelisted=" + isWhitelisted
3005 + ", oldRule=" + uidRulesToString(oldRule)
3006 + ", newRule=" + uidRulesToString(newRule)
3007 + ", newUidRules=" + uidRulesToString(newUidRules)
3008 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3009 }
3010
3011 if (newUidRules == RULE_NONE) {
3012 mUidRules.delete(uid);
3013 } else {
3014 mUidRules.put(uid, newUidRules);
3015 }
3016
3017 // Second step: notify listeners if state changed.
3018 if (newRule != oldRule) {
3019 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003020 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003021 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003022 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3023 } else {
3024 // All scenarios should have been covered above
3025 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3026 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003027 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003028 + ", newRule=" + uidRulesToString(newUidRules)
3029 + ", oldRule=" + uidRulesToString(oldUidRules));
3030 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003031 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003032 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003033 }
3034
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003035 private class AppIdleStateChangeListener
3036 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3037
3038 @Override
3039 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3040 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003041 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3042 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003043 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003044 synchronized (mRulesLock) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003045 updateRuleForAppIdleLocked(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003046 updateRulesForPowerRestrictionsLocked(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003047 }
3048 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003049 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003050 }
3051
3052 @Override
3053 public void onParoleStateChanged(boolean isParoleOn) {
3054 synchronized (mRulesLock) {
3055 updateRulesForAppIdleParoleLocked();
3056 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003057 }
3058 }
3059
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003060 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3061 if (listener != null) {
3062 try {
3063 listener.onUidRulesChanged(uid, uidRules);
3064 } catch (RemoteException ignored) {
3065 }
3066 }
3067 }
3068
3069 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3070 String[] meteredIfaces) {
3071 if (listener != null) {
3072 try {
3073 listener.onMeteredIfacesChanged(meteredIfaces);
3074 } catch (RemoteException ignored) {
3075 }
3076 }
3077 }
3078
3079 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3080 boolean restrictBackground) {
3081 if (listener != null) {
3082 try {
3083 listener.onRestrictBackgroundChanged(restrictBackground);
3084 } catch (RemoteException ignored) {
3085 }
3086 }
3087 }
3088
3089 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3090 int uid, boolean whitelisted) {
3091 if (listener != null) {
3092 try {
3093 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3094 } catch (RemoteException ignored) {
3095 }
3096 }
3097 }
3098
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003099 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003100 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003101 public boolean handleMessage(Message msg) {
3102 switch (msg.what) {
3103 case MSG_RULES_CHANGED: {
3104 final int uid = msg.arg1;
3105 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003106 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003107 final int length = mListeners.beginBroadcast();
3108 for (int i = 0; i < length; i++) {
3109 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003110 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003111 }
3112 mListeners.finishBroadcast();
3113 return true;
3114 }
3115 case MSG_METERED_IFACES_CHANGED: {
3116 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003117 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003118 final int length = mListeners.beginBroadcast();
3119 for (int i = 0; i < length; i++) {
3120 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003121 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003122 }
3123 mListeners.finishBroadcast();
3124 return true;
3125 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003126 case MSG_LIMIT_REACHED: {
3127 final String iface = (String) msg.obj;
3128
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003129 maybeRefreshTrustedTime();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003130 synchronized (mRulesLock) {
3131 if (mMeteredIfaces.contains(iface)) {
3132 try {
3133 // force stats update to make sure we have
3134 // numbers that caused alert to trigger.
3135 mNetworkStats.forceUpdate();
3136 } catch (RemoteException e) {
3137 // ignored; service lives in system_server
3138 }
3139
3140 updateNetworkEnabledLocked();
3141 updateNotificationsLocked();
3142 }
3143 }
3144 return true;
3145 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003146 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3147 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003148 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003149 final int length = mListeners.beginBroadcast();
3150 for (int i = 0; i < length; i++) {
3151 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003152 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003153 }
3154 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003155 final Intent intent =
3156 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3157 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3158 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3159 return true;
3160 }
3161 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003162 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3163 // - when an app is whitelisted
3164 // - when an app is blacklisted
3165 //
3166 // Whether the internal listeners (INetworkPolicyListener implementations) or
3167 // app broadcast receivers are notified depend on the following rules:
3168 //
3169 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3170 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3171 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003172 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003173 final boolean changed = msg.arg2 == 1;
3174 final Boolean whitelisted = (Boolean) msg.obj;
3175
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003176 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003177 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003178 final boolean whitelistedBool = whitelisted.booleanValue();
3179 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3180 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003181 final int length = mListeners.beginBroadcast();
3182 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003183 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003184 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3185 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003186 }
3187 mListeners.finishBroadcast();
3188 }
3189
Felipe Leme9778f762016-01-27 14:46:39 -08003190 final PackageManager pm = mContext.getPackageManager();
3191 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003192 if (changed && packages != null) {
3193 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003194 final int userId = UserHandle.getUserId(uid);
3195 for (String packageName : packages) {
3196 final Intent intent = new Intent(
3197 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3198 intent.setPackage(packageName);
3199 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3200 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3201 }
Felipe Leme9778f762016-01-27 14:46:39 -08003202 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003203 return true;
3204 }
3205 case MSG_ADVISE_PERSIST_THRESHOLD: {
3206 final long lowestRule = (Long) msg.obj;
3207 try {
3208 // make sure stats are recorded frequently enough; we aim
3209 // for 2MB threshold for 2GB/month rules.
3210 final long persistThreshold = lowestRule / 1000;
3211 mNetworkStats.advisePersistThreshold(persistThreshold);
3212 } catch (RemoteException e) {
3213 // ignored; service lives in system_server
3214 }
3215 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003216 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003217 case MSG_SCREEN_ON_CHANGED: {
3218 updateScreenOn();
3219 return true;
3220 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003221 case MSG_UPDATE_INTERFACE_QUOTA: {
3222 removeInterfaceQuota((String) msg.obj);
3223 // int params need to be stitched back into a long
3224 setInterfaceQuota((String) msg.obj,
3225 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3226 return true;
3227 }
3228 case MSG_REMOVE_INTERFACE_QUOTA: {
3229 removeInterfaceQuota((String) msg.obj);
3230 return true;
3231 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003232 default: {
3233 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003234 }
3235 }
3236 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003237 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003238
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003239 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003240 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003241 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003242 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003243 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003244 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003245 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003246 }
3247 }
3248
3249 private void removeInterfaceQuota(String iface) {
3250 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003251 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003252 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003253 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003254 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003255 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003256 }
3257 }
3258
Felipe Leme70c57c22016-03-29 10:45:13 -07003259 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3260 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003261 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003262 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003263 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003264 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3265 } catch (RemoteException e) {
3266 // ignored; service lives in system_server
3267 }
3268 }
3269
3270 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3271 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3272 try {
3273 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3274 } catch (IllegalStateException e) {
3275 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003276 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003277 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003278 }
3279 }
3280
Amith Yamasani15e472352015-04-24 19:06:07 -07003281 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003282 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3283 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3284 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003285 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003286 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003287 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003288 int size = uidRules.size();
3289 int[] uids = new int[size];
3290 int[] rules = new int[size];
3291 for(int index = size - 1; index >= 0; --index) {
3292 uids[index] = uidRules.keyAt(index);
3293 rules[index] = uidRules.valueAt(index);
3294 }
3295 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003296 } catch (IllegalStateException e) {
3297 Log.wtf(TAG, "problem setting firewall uid rules", e);
3298 } catch (RemoteException e) {
3299 // ignored; service lives in system_server
3300 }
3301 }
3302
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003303 /**
3304 * Add or remove a uid to the firewall blacklist for all network ifaces.
3305 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003306 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003307 if (chain == FIREWALL_CHAIN_DOZABLE) {
3308 mUidFirewallDozableRules.put(uid, rule);
3309 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3310 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003311 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3312 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003313 }
3314
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003315 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003316 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003317 } catch (IllegalStateException e) {
3318 Log.wtf(TAG, "problem setting firewall uid rules", e);
3319 } catch (RemoteException e) {
3320 // ignored; service lives in system_server
3321 }
3322 }
3323
3324 /**
3325 * Add or remove a uid to the firewall blacklist for all network ifaces.
3326 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003327 private void enableFirewallChainLocked(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003328 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3329 mFirewallChainStates.get(chain) == enable) {
3330 // All is the same, nothing to do.
3331 return;
3332 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003333 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003334 try {
3335 mNetworkManager.setFirewallChainEnabled(chain, enable);
3336 } catch (IllegalStateException e) {
3337 Log.wtf(TAG, "problem enable firewall chain", e);
3338 } catch (RemoteException e) {
3339 // ignored; service lives in system_server
3340 }
3341 }
3342
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003343 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3344 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003345 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003346 } catch (RuntimeException e) {
3347 Slog.w(TAG, "problem reading network stats: " + e);
3348 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003349 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003350 // ignored; service lives in system_server
3351 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003352 }
3353 }
3354
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003355 private boolean isBandwidthControlEnabled() {
3356 final long token = Binder.clearCallingIdentity();
3357 try {
3358 return mNetworkManager.isBandwidthControlEnabled();
3359 } catch (RemoteException e) {
3360 // ignored; service lives in system_server
3361 return false;
3362 } finally {
3363 Binder.restoreCallingIdentity(token);
3364 }
3365 }
3366
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003367 /**
3368 * Try refreshing {@link #mTime} when stale.
3369 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003370 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003371 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003372 mTime.forceRefresh();
3373 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003374 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003375
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003376 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003377 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3378 }
3379
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003380 private static Intent buildAllowBackgroundDataIntent() {
3381 return new Intent(ACTION_ALLOW_BACKGROUND);
3382 }
3383
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003384 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3385 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3386 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3387 return intent;
3388 }
3389
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003390 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3391 final Intent intent = new Intent();
3392 intent.setComponent(new ComponentName(
3393 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3394 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3395 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3396 return intent;
3397 }
3398
3399 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3400 final Intent intent = new Intent();
3401 intent.setComponent(new ComponentName(
3402 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3403 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3404 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3405 return intent;
3406 }
3407
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003408 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003409 public void addIdleHandler(IdleHandler handler) {
3410 mHandler.getLooper().getQueue().addIdleHandler(handler);
3411 }
3412
Jeff Sharkey1b861272011-05-22 00:34:52 -07003413 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3414 final int size = source.size();
3415 for (int i = 0; i < size; i++) {
3416 target.put(source.keyAt(i), true);
3417 }
3418 }
3419
Stuart Scottf1fb3972015-04-02 18:00:02 -07003420 @Override
3421 public void factoryReset(String subscriber) {
3422 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3423
Stuart Scotte3e314d2015-04-20 14:07:45 -07003424 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3425 return;
3426 }
3427
Stuart Scottf1fb3972015-04-02 18:00:02 -07003428 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003429 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003430 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3431 for (NetworkPolicy policy : policies) {
3432 if (policy.template.equals(template)) {
3433 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3434 policy.inferred = false;
3435 policy.clearSnooze();
3436 }
3437 }
3438 setNetworkPolicies(policies);
3439
3440 // Turn restrict background data off
3441 setRestrictBackground(false);
3442
Stuart Scotte3e314d2015-04-20 14:07:45 -07003443 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3444 // Remove app's "restrict background data" flag
3445 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3446 setUidPolicy(uid, POLICY_NONE);
3447 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003448 }
3449 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003450
3451 private class MyPackageMonitor extends PackageMonitor {
3452
3453 @Override
3454 public void onPackageRemoved(String packageName, int uid) {
3455 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
3456 synchronized (mRulesLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003457 removeRestrictBackgroundWhitelistedUidLocked(uid, true, true);
Felipe Leme781ba142016-05-09 16:24:48 -07003458 updateRestrictionRulesForUidLocked(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003459 }
3460 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003461 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003462
3463 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3464
3465 @Override
3466 public void resetUserState(int userId) {
3467 synchronized (mRulesLock) {
3468 boolean changed = removeUserStateLocked(userId, false);
3469 changed = addDefaultRestrictBackgroundWhitelistUidsLocked(userId) || changed;
3470 if (changed) {
3471 writePolicyLocked();
3472 }
3473 }
3474 }
3475 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003476}