blob: 3e1c529a5fc60cc6ab3ca50e59cbf6e16a98fa0c [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Felipe Leme84d39732016-09-08 13:26:55 -070093import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070094import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070096import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070099import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.Notification;
101import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700102import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700103import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700104import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700106import android.content.Intent;
107import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700109import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700111import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700112import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700113import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700116import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700119import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700122import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700124import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700125import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700127import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiConfiguration;
129import android.net.wifi.WifiInfo;
130import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700131import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700132import android.os.Environment;
133import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700134import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700136import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700141import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700142import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600143import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.ServiceManager;
Felipe Leme873a83a2016-09-07 11:34:10 -0700145import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700146import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700147import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700148import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800149import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700150import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700151import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700152import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700153import android.util.ArrayMap;
154import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700155import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700156import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700157import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700159import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700160import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161import android.util.SparseBooleanArray;
162import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.TrustedTime;
164import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165
Jeff Sharkey497e4432011-06-14 17:27:29 -0700166import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700167import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800168import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800169import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800170import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700172import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700173import com.android.server.DeviceIdleController;
174import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800176import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600177
178import libcore.io.IoUtils;
179
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181
182import org.xmlpull.v1.XmlPullParser;
183import org.xmlpull.v1.XmlPullParserException;
184import org.xmlpull.v1.XmlSerializer;
185
186import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700187import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import java.io.FileInputStream;
189import java.io.FileNotFoundException;
190import java.io.FileOutputStream;
191import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700192import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700193import java.lang.annotation.Retention;
194import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100195import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import java.util.ArrayList;
197import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700198import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700200/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700201 * Service that maintains low-level network policy rules, using
202 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 * <p>
204 * Derives active rules by combining a given policy with other system status,
205 * and delivers to listeners, such as {@link ConnectivityManager}, for
206 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700207 *
208 * <p>
209 * This class uses 2-3 locks to synchronize state:
210 * <ul>
211 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
212 * rules).
213 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
214 * as network policies).
215 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
216 * must be held.
217 * </ul>
218 *
219 * <p>
220 * As such, methods that require synchronization have the following prefixes:
221 * <ul>
222 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
223 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
224 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
225 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
226 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700227 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700228public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800229 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700230 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700231 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700232
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700233 private static final int VERSION_INIT = 1;
234 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700235 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800236 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800237 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800238 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700239 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700240 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700241 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700242 private static final int VERSION_SWITCH_UID = 10;
243 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700248 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700250 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700251
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700252 private static final String TAG_POLICY_LIST = "policy-list";
253 private static final String TAG_NETWORK_POLICY = "network-policy";
254 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700255 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800256 private static final String TAG_WHITELIST = "whitelist";
257 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800258 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259
260 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700261 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700262 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
263 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700264 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800266 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267 private static final String ATTR_WARNING_BYTES = "warningBytes";
268 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700269 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800270 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
271 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800272 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700273 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700275 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 private static final String ATTR_POLICY = "policy";
277
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800279 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800280 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800281 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
284
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700285 private static final int MSG_RULES_CHANGED = 1;
286 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800287 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800288 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700289 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Felipe Leme9778f762016-01-27 14:46:39 -0800290 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700291 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
292 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700293 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
Felipe Leme84d39732016-09-08 13:26:55 -0700294 private static final int MSG_SET_FIREWALL_RULES = 13;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700295
Jeff Sharkey75279902011-05-24 18:39:45 -0700296 private final Context mContext;
297 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700298 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700299 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700300 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700302 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700303
304 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700305 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700306 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700307 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700308
Felipe Lemef0823852016-06-08 13:43:08 -0700309 // See main javadoc for instructions on how to use these locks.
310 final Object mUidRulesFirstLock = new Object();
311 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700312
Felipe Lemef0823852016-06-08 13:43:08 -0700313 @GuardedBy("allLocks") volatile boolean mSystemReady;
314
Felipe Lemef0823852016-06-08 13:43:08 -0700315 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
316 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
317 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700318
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700319 private final boolean mSuppressDefaultPolicy;
320
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700321 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700323 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800324 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700325
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700326 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700327 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700328 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700329 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700330
Felipe Lemef0823852016-06-08 13:43:08 -0700331 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700332 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700333 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700334 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700335 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800336 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700337
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700338 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700339 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700340 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
341
Jeff Sharkey32566012014-12-02 18:30:14 -0800342 /**
343 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700344 * in power save mode, except device idle (doze) still applies.
345 * TODO: An int array might be sufficient
346 */
Felipe Lemef0823852016-06-08 13:43:08 -0700347 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700348 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
349
350 /**
351 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700353 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800354 */
Felipe Lemef0823852016-06-08 13:43:08 -0700355 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700356 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700357
Felipe Lemef0823852016-06-08 13:43:08 -0700358 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700359 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
360
Felipe Lemeb85a6372016-01-14 16:16:16 -0800361 /**
362 * UIDs that have been white-listed to avoid restricted background.
363 */
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800365 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
366
Felipe Lemea9505cc2016-02-26 10:28:41 -0800367 /**
368 * UIDs that have been initially white-listed by system to avoid restricted background.
369 */
Felipe Lemef0823852016-06-08 13:43:08 -0700370 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800371 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
372 new SparseBooleanArray();
373
374 /**
375 * UIDs that have been initially white-listed by system to avoid restricted background,
376 * but later revoked by user.
377 */
Felipe Lemef0823852016-06-08 13:43:08 -0700378 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800379 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
380 new SparseBooleanArray();
381
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700382 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800384 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700385 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800387 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700388
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700389 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700391 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700392
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700393 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700394 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800395 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700396
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600397 /** Higher priority listener before general event dispatch */
398 private INetworkPolicyListener mConnectivityListener;
399
Jeff Sharkey32566012014-12-02 18:30:14 -0800400 private final RemoteCallbackList<INetworkPolicyListener>
401 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700402
Dianne Hackborn497175b2014-07-01 12:56:08 -0700403 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404
Felipe Lemef0823852016-06-08 13:43:08 -0700405 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700406 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700407
Svet Ganov16a16892015-04-16 10:32:04 -0700408 private final AppOpsManager mAppOps;
409
Felipe Lemeb85a6372016-01-14 16:16:16 -0800410 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800411 private final IPackageManager mIPm;
412
Felipe Lemeb85a6372016-01-14 16:16:16 -0800413
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700414 // TODO: keep whitelist of system-critical services that should never have
415 // rules enforced, such as system, phone, and radio UIDs.
416
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700417 // TODO: migrate notifications to SystemUI
418
Jeff Sharkey75279902011-05-24 18:39:45 -0700419 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Lemef8dd7b42016-08-10 13:00:32 -0700420 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
421 this(context, activityManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700422 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700423 }
424
425 private static File getSystemDir() {
426 return new File(Environment.getDataDirectory(), "system");
427 }
428
429 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Lemef8dd7b42016-08-10 13:00:32 -0700430 INetworkStatsService networkStats, INetworkManagementService networkManagement,
431 TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700432 mContext = checkNotNull(context, "missing context");
433 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700434 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700435 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700436 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700437 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700438 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700439 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800440 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700441
Amith Yamasani450a16b2013-09-18 16:28:50 -0700442 HandlerThread thread = new HandlerThread(TAG);
443 thread.start();
444 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700445
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700446 mSuppressDefaultPolicy = suppressDefaultPolicy;
447
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700448 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700449
450 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800451
452 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700453
454 // Expose private service for system components to use.
455 LocalServices.addService(NetworkPolicyManagerInternal.class,
456 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700457 }
458
459 public void bindConnectivityManager(IConnectivityManager connManager) {
460 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700461 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700462
Jeff Sharkey497e4432011-06-14 17:27:29 -0700463 public void bindNotificationManager(INotificationManager notifManager) {
464 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
465 }
466
Felipe Lemef0823852016-06-08 13:43:08 -0700467 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700468 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700469 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
470 mPowerSaveWhitelistExceptIdleAppIds.clear();
471 if (whitelist != null) {
472 for (int uid : whitelist) {
473 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
474 }
475 }
476 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700477 mPowerSaveWhitelistAppIds.clear();
478 if (whitelist != null) {
479 for (int uid : whitelist) {
480 mPowerSaveWhitelistAppIds.put(uid, true);
481 }
482 }
483 } catch (RemoteException e) {
484 }
485 }
486
Felipe Lemea9505cc2016-02-26 10:28:41 -0800487 /**
488 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
489 * revoke the whitelist.
490 *
491 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
492 */
Felipe Lemef0823852016-06-08 13:43:08 -0700493 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800494 final List<UserInfo> users = mUserManager.getUsers();
495 final int numberUsers = users.size();
496
Felipe Lemea110eec2016-04-29 09:58:06 -0700497 boolean changed = false;
498 for (int i = 0; i < numberUsers; i++) {
499 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700500 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700501 }
502 return changed;
503 }
504
Felipe Lemef0823852016-06-08 13:43:08 -0700505 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700506 final SystemConfig sysConfig = SystemConfig.getInstance();
507 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800508 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
509 boolean changed = false;
510 for (int i = 0; i < allowDataUsage.size(); i++) {
511 final String pkg = allowDataUsage.valueAt(i);
512 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700513 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
514 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800515 final ApplicationInfo app;
516 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700517 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800518 } catch (PackageManager.NameNotFoundException e) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700519 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
520 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800521 continue;
522 }
523 if (!app.isPrivilegedApp()) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700524 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
525 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800526 continue;
527 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700528 final int uid = UserHandle.getUid(userId, app.uid);
529 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
530 if (LOGD)
531 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
532 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800533 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700534 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700535 if (LOGD)
536 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
537 + userId + ") to restrict background whitelist");
Felipe Lemea110eec2016-04-29 09:58:06 -0700538 mRestrictBackgroundWhitelistUids.append(uid, true);
539 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800540 }
541 }
542 return changed;
543 }
544
Felipe Lemef0823852016-06-08 13:43:08 -0700545 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700546 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700547 // Clear the states of the current whitelist
548 final int N = mPowerSaveTempWhitelistAppIds.size();
549 for (int i = 0; i < N; i++) {
550 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
551 }
552 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700553 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700554 if (whitelist != null) {
555 for (int uid : whitelist) {
556 mPowerSaveTempWhitelistAppIds.put(uid, true);
557 }
558 }
559 } catch (RemoteException e) {
560 }
561 }
562
Amith Yamasani06f08062015-06-12 13:23:33 -0700563 /**
564 * Remove unnecessary entries in the temp whitelist
565 */
Felipe Lemef0823852016-06-08 13:43:08 -0700566 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700567 final int N = mPowerSaveTempWhitelistAppIds.size();
568 for (int i = N - 1; i >= 0; i--) {
569 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
570 mPowerSaveTempWhitelistAppIds.removeAt(i);
571 }
572 }
573 }
574
Jeff Sharkeya4620792011-05-20 15:29:23 -0700575 public void systemReady() {
Felipe Leme873a83a2016-09-07 11:34:10 -0700576 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
577 try {
578 if (!isBandwidthControlEnabled()) {
579 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
580 return;
581 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700582
Felipe Leme873a83a2016-09-07 11:34:10 -0700583 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700584
Felipe Leme873a83a2016-09-07 11:34:10 -0700585 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800586
Felipe Leme873a83a2016-09-07 11:34:10 -0700587 synchronized (mUidRulesFirstLock) {
588 synchronized (mNetworkPoliciesSecondLock) {
589 updatePowerSaveWhitelistUL();
590 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
591 mPowerManagerInternal.registerLowPowerModeObserver(
592 new PowerManagerInternal.LowPowerModeListener() {
593 @Override
594 public void onLowPowerModeChanged(boolean enabled) {
595 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
596 synchronized (mUidRulesFirstLock) {
597 if (mRestrictPower != enabled) {
598 mRestrictPower = enabled;
599 updateRulesForRestrictPowerUL();
600 }
Felipe Lemef0823852016-06-08 13:43:08 -0700601 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700602 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700603 });
604 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
605
606 mSystemReady = true;
607
608 // read policy from disk
609 readPolicyAL();
610
611 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
612 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700613 }
Felipe Lemef0823852016-06-08 13:43:08 -0700614
Felipe Leme873a83a2016-09-07 11:34:10 -0700615 setRestrictBackgroundUL(mRestrictBackground);
616 updateRulesForGlobalChangeAL(false);
617 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700618 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700620
621 try {
622 mActivityManager.registerUidObserver(mUidObserver,
623 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
624 mNetworkManager.registerObserver(mAlertObserver);
625 } catch (RemoteException e) {
626 // ignored; both services live in system_server
627 }
628
629 // listen for changes to power save whitelist
630 final IntentFilter whitelistFilter = new IntentFilter(
631 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
632 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
633
634 DeviceIdleController.LocalService deviceIdleService
635 = LocalServices.getService(DeviceIdleController.LocalService.class);
636 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
637
638 // watch for network interfaces to be claimed
639 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
640 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
641
642 // listen for package changes to update policy
643 final IntentFilter packageFilter = new IntentFilter();
644 packageFilter.addAction(ACTION_PACKAGE_ADDED);
645 packageFilter.addDataScheme("package");
646 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
647
648 // listen for UID changes to update policy
649 mContext.registerReceiver(
650 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
651
652 // listen for user changes to update policy
653 final IntentFilter userFilter = new IntentFilter();
654 userFilter.addAction(ACTION_USER_ADDED);
655 userFilter.addAction(ACTION_USER_REMOVED);
656 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
657
658 // listen for stats update events
659 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
660 mContext.registerReceiver(
661 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
662
663 // listen for restrict background changes from notifications
664 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
665 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
666
667 // listen for snooze warning from notifications
668 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
669 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
670 MANAGE_NETWORK_POLICY, mHandler);
671
672 // listen for configured wifi networks to be removed
673 final IntentFilter wifiConfigFilter =
674 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
675 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
676
677 // listen for wifi state changes to catch metered hint
678 final IntentFilter wifiStateFilter = new IntentFilter(
679 WifiManager.NETWORK_STATE_CHANGED_ACTION);
680 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
681
682 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
683 } finally {
684 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700685 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700686 }
687
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700688 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700689 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700690 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
691 try {
692 synchronized (mUidRulesFirstLock) {
693 updateUidStateUL(uid, procState);
694 }
695 } finally {
696 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700697 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700698 }
699
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700700 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700701 synchronized (mUidRulesFirstLock) {
702 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700703 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700704 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700705
706 @Override public void onUidActive(int uid) throws RemoteException {
707 }
708
709 @Override public void onUidIdle(int uid) throws RemoteException {
710 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700711 };
712
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700713 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700714 @Override
715 public void onReceive(Context context, Intent intent) {
716 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700717 synchronized (mUidRulesFirstLock) {
718 updatePowerSaveWhitelistUL();
719 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700720 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700721 }
722 }
723 };
724
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700725 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
726 @Override
727 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700728 synchronized (mUidRulesFirstLock) {
729 updatePowerSaveTempWhitelistUL();
730 updateRulesForTempWhitelistChangeUL();
731 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700732 }
733 }
734 };
735
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700736 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700737 @Override
738 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700739 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700740
741 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700742 final int uid = intent.getIntExtra(EXTRA_UID, -1);
743 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700744
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700745 if (ACTION_PACKAGE_ADDED.equals(action)) {
746 // update rules for UID, since it might be subject to
747 // global background data policy
748 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700749 synchronized (mUidRulesFirstLock) {
750 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700751 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700752 }
753 }
754 };
755
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700756 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700757 @Override
758 public void onReceive(Context context, Intent intent) {
759 // on background handler thread, and UID_REMOVED is protected
760
761 final int uid = intent.getIntExtra(EXTRA_UID, -1);
762 if (uid == -1) return;
763
764 // remove any policy and update rules to clean up
765 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700766 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700767 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700768 updateRestrictionRulesForUidUL(uid);
769 synchronized (mNetworkPoliciesSecondLock) {
770 writePolicyAL();
771 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700772 }
773 }
774 };
775
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700776 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700777 @Override
778 public void onReceive(Context context, Intent intent) {
779 // on background handler thread, and USER_ADDED and USER_REMOVED
780 // broadcasts are protected
781
782 final String action = intent.getAction();
783 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
784 if (userId == -1) return;
785
Amith Yamasani15e472352015-04-24 19:06:07 -0700786 switch (action) {
787 case ACTION_USER_REMOVED:
788 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700789 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800790 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700791 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700792 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700793 if (action == ACTION_USER_ADDED) {
794 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700795 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700796 }
797 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700798 synchronized (mNetworkPoliciesSecondLock) {
799 updateRulesForGlobalChangeAL(true);
800 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700801 }
802 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700803 }
804 }
805 };
806
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700807 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700808 * Receiver that watches for {@link INetworkStatsService} updates, which we
809 * use to check against {@link NetworkPolicy#warningBytes}.
810 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700811 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700812 @Override
813 public void onReceive(Context context, Intent intent) {
814 // on background handler thread, and verified
815 // READ_NETWORK_USAGE_HISTORY permission above.
816
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800817 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700818 synchronized (mNetworkPoliciesSecondLock) {
819 updateNetworkEnabledNL();
820 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700821 }
822 }
823 };
824
825 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700826 * Receiver that watches for {@link Notification} control of
827 * {@link #mRestrictBackground}.
828 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700829 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700830 @Override
831 public void onReceive(Context context, Intent intent) {
832 // on background handler thread, and verified MANAGE_NETWORK_POLICY
833 // permission above.
834
835 setRestrictBackground(false);
836 }
837 };
838
839 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800840 * Receiver that watches for {@link Notification} control of
841 * {@link NetworkPolicy#lastWarningSnooze}.
842 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700843 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800844 @Override
845 public void onReceive(Context context, Intent intent) {
846 // on background handler thread, and verified MANAGE_NETWORK_POLICY
847 // permission above.
848
849 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
850 performSnooze(template, TYPE_WARNING);
851 }
852 };
853
854 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700855 * Receiver that watches for {@link WifiConfiguration} to be changed.
856 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700857 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700858 @Override
859 public void onReceive(Context context, Intent intent) {
860 // on background handler thread, and verified CONNECTIVITY_INTERNAL
861 // permission above.
862
863 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
864 if (reason == CHANGE_REASON_REMOVED) {
865 final WifiConfiguration config = intent.getParcelableExtra(
866 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700867 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800868 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700869 synchronized (mUidRulesFirstLock) {
870 synchronized (mNetworkPoliciesSecondLock) {
871 if (mNetworkPolicy.containsKey(template)) {
872 mNetworkPolicy.remove(template);
873 writePolicyAL();
874 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700875 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700876 }
877 }
878 }
879 }
880 };
881
882 /**
883 * Receiver that watches {@link WifiInfo} state changes to infer metered
884 * state. Ignores hints when policy is user-defined.
885 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700886 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700887 @Override
888 public void onReceive(Context context, Intent intent) {
889 // on background handler thread, and verified CONNECTIVITY_INTERNAL
890 // permission above.
891
892 // ignore when not connected
893 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
894 if (!netInfo.isConnected()) return;
895
896 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
897 final boolean meteredHint = info.getMeteredHint();
898
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800899 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700900 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700901 NetworkPolicy policy = mNetworkPolicy.get(template);
902 if (policy == null && meteredHint) {
903 // policy doesn't exist, and AP is hinting that it's
904 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800905 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700906 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700907
908 } else if (policy != null && policy.inferred) {
909 // policy exists, and was inferred: update its current
910 // metered state.
911 policy.metered = meteredHint;
912
913 // since this is inferred for each wifi session, just update
914 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700915 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700916 }
917 }
918 }
919 };
920
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800921 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
922 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
923 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
924 metered, true);
925 }
926
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700927 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700928 * Observer that watches for {@link INetworkManagementService} alerts.
929 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private INetworkManagementEventObserver mAlertObserver
931 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700932 @Override
933 public void limitReached(String limitName, String iface) {
934 // only someone like NMS should be calling us
935 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
936
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800937 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
938 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700939 }
940 }
941 };
942
943 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700944 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
945 * to show visible notifications as needed.
946 */
Felipe Lemef0823852016-06-08 13:43:08 -0700947 void updateNotificationsNL() {
948 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700949
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700951 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700953
954 // TODO: when switching to kernel notifications, compute next future
955 // cycle boundary to recompute notifications.
956
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700957 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800958 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700959 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
960 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700961 // ignore policies that aren't relevant to user
962 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700963 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700964
Jeff Sharkey497e4432011-06-14 17:27:29 -0700965 final long start = computeLastCycleBoundary(currentTime, policy);
966 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700967 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700968
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700969 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800970 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700971 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
972 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700973 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700974 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700975 }
976
Jeff Sharkey497e4432011-06-14 17:27:29 -0700977 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700978 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700979
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800980 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700981 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700982 }
983 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700984 }
985
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700986 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700987 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
988 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700989 if (!mActiveNotifs.contains(tag)) {
990 cancelNotification(tag);
991 }
992 }
993 }
994
995 /**
996 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700997 * current device state, such as when
998 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
999 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001000 */
1001 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001002 if (template.isMatchRuleMobile()) {
1003 final TelephonyManager tele = TelephonyManager.from(mContext);
1004 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001005
Jeff Sharkey32566012014-12-02 18:30:14 -08001006 // Mobile template is relevant when any active subscriber matches
1007 final int[] subIds = sub.getActiveSubscriptionIdList();
1008 for (int subId : subIds) {
1009 final String subscriberId = tele.getSubscriberId(subId);
1010 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001011 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001012 if (template.matches(probeIdent)) {
1013 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001014 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001015 }
1016 return false;
1017 } else {
1018 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001020 }
1021
1022 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001023 * Notify that given {@link NetworkTemplate} is over
1024 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1025 */
Felipe Lemef0823852016-06-08 13:43:08 -07001026 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001027 if (!mOverLimitNotified.contains(template)) {
1028 mContext.startActivity(buildNetworkOverLimitIntent(template));
1029 mOverLimitNotified.add(template);
1030 }
1031 }
1032
Felipe Lemef0823852016-06-08 13:43:08 -07001033 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 mOverLimitNotified.remove(template);
1035 }
1036
1037 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 * Build unique tag that identifies an active {@link NetworkPolicy}
1039 * notification of a specific type, like {@link #TYPE_LIMIT}.
1040 */
1041 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001042 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043 }
1044
1045 /**
1046 * Show notification for combined {@link NetworkPolicy} and specific type,
1047 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1048 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001049 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001050 final String tag = buildNotificationTag(policy, type);
1051 final Notification.Builder builder = new Notification.Builder(mContext);
1052 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001053 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001054 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001055 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001056
1057 final Resources res = mContext.getResources();
1058 switch (type) {
1059 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001060 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001061 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001062
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001063 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064 builder.setTicker(title);
1065 builder.setContentTitle(title);
1066 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001067 builder.setDefaults(Notification.DEFAULT_ALL);
1068 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001069
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001070 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1071 builder.setDeleteIntent(PendingIntent.getBroadcast(
1072 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1073
1074 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001075 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001076 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1077
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078 break;
1079 }
1080 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1082
1083 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001084 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001085 switch (policy.template.getMatchRule()) {
1086 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001087 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001089 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001090 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001091 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001093 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001094 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001095 case MATCH_WIFI:
1096 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001097 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001098 break;
1099 default:
1100 title = null;
1101 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 }
1103
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001104 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001105 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001106 builder.setTicker(title);
1107 builder.setContentTitle(title);
1108 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001109
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1111 builder.setContentIntent(PendingIntent.getActivity(
1112 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1113 break;
1114 }
1115 case TYPE_LIMIT_SNOOZED: {
1116 final long overBytes = totalBytes - policy.limitBytes;
1117 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1118 Formatter.formatFileSize(mContext, overBytes));
1119
1120 final CharSequence title;
1121 switch (policy.template.getMatchRule()) {
1122 case MATCH_MOBILE_3G_LOWER:
1123 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1124 break;
1125 case MATCH_MOBILE_4G:
1126 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1127 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001128 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1130 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001131 case MATCH_WIFI:
1132 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1133 break;
1134 default:
1135 title = null;
1136 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 }
1138
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001139 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001140 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001141 builder.setTicker(title);
1142 builder.setContentTitle(title);
1143 builder.setContentText(body);
1144
1145 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001146 builder.setContentIntent(PendingIntent.getActivity(
1147 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 break;
1149 }
1150 }
1151
1152 // TODO: move to NotificationManager once we can mock it
1153 try {
1154 final String packageName = mContext.getPackageName();
1155 final int[] idReceived = new int[1];
1156 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001157 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001158 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001159 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001161 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001162 }
1163 }
1164
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001165 private void cancelNotification(String tag) {
1166 // TODO: move to NotificationManager once we can mock it
1167 try {
1168 final String packageName = mContext.getPackageName();
1169 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001170 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001171 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001172 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001173 }
1174 }
1175
1176 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001177 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001178 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001179 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001180 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 @Override
1182 public void onReceive(Context context, Intent intent) {
1183 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1184 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001185
1186 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001187 synchronized (mNetworkPoliciesSecondLock) {
1188 ensureActiveMobilePolicyNL();
1189 normalizePoliciesNL();
1190 updateNetworkEnabledNL();
1191 updateNetworkRulesNL();
1192 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001193 }
1194 }
1195 };
1196
1197 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 * Proactively control network data connections when they exceed
1199 * {@link NetworkPolicy#limitBytes}.
1200 */
Felipe Lemef0823852016-06-08 13:43:08 -07001201 void updateNetworkEnabledNL() {
1202 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001203
1204 // TODO: reset any policy-disabled networks when any policy is removed
1205 // completely, which is currently rare case.
1206
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001207 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001208 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1209 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001210 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001211 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001212 setNetworkTemplateEnabled(policy.template, true);
1213 continue;
1214 }
1215
1216 final long start = computeLastCycleBoundary(currentTime, policy);
1217 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001219
1220 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001221 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1222 && policy.lastLimitSnooze < start;
1223 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001224
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001225 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001226 }
1227 }
1228
1229 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001230 * Proactively disable networks that match the given
1231 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001232 */
1233 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001234 // TODO: reach into ConnectivityManager to proactively disable bringing
1235 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001236
1237 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1238 // If mobile data usage hits the limit or if the user resumes the data, we need to
1239 // notify telephony.
1240 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1241 final TelephonyManager tm = TelephonyManager.from(mContext);
1242
1243 final int[] subIds = sm.getActiveSubscriptionIdList();
1244 for (int subId : subIds) {
1245 final String subscriberId = tm.getSubscriberId(subId);
1246 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1247 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1248 // Template is matched when subscriber id matches.
1249 if (template.matches(probeIdent)) {
1250 tm.setPolicyDataEnabled(enabled, subId);
1251 }
1252 }
1253 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001254 }
1255
1256 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 * Examine all connected {@link NetworkState}, looking for
1258 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1259 * remaining quota based on usage cycle and historical stats.
1260 */
Felipe Lemef0823852016-06-08 13:43:08 -07001261 void updateNetworkRulesNL() {
1262 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001263
1264 final NetworkState[] states;
1265 try {
1266 states = mConnManager.getAllNetworkState();
1267 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001268 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001269 return;
1270 }
1271
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001272 // First, generate identities of all connected networks so we can
1273 // quickly compare them against all defined policies below.
1274 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001275 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001276 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001277 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001278 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001279
1280 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001281 if (baseIface != null) {
1282 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001283 }
1284
1285 // Stacked interfaces are considered to have same identity as
1286 // their parent network.
1287 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1288 for (LinkProperties stackedLink : stackedLinks) {
1289 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001290 if (stackedIface != null) {
1291 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001292 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001293 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 }
1295 }
1296
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001297 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001298 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001299 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001300 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001301 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001304 for (int j = connIdents.size() - 1; j >= 0; j--) {
1305 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1306 if (policy.template.matches(ident.second)) {
1307 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 }
1309 }
1310
1311 if (ifaceList.size() > 0) {
1312 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001313 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314 }
1315 }
1316
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001317 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001318 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001319
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320 // apply each policy that we found ifaces for; compute remaining data
1321 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001322 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001323 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1324 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1325 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001327 final long start;
1328 final long totalBytes;
1329 if (policy.hasCycle()) {
1330 start = computeLastCycleBoundary(currentTime, policy);
1331 totalBytes = getTotalBytes(policy.template, start, currentTime);
1332 } else {
1333 start = Long.MAX_VALUE;
1334 totalBytes = 0;
1335 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001336
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001337 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001338 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001339 }
1340
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001341 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001342 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001343 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001344 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001345 if (!hasLimit) {
1346 // metered network, but no policy limit; we still need to
1347 // restrict apps, so push really high quota.
1348 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001349 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001350 // snoozing past quota, but we still need to restrict apps,
1351 // so push really high quota.
1352 quotaBytes = Long.MAX_VALUE;
1353 } else {
1354 // remaining "quota" bytes are based on total usage in
1355 // current cycle. kernel doesn't like 0-byte rules, so we
1356 // set 1-byte quota and disable the radio later.
1357 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1358 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001359
1360 if (ifaces.length > 1) {
1361 // TODO: switch to shared quota once NMS supports
1362 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001363 }
1364
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001365 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001366 // long quotaBytes split up into two ints to fit in message
1367 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1368 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1369 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001370 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001371 }
1372 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001373
1374 // keep track of lowest warning or limit of active policies
1375 if (hasWarning && policy.warningBytes < lowestRule) {
1376 lowestRule = policy.warningBytes;
1377 }
1378 if (hasLimit && policy.limitBytes < lowestRule) {
1379 lowestRule = policy.limitBytes;
1380 }
1381 }
1382
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001383 for (int i = connIfaces.size()-1; i >= 0; i--) {
1384 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001385 // long quotaBytes split up into two ints to fit in message
1386 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1387 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1388 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001389 newMeteredIfaces.add(iface);
1390 }
1391
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001392 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001394 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001395 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1396 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001397 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001398 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1399 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001400 }
1401 }
1402 mMeteredIfaces = newMeteredIfaces;
1403
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001404 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001405 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001406 }
1407
1408 /**
1409 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1410 * have at least a default mobile policy defined.
1411 */
Felipe Lemef0823852016-06-08 13:43:08 -07001412 private void ensureActiveMobilePolicyNL() {
1413 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001414 if (mSuppressDefaultPolicy) return;
1415
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001416 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001417 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001418
Jeff Sharkey32566012014-12-02 18:30:14 -08001419 final int[] subIds = sub.getActiveSubscriptionIdList();
1420 for (int subId : subIds) {
1421 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001422 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001423 }
1424 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001425
Felipe Lemef0823852016-06-08 13:43:08 -07001426 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 // Poke around to see if we already have a policy
1428 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001429 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001430 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1431 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1432 if (template.matches(probeIdent)) {
1433 if (LOGD) {
1434 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1435 + NetworkIdentity.scrubSubscriberId(subscriberId));
1436 }
1437 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001438 }
1439 }
1440
Jeff Sharkey32566012014-12-02 18:30:14 -08001441 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1442 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001443
Jeff Sharkey32566012014-12-02 18:30:14 -08001444 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001445 final int dataWarningConfig = mContext.getResources().getInteger(
1446 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1447 final long warningBytes;
1448 if (dataWarningConfig == WARNING_DISABLED) {
1449 warningBytes = WARNING_DISABLED;
1450 } else {
1451 warningBytes = dataWarningConfig * MB_IN_BYTES;
1452 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001453
Jeff Sharkey32566012014-12-02 18:30:14 -08001454 final Time time = new Time();
1455 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001456
Jeff Sharkey32566012014-12-02 18:30:14 -08001457 final int cycleDay = time.monthDay;
1458 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001459
Jeff Sharkey32566012014-12-02 18:30:14 -08001460 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1461 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1462 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001463 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 }
1465
Felipe Lemef0823852016-06-08 13:43:08 -07001466 private void readPolicyAL() {
1467 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001468
1469 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001470 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001471 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001472
1473 FileInputStream fis = null;
1474 try {
1475 fis = mPolicyFile.openRead();
1476 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001477 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478
1479 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001480 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001481 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482 while ((type = in.next()) != END_DOCUMENT) {
1483 final String tag = in.getName();
1484 if (type == START_TAG) {
1485 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001486 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001487 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001488 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1489 mRestrictBackground = readBooleanAttribute(
1490 in, ATTR_RESTRICT_BACKGROUND);
1491 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001492 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001493 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001494 if (mRestrictBackground != oldValue) {
1495 // Some early services may have read the default value,
1496 // so notify them that it's changed
1497 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1498 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1499 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001500
1501 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1502 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1503 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001504 final String networkId;
1505 if (version >= VERSION_ADDED_NETWORK_ID) {
1506 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1507 } else {
1508 networkId = null;
1509 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001511 final String cycleTimezone;
1512 if (version >= VERSION_ADDED_TIMEZONE) {
1513 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1514 } else {
1515 cycleTimezone = Time.TIMEZONE_UTC;
1516 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001517 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1518 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001519 final long lastLimitSnooze;
1520 if (version >= VERSION_SPLIT_SNOOZE) {
1521 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1522 } else if (version >= VERSION_ADDED_SNOOZE) {
1523 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001524 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001525 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001526 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001527 final boolean metered;
1528 if (version >= VERSION_ADDED_METERED) {
1529 metered = readBooleanAttribute(in, ATTR_METERED);
1530 } else {
1531 switch (networkTemplate) {
1532 case MATCH_MOBILE_3G_LOWER:
1533 case MATCH_MOBILE_4G:
1534 case MATCH_MOBILE_ALL:
1535 metered = true;
1536 break;
1537 default:
1538 metered = false;
1539 }
1540 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001541 final long lastWarningSnooze;
1542 if (version >= VERSION_SPLIT_SNOOZE) {
1543 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1544 } else {
1545 lastWarningSnooze = SNOOZE_NEVER;
1546 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001547 final boolean inferred;
1548 if (version >= VERSION_ADDED_INFERRED) {
1549 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1550 } else {
1551 inferred = false;
1552 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001553
Jeff Sharkey32566012014-12-02 18:30:14 -08001554 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1555 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001556 if (template.isPersistable()) {
1557 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1558 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1559 lastLimitSnooze, metered, inferred));
1560 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001562 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563 final int uid = readIntAttribute(in, ATTR_UID);
1564 final int policy = readIntAttribute(in, ATTR_POLICY);
1565
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001566 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001567 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001568 } else {
1569 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1570 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001571 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001572 final int appId = readIntAttribute(in, ATTR_APP_ID);
1573 final int policy = readIntAttribute(in, ATTR_POLICY);
1574
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001575 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001576 // app policy is deprecated so this is only used in pre system user split.
1577 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001578 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001579 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001580 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001581 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001582 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001583 } else if (TAG_WHITELIST.equals(tag)) {
1584 insideWhitelist = true;
1585 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1586 final int uid = readIntAttribute(in, ATTR_UID);
1587 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001588 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1589 final int uid = readIntAttribute(in, ATTR_UID);
1590 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001591 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001592 } else if (type == END_TAG) {
1593 if (TAG_WHITELIST.equals(tag)) {
1594 insideWhitelist = false;
1595 }
1596
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001597 }
1598 }
1599
1600 } catch (FileNotFoundException e) {
1601 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001602 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001603 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001604 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001606 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607 } finally {
1608 IoUtils.closeQuietly(fis);
1609 }
1610 }
1611
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001612 /**
1613 * Upgrade legacy background data flags, notifying listeners of one last
1614 * change to always-true.
1615 */
Felipe Lemef0823852016-06-08 13:43:08 -07001616 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001617 mRestrictBackground = Settings.Secure.getInt(
1618 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1619
1620 // kick off one last broadcast if restricted
1621 if (mRestrictBackground) {
1622 final Intent broadcast = new Intent(
1623 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001624 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001625 }
1626 }
1627
Felipe Lemef0823852016-06-08 13:43:08 -07001628 void writePolicyAL() {
1629 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001630
1631 FileOutputStream fos = null;
1632 try {
1633 fos = mPolicyFile.startWrite();
1634
1635 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001636 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001637 out.startDocument(null, true);
1638
1639 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001640 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001641 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642
1643 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001644 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1645 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001646 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001647 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001648
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001650 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1651 final String subscriberId = template.getSubscriberId();
1652 if (subscriberId != null) {
1653 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001655 final String networkId = template.getNetworkId();
1656 if (networkId != null) {
1657 out.attribute(null, ATTR_NETWORK_ID, networkId);
1658 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001659 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001660 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001661 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1662 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001663 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1664 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001665 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001666 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667 out.endTag(null, TAG_NETWORK_POLICY);
1668 }
1669
1670 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001671 for (int i = 0; i < mUidPolicy.size(); i++) {
1672 final int uid = mUidPolicy.keyAt(i);
1673 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001674
Jeff Sharkey497e4432011-06-14 17:27:29 -07001675 // skip writing empty policies
1676 if (policy == POLICY_NONE) continue;
1677
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001678 out.startTag(null, TAG_UID_POLICY);
1679 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001680 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001681 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001682 }
1683
1684 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001685
1686 // write all whitelists
1687 out.startTag(null, TAG_WHITELIST);
1688
1689 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001690 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001691 for (int i = 0; i < size; i++) {
1692 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1693 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1694 writeIntAttribute(out, ATTR_UID, uid);
1695 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1696 }
1697
Felipe Lemea9505cc2016-02-26 10:28:41 -08001698 // revoked restrict background whitelist
1699 size = mRestrictBackgroundWhitelistRevokedUids.size();
1700 for (int i = 0; i < size; i++) {
1701 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1702 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1703 writeIntAttribute(out, ATTR_UID, uid);
1704 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1705 }
1706
Felipe Lemeb85a6372016-01-14 16:16:16 -08001707 out.endTag(null, TAG_WHITELIST);
1708
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001709 out.endDocument();
1710
1711 mPolicyFile.finishWrite(fos);
1712 } catch (IOException e) {
1713 if (fos != null) {
1714 mPolicyFile.failWrite(fos);
1715 }
1716 }
1717 }
1718
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001719 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001720 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001722
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001723 if (!UserHandle.isApp(uid)) {
1724 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001725 }
Felipe Lemef0823852016-06-08 13:43:08 -07001726 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001727 final long token = Binder.clearCallingIdentity();
1728 try {
1729 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1730 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001731 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001732 }
1733 } finally {
1734 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001735 }
1736 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001737 }
1738
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001739 @Override
1740 public void addUidPolicy(int uid, int policy) {
1741 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001742
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001743 if (!UserHandle.isApp(uid)) {
1744 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1745 }
1746
Felipe Lemef0823852016-06-08 13:43:08 -07001747 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001748 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1749 policy |= oldPolicy;
1750 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001751 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001752 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001753 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001754 }
1755
1756 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001757 public void removeUidPolicy(int uid, int policy) {
1758 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1759
1760 if (!UserHandle.isApp(uid)) {
1761 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1762 }
1763
Felipe Lemef0823852016-06-08 13:43:08 -07001764 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001765 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1766 policy = oldPolicy & ~policy;
1767 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001768 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001769 }
1770 }
1771 }
1772
Felipe Lemef0823852016-06-08 13:43:08 -07001773 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1774 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001775
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001776 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1777 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1778 isBlacklisted ? 1 : 0).sendToTarget();
1779
1780 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001781 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001782 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1783 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001784 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001785 .sendToTarget();
1786 }
1787 }
1788
Felipe Lemef0823852016-06-08 13:43:08 -07001789 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001790 mUidPolicy.put(uid, policy);
1791
1792 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001793 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001794 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001795 synchronized (mNetworkPoliciesSecondLock) {
1796 writePolicyAL();
1797 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001798 }
1799 }
1800
1801 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001802 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001803 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1804
Felipe Lemef0823852016-06-08 13:43:08 -07001805 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001806 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001807 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001808 }
1809
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001810 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001811 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001812 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1813
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001814 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001815 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001816 for (int i = 0; i < mUidPolicy.size(); i++) {
1817 final int uid = mUidPolicy.keyAt(i);
1818 final int uidPolicy = mUidPolicy.valueAt(i);
1819 if (uidPolicy == policy) {
1820 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001821 }
1822 }
1823 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001824 return uids;
1825 }
1826
1827 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001828 * Removes any persistable state associated with given {@link UserHandle}, persisting
1829 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001830 */
Felipe Lemef0823852016-06-08 13:43:08 -07001831 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001832
Felipe Lemef0823852016-06-08 13:43:08 -07001833 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001834 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001835
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001836 // Remove entries from restricted background UID whitelist
1837 int[] wlUids = new int[0];
1838 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1839 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1840 if (UserHandle.getUserId(uid) == userId) {
1841 wlUids = appendInt(wlUids, uid);
1842 }
1843 }
1844
1845 if (wlUids.length > 0) {
1846 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001847 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001848 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001849 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001850 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001851
1852 // Remove entries from revoked default restricted background UID whitelist
1853 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1854 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1855 if (UserHandle.getUserId(uid) == userId) {
1856 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001857 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001858 }
1859 }
1860
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001861 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001862 int[] uids = new int[0];
1863 for (int i = 0; i < mUidPolicy.size(); i++) {
1864 final int uid = mUidPolicy.keyAt(i);
1865 if (UserHandle.getUserId(uid) == userId) {
1866 uids = appendInt(uids, uid);
1867 }
1868 }
1869
1870 if (uids.length > 0) {
1871 for (int uid : uids) {
1872 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001873 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001874 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001875 }
Felipe Lemef0823852016-06-08 13:43:08 -07001876 synchronized (mNetworkPoliciesSecondLock) {
1877 updateRulesForGlobalChangeAL(true);
1878 if (writePolicy && changed) {
1879 writePolicyAL();
1880 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001881 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001882 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001883 }
1884
1885 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001886 public void setConnectivityListener(INetworkPolicyListener listener) {
1887 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1888 if (mConnectivityListener != null) {
1889 throw new IllegalStateException("Connectivity listener already registered");
1890 }
1891 mConnectivityListener = listener;
1892 }
1893
1894 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001895 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001896 // TODO: create permission for observing network policy
1897 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001898 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001899 }
1900
1901 @Override
1902 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001903 // TODO: create permission for observing network policy
1904 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001905 mListeners.unregister(listener);
1906 }
1907
Jeff Sharkey1b861272011-05-22 00:34:52 -07001908 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001909 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001910 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1911
Felipe Leme6a05eee2016-02-19 14:43:51 -08001912 final long token = Binder.clearCallingIdentity();
1913 try {
1914 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001915 synchronized (mUidRulesFirstLock) {
1916 synchronized (mNetworkPoliciesSecondLock) {
1917 normalizePoliciesNL(policies);
1918 updateNetworkEnabledNL();
1919 updateNetworkRulesNL();
1920 updateNotificationsNL();
1921 writePolicyAL();
1922 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001923 }
1924 } finally {
1925 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001926 }
1927 }
1928
Felipe Lemef0823852016-06-08 13:43:08 -07001929 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001930 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001931 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1932 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001933 }
1934
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001935 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001936 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001937 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001938 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001939 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1940 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1941 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001942 } catch (SecurityException e) {
1943 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001944
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001945 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1946 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1947 return new NetworkPolicy[0];
1948 }
Svet Ganov16a16892015-04-16 10:32:04 -07001949 }
1950
Felipe Lemef0823852016-06-08 13:43:08 -07001951 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001952 final int size = mNetworkPolicy.size();
1953 final NetworkPolicy[] policies = new NetworkPolicy[size];
1954 for (int i = 0; i < size; i++) {
1955 policies[i] = mNetworkPolicy.valueAt(i);
1956 }
1957 return policies;
1958 }
1959 }
1960
Felipe Lemef0823852016-06-08 13:43:08 -07001961 private void normalizePoliciesNL() {
1962 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001963 }
1964
Felipe Lemef0823852016-06-08 13:43:08 -07001965 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001966 final TelephonyManager tele = TelephonyManager.from(mContext);
1967 final String[] merged = tele.getMergedSubscriberIds();
1968
1969 mNetworkPolicy.clear();
1970 for (NetworkPolicy policy : policies) {
1971 // When two normalized templates conflict, prefer the most
1972 // restrictive policy
1973 policy.template = NetworkTemplate.normalize(policy.template, merged);
1974 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1975 if (existing == null || existing.compareTo(policy) > 0) {
1976 if (existing != null) {
1977 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1978 }
1979 mNetworkPolicy.put(policy.template, policy);
1980 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001981 }
1982 }
1983
1984 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001985 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001986 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001987
1988 final long token = Binder.clearCallingIdentity();
1989 try {
1990 performSnooze(template, TYPE_LIMIT);
1991 } finally {
1992 Binder.restoreCallingIdentity(token);
1993 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001994 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001995
Dianne Hackborn497175b2014-07-01 12:56:08 -07001996 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001997 maybeRefreshTrustedTime();
1998 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001999 synchronized (mUidRulesFirstLock) {
2000 synchronized (mNetworkPoliciesSecondLock) {
2001 // find and snooze local policy that matches
2002 final NetworkPolicy policy = mNetworkPolicy.get(template);
2003 if (policy == null) {
2004 throw new IllegalArgumentException("unable to find policy for " + template);
2005 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002006
Felipe Lemef0823852016-06-08 13:43:08 -07002007 switch (type) {
2008 case TYPE_WARNING:
2009 policy.lastWarningSnooze = currentTime;
2010 break;
2011 case TYPE_LIMIT:
2012 policy.lastLimitSnooze = currentTime;
2013 break;
2014 default:
2015 throw new IllegalArgumentException("unexpected type");
2016 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002017
Felipe Lemef0823852016-06-08 13:43:08 -07002018 normalizePoliciesNL();
2019 updateNetworkEnabledNL();
2020 updateNetworkRulesNL();
2021 updateNotificationsNL();
2022 writePolicyAL();
2023 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002024 }
2025 }
2026
2027 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002028 public void onTetheringChanged(String iface, boolean tethering) {
2029 // No need to enforce permission because setRestrictBackground() will do it.
2030 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002031 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002032 if (mRestrictBackground && tethering) {
2033 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2034 setRestrictBackground(false);
2035 }
2036 }
2037 }
2038
2039 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002040 public void setRestrictBackground(boolean restrictBackground) {
2041 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002042 final long token = Binder.clearCallingIdentity();
2043 try {
2044 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002045 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002046 if (restrictBackground == mRestrictBackground) {
2047 // Ideally, UI should never allow this scenario...
2048 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2049 return;
2050 }
Felipe Lemef0823852016-06-08 13:43:08 -07002051 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002052 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002053
Felipe Leme6a05eee2016-02-19 14:43:51 -08002054 } finally {
2055 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002056 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002057
2058 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2059 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002060 }
2061
Felipe Lemef0823852016-06-08 13:43:08 -07002062 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Lemea1540892016-06-21 13:08:55 -07002063 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002064 final boolean oldRestrictBackground = mRestrictBackground;
2065 mRestrictBackground = restrictBackground;
2066 // Must whitelist foreground apps before turning data saver mode on.
2067 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2068 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002069 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002070 try {
2071 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2072 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2073 mRestrictBackground = oldRestrictBackground;
2074 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002075 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002076 return;
2077 }
2078 } catch (RemoteException e) {
2079 // ignored; service lives in system_server
2080 }
Felipe Lemef0823852016-06-08 13:43:08 -07002081 synchronized (mNetworkPoliciesSecondLock) {
2082 updateNotificationsNL();
2083 writePolicyAL();
2084 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002085 }
2086
Jeff Sharkey46645002011-07-27 21:11:21 -07002087 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002088 public void addRestrictBackgroundWhitelistedUid(int uid) {
2089 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002090 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002091 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002092 int changed;
2093 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002094 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002095 if (oldStatus) {
2096 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2097 return;
2098 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002099 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002100 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002101 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002102 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2103 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2104 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2105 + " from revoked restrict background whitelist");
2106 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2107 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002108 if (needFirewallRules) {
2109 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002110 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002111 }
2112 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002113 synchronized (mNetworkPoliciesSecondLock) {
2114 writePolicyAL();
2115 }
2116 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002117 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002118 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2119 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002120 }
2121
2122 @Override
2123 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2124 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002125 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002126 synchronized (mUidRulesFirstLock) {
2127 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002128 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002129 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2130 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002131 }
2132
Felipe Leme70c57c22016-03-29 10:45:13 -07002133 /**
2134 * Removes a uid from the restricted background whitelist, returning whether its current
2135 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2136 */
Felipe Lemef0823852016-06-08 13:43:08 -07002137 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002138 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002139 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002140 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002141 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2142 return false;
2143 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002144 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002145 if (oldStatus) {
2146 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2147 mRestrictBackgroundWhitelistUids.delete(uid);
2148 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002149 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2150 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2151 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2152 + " to revoked restrict background whitelist");
2153 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2154 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002155 if (needFirewallRules) {
2156 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002157 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002158 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002159 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002160 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002161 synchronized (mNetworkPoliciesSecondLock) {
2162 writePolicyAL();
2163 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002164 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002165 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2166 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002167 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002168 }
2169
2170 @Override
2171 public int[] getRestrictBackgroundWhitelistedUids() {
2172 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002173 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002174 final int size = mRestrictBackgroundWhitelistUids.size();
2175 final int[] whitelist = new int[size];
2176 for (int i = 0; i < size; i++) {
2177 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2178 }
2179 if (LOGV) {
2180 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2181 + mRestrictBackgroundWhitelistUids);
2182 }
2183 return whitelist;
2184 }
2185 }
2186
2187 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002188 public int getRestrictBackgroundByCaller() {
2189 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2190 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002191
Felipe Lemef0823852016-06-08 13:43:08 -07002192 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002193 // Must clear identity because getUidPolicy() is restricted to system.
2194 final long token = Binder.clearCallingIdentity();
2195 final int policy;
2196 try {
2197 policy = getUidPolicy(uid);
2198 } finally {
2199 Binder.restoreCallingIdentity(token);
2200 }
2201 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2202 // App is blacklisted.
2203 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2204 }
Felipe Leme1b103232016-01-22 09:44:57 -08002205 if (!mRestrictBackground) {
2206 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2207 }
2208 return mRestrictBackgroundWhitelistUids.get(uid)
2209 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2210 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2211 }
2212 }
2213
2214 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002215 public boolean getRestrictBackground() {
2216 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2217
Felipe Lemef0823852016-06-08 13:43:08 -07002218 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002219 return mRestrictBackground;
2220 }
2221 }
2222
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002223 @Override
2224 public void setDeviceIdleMode(boolean enabled) {
2225 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002226 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2227 try {
2228 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002229 if (mDeviceIdleMode == enabled) {
2230 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002231 }
Felipe Lemeea014392016-09-06 13:59:54 -07002232 mDeviceIdleMode = enabled;
2233 if (mSystemReady) {
2234 // Device idle change means we need to rebuild rules for all
2235 // known apps, so do a global refresh.
2236 updateRulesForRestrictPowerUL();
2237 }
2238 }
2239 if (enabled) {
2240 EventLogTags.writeDeviceIdleOnPhase("net");
2241 } else {
2242 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002243 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002244 } finally {
2245 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002246 }
2247 }
2248
Felipe Lemef0823852016-06-08 13:43:08 -07002249 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002250 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2251 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002252 if (policy.template.matches(ident)) {
2253 return policy;
2254 }
2255 }
2256 return null;
2257 }
2258
2259 @Override
2260 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2261 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2262
2263 // only returns usage summary, so we don't require caller to have
2264 // READ_NETWORK_USAGE_HISTORY.
2265 final long token = Binder.clearCallingIdentity();
2266 try {
2267 return getNetworkQuotaInfoUnchecked(state);
2268 } finally {
2269 Binder.restoreCallingIdentity(token);
2270 }
2271 }
2272
2273 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2274 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2275
2276 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002277 synchronized (mNetworkPoliciesSecondLock) {
2278 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002279 }
2280
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002281 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002282 // missing policy means we can't derive useful quota info
2283 return null;
2284 }
2285
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002286 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002287
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002288 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002289 final long start = computeLastCycleBoundary(currentTime, policy);
2290 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002291 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002292
2293 // report soft and hard limits under policy
2294 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2295 : NetworkQuotaInfo.NO_LIMIT;
2296 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2297 : NetworkQuotaInfo.NO_LIMIT;
2298
2299 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2300 }
2301
Jeff Sharkey46645002011-07-27 21:11:21 -07002302 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002303 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002304 if (state.networkInfo == null) {
2305 return false;
2306 }
2307
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002308 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2309
2310 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002311 synchronized (mNetworkPoliciesSecondLock) {
2312 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002313 }
2314
2315 if (policy != null) {
2316 return policy.metered;
2317 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002318 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002319 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002320 return true;
2321 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002322 return false;
2323 }
2324 }
2325
2326 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002327 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002328 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002329
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002330 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2331
Dianne Hackborn497175b2014-07-01 12:56:08 -07002332 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002333 for (String arg : args) {
2334 argSet.add(arg);
2335 }
2336
Felipe Lemef0823852016-06-08 13:43:08 -07002337 synchronized (mUidRulesFirstLock) {
2338 synchronized (mNetworkPoliciesSecondLock) {
2339 if (argSet.contains("--unsnooze")) {
2340 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2341 mNetworkPolicy.valueAt(i).clearSnooze();
2342 }
2343
2344 normalizePoliciesNL();
2345 updateNetworkEnabledNL();
2346 updateNetworkRulesNL();
2347 updateNotificationsNL();
2348 writePolicyAL();
2349
2350 fout.println("Cleared snooze timestamps");
2351 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002352 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002353
Felipe Lemef0823852016-06-08 13:43:08 -07002354 fout.print("System ready: "); fout.println(mSystemReady);
2355 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2356 fout.print("Restrict power: "); fout.println(mRestrictPower);
2357 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2358 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002359 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002360 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2361 fout.println(mNetworkPolicy.valueAt(i).toString());
2362 }
2363 fout.decreaseIndent();
2364
2365 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2366
2367 fout.println("Policy for UIDs:");
2368 fout.increaseIndent();
2369 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002370 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002371 final int uid = mUidPolicy.keyAt(i);
2372 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002373 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002374 fout.print(uid);
2375 fout.print(" policy=");
2376 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2377 fout.println();
2378 }
2379 fout.decreaseIndent();
2380
2381 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2382 if (size > 0) {
2383 fout.println("Power save whitelist (except idle) app ids:");
2384 fout.increaseIndent();
2385 for (int i = 0; i < size; i++) {
2386 fout.print("UID=");
2387 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2388 fout.print(": ");
2389 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2390 fout.println();
2391 }
2392 fout.decreaseIndent();
2393 }
2394
2395 size = mPowerSaveWhitelistAppIds.size();
2396 if (size > 0) {
2397 fout.println("Power save whitelist app ids:");
2398 fout.increaseIndent();
2399 for (int i = 0; i < size; i++) {
2400 fout.print("UID=");
2401 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2402 fout.print(": ");
2403 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2404 fout.println();
2405 }
2406 fout.decreaseIndent();
2407 }
2408
2409 size = mRestrictBackgroundWhitelistUids.size();
2410 if (size > 0) {
2411 fout.println("Restrict background whitelist uids:");
2412 fout.increaseIndent();
2413 for (int i = 0; i < size; i++) {
2414 fout.print("UID=");
2415 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2416 fout.println();
2417 }
2418 fout.decreaseIndent();
2419 }
2420
2421 size = mDefaultRestrictBackgroundWhitelistUids.size();
2422 if (size > 0) {
2423 fout.println("Default restrict background whitelist uids:");
2424 fout.increaseIndent();
2425 for (int i = 0; i < size; i++) {
2426 fout.print("UID=");
2427 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2428 fout.println();
2429 }
2430 fout.decreaseIndent();
2431 }
2432
2433 size = mRestrictBackgroundWhitelistRevokedUids.size();
2434 if (size > 0) {
2435 fout.println("Default restrict background whitelist uids revoked by users:");
2436 fout.increaseIndent();
2437 for (int i = 0; i < size; i++) {
2438 fout.print("UID=");
2439 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2440 fout.println();
2441 }
2442 fout.decreaseIndent();
2443 }
2444
2445 final SparseBooleanArray knownUids = new SparseBooleanArray();
2446 collectKeys(mUidState, knownUids);
2447 collectKeys(mUidRules, knownUids);
2448
2449 fout.println("Status for all known UIDs:");
2450 fout.increaseIndent();
2451 size = knownUids.size();
2452 for (int i = 0; i < size; i++) {
2453 final int uid = knownUids.keyAt(i);
2454 fout.print("UID=");
2455 fout.print(uid);
2456
2457 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2458 fout.print(" state=");
2459 fout.print(state);
2460 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2461 fout.print(" (fg)");
2462 } else {
2463 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2464 ? " (fg svc)" : " (bg)");
2465 }
2466
2467 final int uidRules = mUidRules.get(uid, RULE_NONE);
2468 fout.print(" rules=");
2469 fout.print(uidRulesToString(uidRules));
2470 fout.println();
2471 }
2472 fout.decreaseIndent();
2473
2474 fout.println("Status for just UIDs with rules:");
2475 fout.increaseIndent();
2476 size = mUidRules.size();
2477 for (int i = 0; i < size; i++) {
2478 final int uid = mUidRules.keyAt(i);
2479 fout.print("UID=");
2480 fout.print(uid);
2481 final int uidRules = mUidRules.get(uid, RULE_NONE);
2482 fout.print(" rules=");
2483 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002484 fout.println();
2485 }
2486 fout.decreaseIndent();
2487 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002488 }
2489 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002490
2491 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002492 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2493 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002494 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002495 this, in, out, err, args, resultReceiver);
2496 }
2497
2498 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002499 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002500 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2501
Felipe Lemef0823852016-06-08 13:43:08 -07002502 synchronized (mUidRulesFirstLock) {
2503 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002504 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002505 }
2506
Felipe Lemef0823852016-06-08 13:43:08 -07002507 private boolean isUidForegroundUL(int uid) {
2508 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002509 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2510 }
2511
Felipe Lemef0823852016-06-08 13:43:08 -07002512 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002513 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002514 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002515 }
2516
Felipe Lemef0823852016-06-08 13:43:08 -07002517 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002518 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2519 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2520 }
2521
Felipe Lemef0823852016-06-08 13:43:08 -07002522 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002523 // only really in foreground when screen is also on
Felipe Lemef8dd7b42016-08-10 13:00:32 -07002524 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002525 }
2526
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002527 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002528 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002529 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2530 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002531 */
Felipe Lemef0823852016-06-08 13:43:08 -07002532 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002533 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2534 try {
2535 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2536 if (oldUidState != uidState) {
2537 // state changed, push updated rules
2538 mUidState.put(uid, uidState);
2539 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2540 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2541 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2542 if (isUidIdle(uid)) {
2543 updateRuleForAppIdleUL(uid);
2544 }
2545 if (mDeviceIdleMode) {
2546 updateRuleForDeviceIdleUL(uid);
2547 }
2548 if (mRestrictPower) {
2549 updateRuleForRestrictPowerUL(uid);
2550 }
2551 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002552 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002553 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002554 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002555 } finally {
2556 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002557 }
2558 }
2559
Felipe Lemef0823852016-06-08 13:43:08 -07002560 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002561 final int index = mUidState.indexOfKey(uid);
2562 if (index >= 0) {
2563 final int oldUidState = mUidState.valueAt(index);
2564 mUidState.removeAt(index);
2565 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002566 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002567 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002568 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002569 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002570 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002571 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002572 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002573 }
Felipe Lemef0823852016-06-08 13:43:08 -07002574 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002575 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002576 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002577 }
2578 }
2579
Felipe Lemef28983d2016-03-25 12:18:23 -07002580 // adjust stats accounting based on foreground status
2581 private void updateNetworkStats(int uid, boolean uidForeground) {
2582 try {
2583 mNetworkStats.setUidForeground(uid, uidForeground);
2584 } catch (RemoteException e) {
2585 // ignored; service lives in system_server
2586 }
2587 }
2588
Felipe Lemef0823852016-06-08 13:43:08 -07002589 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002590 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002591 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002592 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002593 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002594 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002595 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002596 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002597 }
2598 }
2599
Felipe Leme011b98f2016-02-10 17:28:31 -08002600 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002601 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2602 }
2603
Felipe Lemef0823852016-06-08 13:43:08 -07002604 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002605 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2606 }
2607
Felipe Lemef0823852016-06-08 13:43:08 -07002608 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002609 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2610 try {
2611 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2612 mUidFirewallPowerSaveRules);
2613 } finally {
2614 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2615 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002616 }
2617
Felipe Lemef0823852016-06-08 13:43:08 -07002618 void updateRuleForRestrictPowerUL(int uid) {
2619 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002620 }
2621
Felipe Lemef0823852016-06-08 13:43:08 -07002622 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002623 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2624 try {
2625 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2626 mUidFirewallDozableRules);
2627 } finally {
2628 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2629 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002630 }
2631
Felipe Lemef0823852016-06-08 13:43:08 -07002632 void updateRuleForDeviceIdleUL(int uid) {
2633 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002634 }
2635
Felipe Lemef28983d2016-03-25 12:18:23 -07002636 // NOTE: since both fw_dozable and fw_powersave uses the same map
2637 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002638 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002639 SparseIntArray rules) {
2640 if (enabled) {
2641 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002642 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002643 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002644 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002645 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002646 for (int ui = users.size() - 1; ui >= 0; ui--) {
2647 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002648 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002649 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2650 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2651 int uid = UserHandle.getUid(user.id, appId);
2652 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2653 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002654 }
2655 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2656 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2657 int uid = UserHandle.getUid(user.id, appId);
2658 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2659 }
2660 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002661 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002662 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002663 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2664 }
2665 }
Felipe Leme84d39732016-09-08 13:26:55 -07002666 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2667 } else {
2668 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002669 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002670 }
2671
Felipe Lemef0823852016-06-08 13:43:08 -07002672 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002673 final int appId = UserHandle.getAppId(uid);
2674 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2675 }
2676
Felipe Lemef28983d2016-03-25 12:18:23 -07002677 // NOTE: since both fw_dozable and fw_powersave uses the same map
2678 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002679 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002680 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002681 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002682 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2683 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002684 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002685 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002686 }
2687 }
2688 }
2689
Felipe Lemef0823852016-06-08 13:43:08 -07002690 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002691 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2692 try {
2693 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2694 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002695
Felipe Leme873a83a2016-09-07 11:34:10 -07002696 // Fully update the app idle firewall chain.
2697 final List<UserInfo> users = mUserManager.getUsers();
2698 for (int ui = users.size() - 1; ui >= 0; ui--) {
2699 UserInfo user = users.get(ui);
2700 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2701 for (int uid : idleUids) {
2702 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2703 // quick check: if this uid doesn't have INTERNET permission, it
2704 // doesn't have network access anyway, so it is a waste to mess
2705 // with it here.
2706 if (hasInternetPermissions(uid)) {
2707 uidRules.put(uid, FIREWALL_RULE_DENY);
2708 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002709 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002710 }
2711 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002712
Felipe Leme84d39732016-09-08 13:26:55 -07002713 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002714 } finally {
2715 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2716 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002717 }
2718
Felipe Lemef0823852016-06-08 13:43:08 -07002719 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002720 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002721
2722 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002723 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002724 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002725 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2726 } else {
2727 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2728 }
2729 }
2730
Felipe Lemef0823852016-06-08 13:43:08 -07002731 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002732 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002733 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002734 }
2735
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002736 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002737 * Update rules that might be changed by {@link #mRestrictBackground},
2738 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002739 */
Felipe Lemef0823852016-06-08 13:43:08 -07002740 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002741 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2742 try {
Felipe Leme09700462016-09-08 09:33:48 -07002743 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002744 updateRulesForRestrictPowerUL();
2745 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002746
Felipe Leme873a83a2016-09-07 11:34:10 -07002747 // If the set of restricted networks may have changed, re-evaluate those.
2748 if (restrictedNetworksChanged) {
2749 normalizePoliciesNL();
2750 updateNetworkRulesNL();
2751 }
2752 } finally {
2753 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002754 }
2755 }
2756
Felipe Leme09700462016-09-08 09:33:48 -07002757 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002758 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002759 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2760 try {
2761 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002762 updateRulesForPowerSaveUL();
2763 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2764 } finally {
2765 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2766 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002767 }
2768
Felipe Lemef0823852016-06-08 13:43:08 -07002769 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002770 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2771 try {
2772 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2773 } finally {
2774 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2775 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002776 }
2777
2778 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2779 private static final int TYPE_RESTRICT_POWER = 2;
2780 @Retention(RetentionPolicy.SOURCE)
2781 @IntDef(flag = false, value = {
2782 TYPE_RESTRICT_BACKGROUND,
2783 TYPE_RESTRICT_POWER,
2784 })
2785 public @interface RestrictType {
2786 }
2787
2788 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002789 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002790 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2791 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2792 }
2793 try {
2794 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002795
Felipe Leme873a83a2016-09-07 11:34:10 -07002796 // update rules for all installed applications
2797 final List<UserInfo> users = mUserManager.getUsers();
2798 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2799 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2800 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2801 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002802
Felipe Leme873a83a2016-09-07 11:34:10 -07002803 final int usersSize = users.size();
2804 final int appsSize = apps.size();
2805 for (int i = 0; i < usersSize; i++) {
2806 final UserInfo user = users.get(i);
2807 for (int j = 0; j < appsSize; j++) {
2808 final ApplicationInfo app = apps.get(j);
2809 final int uid = UserHandle.getUid(user.id, app.uid);
2810 switch (type) {
2811 case TYPE_RESTRICT_BACKGROUND:
2812 updateRulesForDataUsageRestrictionsUL(uid);
2813 break;
2814 case TYPE_RESTRICT_POWER:
2815 updateRulesForPowerRestrictionsUL(uid);
2816 break;
2817 default:
2818 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2819 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002820 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002821 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002822 } finally {
2823 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2824 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2825 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002826 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002827 }
2828
Felipe Lemef0823852016-06-08 13:43:08 -07002829 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002830 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002831 for (int i = 0; i < users.size(); i++) {
2832 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002833 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002834 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002835 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002836 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002837 updateRuleForAppIdleUL(uid);
2838 updateRuleForDeviceIdleUL(uid);
2839 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002840 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002841 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002842 }
2843 }
2844 }
2845
Felipe Leme70c57c22016-03-29 10:45:13 -07002846 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2847 // methods below could be merged into a isUidValidForRules() method.
2848 private boolean isUidValidForBlacklistRules(int uid) {
2849 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002850 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002851 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002852 return true;
2853 }
2854
2855 return false;
2856 }
2857
Felipe Leme70c57c22016-03-29 10:45:13 -07002858 private boolean isUidValidForWhitelistRules(int uid) {
2859 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2860 }
2861
Amith Yamasani15e472352015-04-24 19:06:07 -07002862 private boolean isUidIdle(int uid) {
2863 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2864 final int userId = UserHandle.getUserId(uid);
2865
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002866 if (!ArrayUtils.isEmpty(packages)) {
2867 for (String packageName : packages) {
2868 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2869 return false;
2870 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002871 }
2872 }
2873 return true;
2874 }
2875
2876 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002877 * Checks if an uid has INTERNET permissions.
2878 * <p>
2879 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002880 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002881 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002882 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002883 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002884 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002885 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002886 }
2887 } catch (RemoteException e) {
2888 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002889 return true;
2890 }
2891
2892 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002893 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002894 *
Felipe Leme781ba142016-05-09 16:24:48 -07002895 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002896 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002897 * <li>Doze mode
2898 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002899 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002900 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002901 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002902 *
2903 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002904 */
Felipe Lemef0823852016-06-08 13:43:08 -07002905 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002906 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002907 updateRuleForDeviceIdleUL(uid);
2908 updateRuleForAppIdleUL(uid);
2909 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002910
2911 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002912 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002913
2914 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002915 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002916 }
2917
Felipe Leme70c57c22016-03-29 10:45:13 -07002918 /**
2919 * Applies network rules to bandwidth controllers based on process state and user-defined
2920 * restrictions (blacklist / whitelist).
2921 *
2922 * <p>
2923 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2924 * networks:
2925 * <ul>
2926 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2927 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2928 * also blacklisted.
2929 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2930 * no UIDs other those whitelisted will have access.
2931 * <ul>
2932 *
2933 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2934 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2935 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2936 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002937 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002938 * {@link INetworkManagementService}, but this method should also be called in events (like
2939 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2940 * following rules should also be applied:
2941 *
2942 * <ul>
2943 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2944 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2945 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2946 * {@code bw_penalty_box}.
2947 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2948 * </ul>
2949 *
2950 * <p>For optimization, the rules are only applied on user apps that have internet access
2951 * permission, since there is no need to change the {@code iptables} rule if the app does not
2952 * have permission to use the internet.
2953 *
2954 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002955 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002956 */
Felipe Lemef0823852016-06-08 13:43:08 -07002957 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2958 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002959 }
2960
2961 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002962 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002963 * app is removed - it ignores the UID validity check.
2964 */
Felipe Lemef0823852016-06-08 13:43:08 -07002965 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002966 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2967 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2968 return;
2969 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002970
Dianne Hackborn497175b2014-07-01 12:56:08 -07002971 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002972 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002973 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002974
Felipe Leme781ba142016-05-09 16:24:48 -07002975 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2976 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2977 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2978 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002979
Felipe Leme70c57c22016-03-29 10:45:13 -07002980 // First step: define the new rule based on user restrictions and foreground state.
2981 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002982 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2983 newRule = RULE_TEMPORARY_ALLOW_METERED;
2984 } else if (isWhitelisted) {
2985 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002986 }
2987 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002988 if (isBlacklisted) {
2989 newRule = RULE_REJECT_METERED;
2990 } else if (mRestrictBackground && isWhitelisted) {
2991 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002992 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002993 }
Felipe Leme781ba142016-05-09 16:24:48 -07002994 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002995
Felipe Lemef28983d2016-03-25 12:18:23 -07002996 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002997 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002998 + ": isForeground=" +isForeground
2999 + ", isBlacklisted=" + isBlacklisted
3000 + ", isWhitelisted=" + isWhitelisted
3001 + ", oldRule=" + uidRulesToString(oldRule)
3002 + ", newRule=" + uidRulesToString(newRule)
3003 + ", newUidRules=" + uidRulesToString(newUidRules)
3004 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003005 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003006
Felipe Leme46c4fc32016-05-04 09:21:43 -07003007 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003008 mUidRules.delete(uid);
3009 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003010 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003011 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003012
Felipe Leme70c57c22016-03-29 10:45:13 -07003013 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003014 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07003015 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003016 // Temporarily whitelist foreground app, removing from blacklist if necessary
3017 // (since bw_penalty_box prevails over bw_happy_box).
3018
3019 setMeteredNetworkWhitelist(uid, true);
3020 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3021 // but ideally it should be just:
3022 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003023 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003024 setMeteredNetworkBlacklist(uid, false);
3025 }
Felipe Leme781ba142016-05-09 16:24:48 -07003026 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003027 // Remove temporary whitelist from app that is not on foreground anymore.
3028
3029 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3030 // but ideally they should be just:
3031 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3032 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003033 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003034 setMeteredNetworkWhitelist(uid, false);
3035 }
Felipe Leme781ba142016-05-09 16:24:48 -07003036 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003037 setMeteredNetworkBlacklist(uid, true);
3038 }
Felipe Leme781ba142016-05-09 16:24:48 -07003039 } else if ((newRule & RULE_REJECT_METERED) != 0
3040 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003041 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003042 setMeteredNetworkBlacklist(uid, isBlacklisted);
3043 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003044 // Since blacklist prevails over whitelist, we need to handle the special case
3045 // where app is whitelisted and blacklisted at the same time (although such
3046 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003047 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003048 }
Felipe Leme781ba142016-05-09 16:24:48 -07003049 } else if ((newRule & RULE_ALLOW_METERED) != 0
3050 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003051 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003052 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003053 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003054 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003055 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3056 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003057 + ", whitelisted=" + isWhitelisted
3058 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003059 + ", newRule=" + uidRulesToString(newUidRules)
3060 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003061 }
Felipe Leme781ba142016-05-09 16:24:48 -07003062
3063 // Dispatch changed rule to existing listeners.
3064 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3065 }
3066 }
3067
3068 /**
3069 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3070 * listeners in case of change.
3071 * <p>
3072 * There are 3 power-related rules that affects whether an app has background access on
3073 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3074 * restriction, it's added to the equivalent firewall chain:
3075 * <ul>
3076 * <li>App is idle: {@code fw_standby} firewall chain.
3077 * <li>Device is idle: {@code fw_dozable} firewall chain.
3078 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3079 * </ul>
3080 * <p>
3081 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3082 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3083 * <p>
3084 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3085 */
Felipe Lemef0823852016-06-08 13:43:08 -07003086 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003087 if (!isUidValidForBlacklistRules(uid)) {
3088 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3089 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003090 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003091
Felipe Leme781ba142016-05-09 16:24:48 -07003092 final boolean isIdle = isUidIdle(uid);
3093 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Leme781ba142016-05-09 16:24:48 -07003094 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003095 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003096
Felipe Lemef0823852016-06-08 13:43:08 -07003097 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003098 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3099 int newRule = RULE_NONE;
3100
3101 // First step: define the new rule based on user restrictions and foreground state.
3102
3103 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3104 // by considering the foreground and non-foreground states.
3105 if (isForeground) {
3106 if (restrictMode) {
3107 newRule = RULE_ALLOW_ALL;
3108 }
3109 } else if (restrictMode) {
3110 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3111 }
3112
3113 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3114
3115 if (LOGV) {
Felipe Lemef8dd7b42016-08-10 13:00:32 -07003116 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003117 + ", isIdle: " + isIdle
3118 + ", mRestrictPower: " + mRestrictPower
3119 + ", mDeviceIdleMode: " + mDeviceIdleMode
3120 + ", isForeground=" + isForeground
3121 + ", isWhitelisted=" + isWhitelisted
3122 + ", oldRule=" + uidRulesToString(oldRule)
3123 + ", newRule=" + uidRulesToString(newRule)
3124 + ", newUidRules=" + uidRulesToString(newUidRules)
3125 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3126 }
3127
3128 if (newUidRules == RULE_NONE) {
3129 mUidRules.delete(uid);
3130 } else {
3131 mUidRules.put(uid, newUidRules);
3132 }
3133
3134 // Second step: notify listeners if state changed.
3135 if (newRule != oldRule) {
3136 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003137 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003138 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003139 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3140 } else {
3141 // All scenarios should have been covered above
3142 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3143 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003144 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003145 + ", newRule=" + uidRulesToString(newUidRules)
3146 + ", oldRule=" + uidRulesToString(oldUidRules));
3147 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003148 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003149 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003150 }
3151
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003152 private class AppIdleStateChangeListener
3153 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3154
3155 @Override
3156 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3157 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003158 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3159 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003160 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003161 synchronized (mUidRulesFirstLock) {
3162 updateRuleForAppIdleUL(uid);
3163 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003164 }
3165 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003166 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003167 }
3168
3169 @Override
3170 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003171 synchronized (mUidRulesFirstLock) {
3172 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003173 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003174 }
3175 }
3176
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003177 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3178 if (listener != null) {
3179 try {
3180 listener.onUidRulesChanged(uid, uidRules);
3181 } catch (RemoteException ignored) {
3182 }
3183 }
3184 }
3185
3186 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3187 String[] meteredIfaces) {
3188 if (listener != null) {
3189 try {
3190 listener.onMeteredIfacesChanged(meteredIfaces);
3191 } catch (RemoteException ignored) {
3192 }
3193 }
3194 }
3195
3196 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3197 boolean restrictBackground) {
3198 if (listener != null) {
3199 try {
3200 listener.onRestrictBackgroundChanged(restrictBackground);
3201 } catch (RemoteException ignored) {
3202 }
3203 }
3204 }
3205
3206 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3207 int uid, boolean whitelisted) {
3208 if (listener != null) {
3209 try {
3210 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3211 } catch (RemoteException ignored) {
3212 }
3213 }
3214 }
3215
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003216 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3217 int uid, boolean blacklisted) {
3218 if (listener != null) {
3219 try {
3220 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3221 } catch (RemoteException ignored) {
3222 }
3223 }
3224 }
3225
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003226 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003227 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003228 public boolean handleMessage(Message msg) {
3229 switch (msg.what) {
3230 case MSG_RULES_CHANGED: {
3231 final int uid = msg.arg1;
3232 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003233 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003234 final int length = mListeners.beginBroadcast();
3235 for (int i = 0; i < length; i++) {
3236 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003237 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003238 }
3239 mListeners.finishBroadcast();
3240 return true;
3241 }
3242 case MSG_METERED_IFACES_CHANGED: {
3243 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003244 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003245 final int length = mListeners.beginBroadcast();
3246 for (int i = 0; i < length; i++) {
3247 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003248 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003249 }
3250 mListeners.finishBroadcast();
3251 return true;
3252 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003253 case MSG_LIMIT_REACHED: {
3254 final String iface = (String) msg.obj;
3255
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003256 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003257 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003258 if (mMeteredIfaces.contains(iface)) {
3259 try {
3260 // force stats update to make sure we have
3261 // numbers that caused alert to trigger.
3262 mNetworkStats.forceUpdate();
3263 } catch (RemoteException e) {
3264 // ignored; service lives in system_server
3265 }
3266
Felipe Lemef0823852016-06-08 13:43:08 -07003267 updateNetworkEnabledNL();
3268 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003269 }
3270 }
3271 return true;
3272 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003273 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3274 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003275 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003276 final int length = mListeners.beginBroadcast();
3277 for (int i = 0; i < length; i++) {
3278 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003279 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003280 }
3281 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003282 final Intent intent =
3283 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3284 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3285 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3286 return true;
3287 }
3288 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003289 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3290 // - when an app is whitelisted
3291 // - when an app is blacklisted
3292 //
3293 // Whether the internal listeners (INetworkPolicyListener implementations) or
3294 // app broadcast receivers are notified depend on the following rules:
3295 //
3296 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3297 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3298 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003299 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003300 final boolean changed = msg.arg2 == 1;
3301 final Boolean whitelisted = (Boolean) msg.obj;
3302
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003303 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003304 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003305 final boolean whitelistedBool = whitelisted.booleanValue();
3306 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3307 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003308 final int length = mListeners.beginBroadcast();
3309 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003310 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003311 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3312 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003313 }
3314 mListeners.finishBroadcast();
3315 }
Felipe Leme9778f762016-01-27 14:46:39 -08003316 final PackageManager pm = mContext.getPackageManager();
3317 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003318 if (changed && packages != null) {
3319 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003320 final int userId = UserHandle.getUserId(uid);
3321 for (String packageName : packages) {
3322 final Intent intent = new Intent(
3323 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3324 intent.setPackage(packageName);
3325 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3326 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3327 }
Felipe Leme9778f762016-01-27 14:46:39 -08003328 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003329 return true;
3330 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003331 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3332 final int uid = msg.arg1;
3333 final boolean blacklisted = msg.arg2 == 1;
3334
3335 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3336 blacklisted);
3337 final int length = mListeners.beginBroadcast();
3338 for (int i = 0; i < length; i++) {
3339 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3340 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3341 blacklisted);
3342 }
3343 mListeners.finishBroadcast();
3344 return true;
3345 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003346 case MSG_ADVISE_PERSIST_THRESHOLD: {
3347 final long lowestRule = (Long) msg.obj;
3348 try {
3349 // make sure stats are recorded frequently enough; we aim
3350 // for 2MB threshold for 2GB/month rules.
3351 final long persistThreshold = lowestRule / 1000;
3352 mNetworkStats.advisePersistThreshold(persistThreshold);
3353 } catch (RemoteException e) {
3354 // ignored; service lives in system_server
3355 }
3356 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003357 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003358 case MSG_UPDATE_INTERFACE_QUOTA: {
3359 removeInterfaceQuota((String) msg.obj);
3360 // int params need to be stitched back into a long
3361 setInterfaceQuota((String) msg.obj,
3362 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3363 return true;
3364 }
3365 case MSG_REMOVE_INTERFACE_QUOTA: {
3366 removeInterfaceQuota((String) msg.obj);
3367 return true;
3368 }
Felipe Leme84d39732016-09-08 13:26:55 -07003369 case MSG_SET_FIREWALL_RULES: {
3370 final int chain = msg.arg1;
3371 final int toggle = msg.arg2;
3372 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3373 if (uidRules != null) {
3374 setUidFirewallRules(chain, uidRules);
3375 }
3376 if (toggle != CHAIN_TOGGLE_NONE) {
3377 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3378 }
3379 return true;
3380 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003381 default: {
3382 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003383 }
3384 }
3385 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003386 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003387
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003388 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003389 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003390 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003391 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003392 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003393 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003394 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003395 }
3396 }
3397
3398 private void removeInterfaceQuota(String iface) {
3399 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003400 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003401 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003402 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003403 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003404 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003405 }
3406 }
3407
Felipe Leme70c57c22016-03-29 10:45:13 -07003408 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3409 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003410 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003411 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003412 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003413 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3414 } catch (RemoteException e) {
3415 // ignored; service lives in system_server
3416 }
3417 }
3418
3419 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3420 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3421 try {
3422 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3423 } catch (IllegalStateException e) {
3424 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003425 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003426 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003427 }
3428 }
3429
Felipe Leme84d39732016-09-08 13:26:55 -07003430 private static final int CHAIN_TOGGLE_NONE = 0;
3431 private static final int CHAIN_TOGGLE_ENABLE = 1;
3432 private static final int CHAIN_TOGGLE_DISABLE = 2;
3433 @Retention(RetentionPolicy.SOURCE)
3434 @IntDef(flag = false, value = {
3435 CHAIN_TOGGLE_NONE,
3436 CHAIN_TOGGLE_ENABLE,
3437 CHAIN_TOGGLE_DISABLE
3438 })
3439 public @interface ChainToggleType {
3440 }
3441
3442 /**
3443 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3444 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3445 *
3446 * @param chain firewall chain.
3447 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3448 * @param toggle whether the chain should be enabled, disabled, or not changed.
3449 */
3450 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3451 @ChainToggleType int toggle) {
3452 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3453 }
3454
Amith Yamasani15e472352015-04-24 19:06:07 -07003455 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003456 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3457 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3458 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003459 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003460 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003461 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003462 int size = uidRules.size();
3463 int[] uids = new int[size];
3464 int[] rules = new int[size];
3465 for(int index = size - 1; index >= 0; --index) {
3466 uids[index] = uidRules.keyAt(index);
3467 rules[index] = uidRules.valueAt(index);
3468 }
3469 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003470 } catch (IllegalStateException e) {
3471 Log.wtf(TAG, "problem setting firewall uid rules", e);
3472 } catch (RemoteException e) {
3473 // ignored; service lives in system_server
3474 }
3475 }
3476
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003477 /**
3478 * Add or remove a uid to the firewall blacklist for all network ifaces.
3479 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003480 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003481 if (chain == FIREWALL_CHAIN_DOZABLE) {
3482 mUidFirewallDozableRules.put(uid, rule);
3483 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3484 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003485 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3486 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003487 }
3488
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003489 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003490 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003491 } catch (IllegalStateException e) {
3492 Log.wtf(TAG, "problem setting firewall uid rules", e);
3493 } catch (RemoteException e) {
3494 // ignored; service lives in system_server
3495 }
3496 }
3497
3498 /**
3499 * Add or remove a uid to the firewall blacklist for all network ifaces.
3500 */
Felipe Lemef0823852016-06-08 13:43:08 -07003501 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003502 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3503 mFirewallChainStates.get(chain) == enable) {
3504 // All is the same, nothing to do.
3505 return;
3506 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003507 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003508 try {
3509 mNetworkManager.setFirewallChainEnabled(chain, enable);
3510 } catch (IllegalStateException e) {
3511 Log.wtf(TAG, "problem enable firewall chain", e);
3512 } catch (RemoteException e) {
3513 // ignored; service lives in system_server
3514 }
3515 }
3516
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003517 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3518 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003519 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003520 } catch (RuntimeException e) {
3521 Slog.w(TAG, "problem reading network stats: " + e);
3522 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003523 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003524 // ignored; service lives in system_server
3525 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003526 }
3527 }
3528
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003529 private boolean isBandwidthControlEnabled() {
3530 final long token = Binder.clearCallingIdentity();
3531 try {
3532 return mNetworkManager.isBandwidthControlEnabled();
3533 } catch (RemoteException e) {
3534 // ignored; service lives in system_server
3535 return false;
3536 } finally {
3537 Binder.restoreCallingIdentity(token);
3538 }
3539 }
3540
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003541 /**
3542 * Try refreshing {@link #mTime} when stale.
3543 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003544 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003545 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003546 mTime.forceRefresh();
3547 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003548 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003549
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003550 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003551 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3552 }
3553
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003554 private static Intent buildAllowBackgroundDataIntent() {
3555 return new Intent(ACTION_ALLOW_BACKGROUND);
3556 }
3557
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003558 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3559 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3560 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3561 return intent;
3562 }
3563
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003564 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3565 final Intent intent = new Intent();
3566 intent.setComponent(new ComponentName(
3567 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3568 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3569 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3570 return intent;
3571 }
3572
3573 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3574 final Intent intent = new Intent();
3575 intent.setComponent(new ComponentName(
3576 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3577 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3578 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3579 return intent;
3580 }
3581
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003582 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003583 public void addIdleHandler(IdleHandler handler) {
3584 mHandler.getLooper().getQueue().addIdleHandler(handler);
3585 }
3586
Jeff Sharkey1b861272011-05-22 00:34:52 -07003587 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3588 final int size = source.size();
3589 for (int i = 0; i < size; i++) {
3590 target.put(source.keyAt(i), true);
3591 }
3592 }
3593
Stuart Scottf1fb3972015-04-02 18:00:02 -07003594 @Override
3595 public void factoryReset(String subscriber) {
3596 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3597
Stuart Scotte3e314d2015-04-20 14:07:45 -07003598 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3599 return;
3600 }
3601
Stuart Scottf1fb3972015-04-02 18:00:02 -07003602 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003603 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003604 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3605 for (NetworkPolicy policy : policies) {
3606 if (policy.template.equals(template)) {
3607 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3608 policy.inferred = false;
3609 policy.clearSnooze();
3610 }
3611 }
3612 setNetworkPolicies(policies);
3613
3614 // Turn restrict background data off
3615 setRestrictBackground(false);
3616
Stuart Scotte3e314d2015-04-20 14:07:45 -07003617 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3618 // Remove app's "restrict background data" flag
3619 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3620 setUidPolicy(uid, POLICY_NONE);
3621 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003622 }
3623 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003624
3625 private class MyPackageMonitor extends PackageMonitor {
3626
3627 @Override
3628 public void onPackageRemoved(String packageName, int uid) {
3629 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003630 synchronized (mUidRulesFirstLock) {
3631 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3632 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003633 }
3634 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003635 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003636
3637 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3638
3639 @Override
3640 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003641 synchronized (mUidRulesFirstLock) {
3642 boolean changed = removeUserStateUL(userId, false);
3643 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003644 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003645 synchronized (mNetworkPoliciesSecondLock) {
3646 writePolicyAL();
3647 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003648 }
3649 }
3650 }
3651 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003652}