blob: 8dcf653cc491740e887d216c6ead83973cb00ca1 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
128import android.net.wifi.WifiInfo;
129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700141import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700142import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600143import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700145import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700146import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700147import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800148import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700149import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700150import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700151import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700152import android.util.ArrayMap;
153import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700154import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700155import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700156import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700158import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700159import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700160import android.util.SparseBooleanArray;
161import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700162import android.util.TrustedTime;
163import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700164
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700166import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800167import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800168import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800169import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700171import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700172import com.android.server.DeviceIdleController;
173import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700174import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800175import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600176
177import libcore.io.IoUtils;
178
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180
181import org.xmlpull.v1.XmlPullParser;
182import org.xmlpull.v1.XmlPullParserException;
183import org.xmlpull.v1.XmlSerializer;
184
185import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700186import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187import java.io.FileInputStream;
188import java.io.FileNotFoundException;
189import java.io.FileOutputStream;
190import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700191import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700192import java.lang.annotation.Retention;
193import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100194import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195import java.util.ArrayList;
196import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700197import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700199/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700200 * Service that maintains low-level network policy rules, using
201 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700202 * <p>
203 * Derives active rules by combining a given policy with other system status,
204 * and delivers to listeners, such as {@link ConnectivityManager}, for
205 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700206 *
207 * <p>
208 * This class uses 2-3 locks to synchronize state:
209 * <ul>
210 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
211 * rules).
212 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
213 * as network policies).
214 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
215 * must be held.
216 * </ul>
217 *
218 * <p>
219 * As such, methods that require synchronization have the following prefixes:
220 * <ul>
221 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
222 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
223 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
224 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
225 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700226 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700227public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800228 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700229 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700230 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700231
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700232 private static final int VERSION_INIT = 1;
233 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700234 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800235 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800236 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800237 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700238 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700239 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700240 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700241 private static final int VERSION_SWITCH_UID = 10;
242 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800244 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700245 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800246 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700247 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700249 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700250
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251 private static final String TAG_POLICY_LIST = "policy-list";
252 private static final String TAG_NETWORK_POLICY = "network-policy";
253 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700254 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800255 private static final String TAG_WHITELIST = "whitelist";
256 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800257 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700258
259 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700260 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
262 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700263 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800265 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private static final String ATTR_WARNING_BYTES = "warningBytes";
267 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700268 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800269 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
270 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800271 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700272 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700273 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700274 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700275 private static final String ATTR_POLICY = "policy";
276
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800278 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800279 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800280 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700281
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
283
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700284 private static final int MSG_RULES_CHANGED = 1;
285 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800286 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800287 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700288 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700289 private static final int MSG_SCREEN_ON_CHANGED = 8;
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;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700294
Jeff Sharkey75279902011-05-24 18:39:45 -0700295 private final Context mContext;
296 private final IActivityManager mActivityManager;
297 private final IPowerManager mPowerManager;
298 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
315 @GuardedBy("mUidRulesFirstLock") volatile boolean mScreenOn;
316 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
317 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
318 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700319
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700320 private final boolean mSuppressDefaultPolicy;
321
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700322 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800323 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700324 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800325 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700326
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700327 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700328 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700329 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700330 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700331
Felipe Lemef0823852016-06-08 13:43:08 -0700332 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700333 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700334 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700335 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800337 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700338
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700339 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700340 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700341 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
342
Jeff Sharkey32566012014-12-02 18:30:14 -0800343 /**
344 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700345 * in power save mode, except device idle (doze) still applies.
346 * TODO: An int array might be sufficient
347 */
Felipe Lemef0823852016-06-08 13:43:08 -0700348 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700349 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
350
351 /**
352 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800353 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700354 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800355 */
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700357 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700358
Felipe Lemef0823852016-06-08 13:43:08 -0700359 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700360 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
361
Felipe Lemeb85a6372016-01-14 16:16:16 -0800362 /**
363 * UIDs that have been white-listed to avoid restricted background.
364 */
Felipe Lemef0823852016-06-08 13:43:08 -0700365 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800366 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
367
Felipe Lemea9505cc2016-02-26 10:28:41 -0800368 /**
369 * UIDs that have been initially white-listed by system to avoid restricted background.
370 */
Felipe Lemef0823852016-06-08 13:43:08 -0700371 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800372 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
373 new SparseBooleanArray();
374
375 /**
376 * UIDs that have been initially white-listed by system to avoid restricted background,
377 * but later revoked by user.
378 */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800380 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
381 new SparseBooleanArray();
382
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700383 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800385 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700386 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800388 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700389
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700390 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700392 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700393
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700394 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800396 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700397
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600398 /** Higher priority listener before general event dispatch */
399 private INetworkPolicyListener mConnectivityListener;
400
Jeff Sharkey32566012014-12-02 18:30:14 -0800401 private final RemoteCallbackList<INetworkPolicyListener>
402 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700403
Dianne Hackborn497175b2014-07-01 12:56:08 -0700404 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700405
Felipe Lemef0823852016-06-08 13:43:08 -0700406 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700408
Svet Ganov16a16892015-04-16 10:32:04 -0700409 private final AppOpsManager mAppOps;
410
Felipe Lemeb85a6372016-01-14 16:16:16 -0800411 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800412 private final IPackageManager mIPm;
413
Felipe Lemeb85a6372016-01-14 16:16:16 -0800414
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700415 // TODO: keep whitelist of system-critical services that should never have
416 // rules enforced, such as system, phone, and radio UIDs.
417
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700418 // TODO: migrate notifications to SystemUI
419
Jeff Sharkey75279902011-05-24 18:39:45 -0700420 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700421 IPowerManager powerManager, INetworkStatsService networkStats,
422 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700423 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700424 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700425 }
426
427 private static File getSystemDir() {
428 return new File(Environment.getDataDirectory(), "system");
429 }
430
431 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700432 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700433 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
434 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700435 mContext = checkNotNull(context, "missing context");
436 mActivityManager = checkNotNull(activityManager, "missing activityManager");
437 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700438 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700439 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700440 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700441 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700442 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700443 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800444 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700445
Amith Yamasani450a16b2013-09-18 16:28:50 -0700446 HandlerThread thread = new HandlerThread(TAG);
447 thread.start();
448 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700449
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700450 mSuppressDefaultPolicy = suppressDefaultPolicy;
451
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700452 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700453
454 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800455
456 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700457
458 // Expose private service for system components to use.
459 LocalServices.addService(NetworkPolicyManagerInternal.class,
460 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700461 }
462
463 public void bindConnectivityManager(IConnectivityManager connManager) {
464 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700465 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700466
Jeff Sharkey497e4432011-06-14 17:27:29 -0700467 public void bindNotificationManager(INotificationManager notifManager) {
468 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
469 }
470
Felipe Lemef0823852016-06-08 13:43:08 -0700471 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700472 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700473 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
474 mPowerSaveWhitelistExceptIdleAppIds.clear();
475 if (whitelist != null) {
476 for (int uid : whitelist) {
477 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
478 }
479 }
480 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700481 mPowerSaveWhitelistAppIds.clear();
482 if (whitelist != null) {
483 for (int uid : whitelist) {
484 mPowerSaveWhitelistAppIds.put(uid, true);
485 }
486 }
487 } catch (RemoteException e) {
488 }
489 }
490
Felipe Lemea9505cc2016-02-26 10:28:41 -0800491 /**
492 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
493 * revoke the whitelist.
494 *
495 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
496 */
Felipe Lemef0823852016-06-08 13:43:08 -0700497 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800498 final List<UserInfo> users = mUserManager.getUsers();
499 final int numberUsers = users.size();
500
Felipe Lemea110eec2016-04-29 09:58:06 -0700501 boolean changed = false;
502 for (int i = 0; i < numberUsers; i++) {
503 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700504 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700505 }
506 return changed;
507 }
508
Felipe Lemef0823852016-06-08 13:43:08 -0700509 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700510 final SystemConfig sysConfig = SystemConfig.getInstance();
511 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800512 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
513 boolean changed = false;
514 for (int i = 0; i < allowDataUsage.size(); i++) {
515 final String pkg = allowDataUsage.valueAt(i);
516 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700517 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
518 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800519 final ApplicationInfo app;
520 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700521 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800522 } catch (PackageManager.NameNotFoundException e) {
523 // Should not happen
524 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
525 continue;
526 }
527 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700528 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800529 continue;
530 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700531 final int uid = UserHandle.getUid(userId, app.uid);
532 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
533 if (LOGD)
534 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
535 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700537 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
538 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
539 + userId + ") to restrict background whitelist");
540 mRestrictBackgroundWhitelistUids.append(uid, true);
541 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800542 }
543 }
544 return changed;
545 }
546
Felipe Lemef0823852016-06-08 13:43:08 -0700547 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700548 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700549 // Clear the states of the current whitelist
550 final int N = mPowerSaveTempWhitelistAppIds.size();
551 for (int i = 0; i < N; i++) {
552 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
553 }
554 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700555 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700556 if (whitelist != null) {
557 for (int uid : whitelist) {
558 mPowerSaveTempWhitelistAppIds.put(uid, true);
559 }
560 }
561 } catch (RemoteException e) {
562 }
563 }
564
Amith Yamasani06f08062015-06-12 13:23:33 -0700565 /**
566 * Remove unnecessary entries in the temp whitelist
567 */
Felipe Lemef0823852016-06-08 13:43:08 -0700568 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700569 final int N = mPowerSaveTempWhitelistAppIds.size();
570 for (int i = N - 1; i >= 0; i--) {
571 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
572 mPowerSaveTempWhitelistAppIds.removeAt(i);
573 }
574 }
575 }
576
Jeff Sharkeya4620792011-05-20 15:29:23 -0700577 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700578 if (!isBandwidthControlEnabled()) {
579 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
580 return;
581 }
582
Amith Yamasani15e472352015-04-24 19:06:07 -0700583 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
584
Felipe Lemeb85a6372016-01-14 16:16:16 -0800585 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
586
Felipe Lemef0823852016-06-08 13:43:08 -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 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700601 }
602 }
Felipe Lemef0823852016-06-08 13:43:08 -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 Lemed31a97f2016-05-06 14:53:50 -0700614
Felipe Lemef0823852016-06-08 13:43:08 -0700615 setRestrictBackgroundUL(mRestrictBackground);
616 updateRulesForGlobalChangeAL(false);
617 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800618 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700619 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700620
Jeff Sharkeya4620792011-05-20 15:29:23 -0700621 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700622
Jeff Sharkeya4620792011-05-20 15:29:23 -0700623 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700624 mActivityManager.registerUidObserver(mUidObserver,
625 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700626 mNetworkManager.registerObserver(mAlertObserver);
627 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700628 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700629 }
630
Jeff Sharkeya4620792011-05-20 15:29:23 -0700631 // TODO: traverse existing processes to know foreground state, or have
632 // activitymanager dispatch current state when new observer attached.
633
634 final IntentFilter screenFilter = new IntentFilter();
635 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
636 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700637 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700638
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700639 // listen for changes to power save whitelist
640 final IntentFilter whitelistFilter = new IntentFilter(
641 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
642 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
643
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700644 DeviceIdleController.LocalService deviceIdleService
645 = LocalServices.getService(DeviceIdleController.LocalService.class);
646 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
647
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700648 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900649 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700650 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
651
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700652 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700653 final IntentFilter packageFilter = new IntentFilter();
654 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700655 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700656 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700657
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700658 // listen for UID changes to update policy
659 mContext.registerReceiver(
660 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
661
662 // listen for user changes to update policy
663 final IntentFilter userFilter = new IntentFilter();
664 userFilter.addAction(ACTION_USER_ADDED);
665 userFilter.addAction(ACTION_USER_REMOVED);
666 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
667
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700668 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700669 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
670 mContext.registerReceiver(
671 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
672
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700673 // listen for restrict background changes from notifications
674 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
675 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
676
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800677 // listen for snooze warning from notifications
678 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
679 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
680 MANAGE_NETWORK_POLICY, mHandler);
681
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700682 // listen for configured wifi networks to be removed
683 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700684 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700685
686 // listen for wifi state changes to catch metered hint
687 final IntentFilter wifiStateFilter = new IntentFilter(
688 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700689 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700690
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700691 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700692
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700693 }
694
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700695 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700696 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700697 synchronized (mUidRulesFirstLock) {
698 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700699 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700700 }
701
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700702 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700703 synchronized (mUidRulesFirstLock) {
704 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700705 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700706 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700707
708 @Override public void onUidActive(int uid) throws RemoteException {
709 }
710
711 @Override public void onUidIdle(int uid) throws RemoteException {
712 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700713 };
714
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700715 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700716 @Override
717 public void onReceive(Context context, Intent intent) {
718 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700719 synchronized (mUidRulesFirstLock) {
720 updatePowerSaveWhitelistUL();
721 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700722 }
723 }
724 };
725
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700726 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
727 @Override
728 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700729 synchronized (mUidRulesFirstLock) {
730 updatePowerSaveTempWhitelistUL();
731 updateRulesForTempWhitelistChangeUL();
732 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700733 }
734 }
735 };
736
737 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700738 @Override
739 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800740 // screen-related broadcasts are protected by system, no need
741 // for permissions check.
742 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700743 }
744 };
745
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700746 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700747 @Override
748 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700749 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700750
751 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700752 final int uid = intent.getIntExtra(EXTRA_UID, -1);
753 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700754
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700755 if (ACTION_PACKAGE_ADDED.equals(action)) {
756 // update rules for UID, since it might be subject to
757 // global background data policy
758 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700759 synchronized (mUidRulesFirstLock) {
760 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700761 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700762 }
763 }
764 };
765
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700766 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700767 @Override
768 public void onReceive(Context context, Intent intent) {
769 // on background handler thread, and UID_REMOVED is protected
770
771 final int uid = intent.getIntExtra(EXTRA_UID, -1);
772 if (uid == -1) return;
773
774 // remove any policy and update rules to clean up
775 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700776 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700777 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700778 updateRestrictionRulesForUidUL(uid);
779 synchronized (mNetworkPoliciesSecondLock) {
780 writePolicyAL();
781 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700782 }
783 }
784 };
785
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700786 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700787 @Override
788 public void onReceive(Context context, Intent intent) {
789 // on background handler thread, and USER_ADDED and USER_REMOVED
790 // broadcasts are protected
791
792 final String action = intent.getAction();
793 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
794 if (userId == -1) return;
795
Amith Yamasani15e472352015-04-24 19:06:07 -0700796 switch (action) {
797 case ACTION_USER_REMOVED:
798 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700799 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800800 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700801 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700802 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700803 if (action == ACTION_USER_ADDED) {
804 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700805 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700806 }
807 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700808 synchronized (mNetworkPoliciesSecondLock) {
809 updateRulesForGlobalChangeAL(true);
810 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700811 }
812 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700813 }
814 }
815 };
816
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700817 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700818 * Receiver that watches for {@link INetworkStatsService} updates, which we
819 * use to check against {@link NetworkPolicy#warningBytes}.
820 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700821 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700822 @Override
823 public void onReceive(Context context, Intent intent) {
824 // on background handler thread, and verified
825 // READ_NETWORK_USAGE_HISTORY permission above.
826
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800827 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700828 synchronized (mNetworkPoliciesSecondLock) {
829 updateNetworkEnabledNL();
830 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700831 }
832 }
833 };
834
835 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700836 * Receiver that watches for {@link Notification} control of
837 * {@link #mRestrictBackground}.
838 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700839 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700840 @Override
841 public void onReceive(Context context, Intent intent) {
842 // on background handler thread, and verified MANAGE_NETWORK_POLICY
843 // permission above.
844
845 setRestrictBackground(false);
846 }
847 };
848
849 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800850 * Receiver that watches for {@link Notification} control of
851 * {@link NetworkPolicy#lastWarningSnooze}.
852 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700853 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800854 @Override
855 public void onReceive(Context context, Intent intent) {
856 // on background handler thread, and verified MANAGE_NETWORK_POLICY
857 // permission above.
858
859 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
860 performSnooze(template, TYPE_WARNING);
861 }
862 };
863
864 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700865 * Receiver that watches for {@link WifiConfiguration} to be changed.
866 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700867 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700868 @Override
869 public void onReceive(Context context, Intent intent) {
870 // on background handler thread, and verified CONNECTIVITY_INTERNAL
871 // permission above.
872
873 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
874 if (reason == CHANGE_REASON_REMOVED) {
875 final WifiConfiguration config = intent.getParcelableExtra(
876 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700877 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800878 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700879 synchronized (mUidRulesFirstLock) {
880 synchronized (mNetworkPoliciesSecondLock) {
881 if (mNetworkPolicy.containsKey(template)) {
882 mNetworkPolicy.remove(template);
883 writePolicyAL();
884 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700885 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700886 }
887 }
888 }
889 }
890 };
891
892 /**
893 * Receiver that watches {@link WifiInfo} state changes to infer metered
894 * state. Ignores hints when policy is user-defined.
895 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700896 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700897 @Override
898 public void onReceive(Context context, Intent intent) {
899 // on background handler thread, and verified CONNECTIVITY_INTERNAL
900 // permission above.
901
902 // ignore when not connected
903 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
904 if (!netInfo.isConnected()) return;
905
906 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
907 final boolean meteredHint = info.getMeteredHint();
908
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800909 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700910 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700911 NetworkPolicy policy = mNetworkPolicy.get(template);
912 if (policy == null && meteredHint) {
913 // policy doesn't exist, and AP is hinting that it's
914 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800915 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700916 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700917
918 } else if (policy != null && policy.inferred) {
919 // policy exists, and was inferred: update its current
920 // metered state.
921 policy.metered = meteredHint;
922
923 // since this is inferred for each wifi session, just update
924 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700925 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700926 }
927 }
928 }
929 };
930
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800931 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
932 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
933 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
934 metered, true);
935 }
936
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700937 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700938 * Observer that watches for {@link INetworkManagementService} alerts.
939 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700940 final private INetworkManagementEventObserver mAlertObserver
941 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700942 @Override
943 public void limitReached(String limitName, String iface) {
944 // only someone like NMS should be calling us
945 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
946
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800947 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
948 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700949 }
950 }
951 };
952
953 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
955 * to show visible notifications as needed.
956 */
Felipe Lemef0823852016-06-08 13:43:08 -0700957 void updateNotificationsNL() {
958 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700959
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700960 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700961 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700962 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963
964 // TODO: when switching to kernel notifications, compute next future
965 // cycle boundary to recompute notifications.
966
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700967 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800968 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700969 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
970 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700971 // ignore policies that aren't relevant to user
972 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700973 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700974
Jeff Sharkey497e4432011-06-14 17:27:29 -0700975 final long start = computeLastCycleBoundary(currentTime, policy);
976 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700977 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700978
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700979 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800980 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700981 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
982 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700983 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700984 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985 }
986
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700988 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700989
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800990 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700992 }
993 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700994 }
995
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700997 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
998 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 if (!mActiveNotifs.contains(tag)) {
1000 cancelNotification(tag);
1001 }
1002 }
1003 }
1004
1005 /**
1006 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001007 * current device state, such as when
1008 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1009 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001010 */
1011 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001012 if (template.isMatchRuleMobile()) {
1013 final TelephonyManager tele = TelephonyManager.from(mContext);
1014 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001015
Jeff Sharkey32566012014-12-02 18:30:14 -08001016 // Mobile template is relevant when any active subscriber matches
1017 final int[] subIds = sub.getActiveSubscriptionIdList();
1018 for (int subId : subIds) {
1019 final String subscriberId = tele.getSubscriberId(subId);
1020 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001021 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001022 if (template.matches(probeIdent)) {
1023 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001024 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001025 }
1026 return false;
1027 } else {
1028 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001029 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 }
1031
1032 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001033 * Notify that given {@link NetworkTemplate} is over
1034 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1035 */
Felipe Lemef0823852016-06-08 13:43:08 -07001036 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 if (!mOverLimitNotified.contains(template)) {
1038 mContext.startActivity(buildNetworkOverLimitIntent(template));
1039 mOverLimitNotified.add(template);
1040 }
1041 }
1042
Felipe Lemef0823852016-06-08 13:43:08 -07001043 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 mOverLimitNotified.remove(template);
1045 }
1046
1047 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048 * Build unique tag that identifies an active {@link NetworkPolicy}
1049 * notification of a specific type, like {@link #TYPE_LIMIT}.
1050 */
1051 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001052 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001053 }
1054
1055 /**
1056 * Show notification for combined {@link NetworkPolicy} and specific type,
1057 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1058 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001059 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001060 final String tag = buildNotificationTag(policy, type);
1061 final Notification.Builder builder = new Notification.Builder(mContext);
1062 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001063 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001064 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001065 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001066
1067 final Resources res = mContext.getResources();
1068 switch (type) {
1069 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001071 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001073 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074 builder.setTicker(title);
1075 builder.setContentTitle(title);
1076 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001077
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001078 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1079 builder.setDeleteIntent(PendingIntent.getBroadcast(
1080 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1081
1082 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001083 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001084 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1085
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 break;
1087 }
1088 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1090
1091 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001092 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001093 switch (policy.template.getMatchRule()) {
1094 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001097 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001099 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001100 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001101 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001103 case MATCH_WIFI:
1104 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001105 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 break;
1107 default:
1108 title = null;
1109 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001110 }
1111
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001112 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001113 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114 builder.setTicker(title);
1115 builder.setContentTitle(title);
1116 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001117
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1119 builder.setContentIntent(PendingIntent.getActivity(
1120 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1121 break;
1122 }
1123 case TYPE_LIMIT_SNOOZED: {
1124 final long overBytes = totalBytes - policy.limitBytes;
1125 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1126 Formatter.formatFileSize(mContext, overBytes));
1127
1128 final CharSequence title;
1129 switch (policy.template.getMatchRule()) {
1130 case MATCH_MOBILE_3G_LOWER:
1131 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1132 break;
1133 case MATCH_MOBILE_4G:
1134 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1135 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001136 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1138 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001139 case MATCH_WIFI:
1140 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1141 break;
1142 default:
1143 title = null;
1144 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 }
1146
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001147 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001148 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 builder.setTicker(title);
1150 builder.setContentTitle(title);
1151 builder.setContentText(body);
1152
1153 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001154 builder.setContentIntent(PendingIntent.getActivity(
1155 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001156 break;
1157 }
1158 }
1159
1160 // TODO: move to NotificationManager once we can mock it
1161 try {
1162 final String packageName = mContext.getPackageName();
1163 final int[] idReceived = new int[1];
1164 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001165 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001166 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001167 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001169 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001170 }
1171 }
1172
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001173 private void cancelNotification(String tag) {
1174 // TODO: move to NotificationManager once we can mock it
1175 try {
1176 final String packageName = mContext.getPackageName();
1177 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001178 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001179 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001180 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001181 }
1182 }
1183
1184 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001185 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001186 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001187 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001188 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001189 @Override
1190 public void onReceive(Context context, Intent intent) {
1191 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1192 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001193
1194 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001195 synchronized (mNetworkPoliciesSecondLock) {
1196 ensureActiveMobilePolicyNL();
1197 normalizePoliciesNL();
1198 updateNetworkEnabledNL();
1199 updateNetworkRulesNL();
1200 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001201 }
1202 }
1203 };
1204
1205 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001206 * Proactively control network data connections when they exceed
1207 * {@link NetworkPolicy#limitBytes}.
1208 */
Felipe Lemef0823852016-06-08 13:43:08 -07001209 void updateNetworkEnabledNL() {
1210 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001211
1212 // TODO: reset any policy-disabled networks when any policy is removed
1213 // completely, which is currently rare case.
1214
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001215 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001216 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1217 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001219 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001220 setNetworkTemplateEnabled(policy.template, true);
1221 continue;
1222 }
1223
1224 final long start = computeLastCycleBoundary(currentTime, policy);
1225 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001226 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227
1228 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001229 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1230 && policy.lastLimitSnooze < start;
1231 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001232
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001233 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 }
1235 }
1236
1237 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001238 * Proactively disable networks that match the given
1239 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 */
1241 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001242 // TODO: reach into ConnectivityManager to proactively disable bringing
1243 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001244
1245 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1246 // If mobile data usage hits the limit or if the user resumes the data, we need to
1247 // notify telephony.
1248 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1249 final TelephonyManager tm = TelephonyManager.from(mContext);
1250
1251 final int[] subIds = sm.getActiveSubscriptionIdList();
1252 for (int subId : subIds) {
1253 final String subscriberId = tm.getSubscriberId(subId);
1254 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1255 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1256 // Template is matched when subscriber id matches.
1257 if (template.matches(probeIdent)) {
1258 tm.setPolicyDataEnabled(enabled, subId);
1259 }
1260 }
1261 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001262 }
1263
1264 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001265 * Examine all connected {@link NetworkState}, looking for
1266 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1267 * remaining quota based on usage cycle and historical stats.
1268 */
Felipe Lemef0823852016-06-08 13:43:08 -07001269 void updateNetworkRulesNL() {
1270 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271
1272 final NetworkState[] states;
1273 try {
1274 states = mConnManager.getAllNetworkState();
1275 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001276 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001277 return;
1278 }
1279
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001280 // First, generate identities of all connected networks so we can
1281 // quickly compare them against all defined policies below.
1282 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001283 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001285 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001286 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001287
1288 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001289 if (baseIface != null) {
1290 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001291 }
1292
1293 // Stacked interfaces are considered to have same identity as
1294 // their parent network.
1295 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1296 for (LinkProperties stackedLink : stackedLinks) {
1297 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001298 if (stackedIface != null) {
1299 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001300 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001301 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 }
1303 }
1304
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001305 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001306 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001307 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001308 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001309 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001310
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001311 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001312 for (int j = connIdents.size() - 1; j >= 0; j--) {
1313 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1314 if (policy.template.matches(ident.second)) {
1315 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316 }
1317 }
1318
1319 if (ifaceList.size() > 0) {
1320 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001321 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 }
1323 }
1324
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001325 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001326 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001327
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 // apply each policy that we found ifaces for; compute remaining data
1329 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001330 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001331 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1332 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1333 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001335 final long start;
1336 final long totalBytes;
1337 if (policy.hasCycle()) {
1338 start = computeLastCycleBoundary(currentTime, policy);
1339 totalBytes = getTotalBytes(policy.template, start, currentTime);
1340 } else {
1341 start = Long.MAX_VALUE;
1342 totalBytes = 0;
1343 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001345 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001346 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001347 }
1348
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001349 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001350 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001351 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001352 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001353 if (!hasLimit) {
1354 // metered network, but no policy limit; we still need to
1355 // restrict apps, so push really high quota.
1356 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001357 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001358 // snoozing past quota, but we still need to restrict apps,
1359 // so push really high quota.
1360 quotaBytes = Long.MAX_VALUE;
1361 } else {
1362 // remaining "quota" bytes are based on total usage in
1363 // current cycle. kernel doesn't like 0-byte rules, so we
1364 // set 1-byte quota and disable the radio later.
1365 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1366 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001367
1368 if (ifaces.length > 1) {
1369 // TODO: switch to shared quota once NMS supports
1370 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001371 }
1372
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001373 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001374 // long quotaBytes split up into two ints to fit in message
1375 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1376 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1377 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001378 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001379 }
1380 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001381
1382 // keep track of lowest warning or limit of active policies
1383 if (hasWarning && policy.warningBytes < lowestRule) {
1384 lowestRule = policy.warningBytes;
1385 }
1386 if (hasLimit && policy.limitBytes < lowestRule) {
1387 lowestRule = policy.limitBytes;
1388 }
1389 }
1390
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001391 for (int i = connIfaces.size()-1; i >= 0; i--) {
1392 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001393 // long quotaBytes split up into two ints to fit in message
1394 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1395 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1396 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001397 newMeteredIfaces.add(iface);
1398 }
1399
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001400 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001401
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001402 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001403 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1404 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001405 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001406 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1407 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001408 }
1409 }
1410 mMeteredIfaces = newMeteredIfaces;
1411
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001412 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001413 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001414 }
1415
1416 /**
1417 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1418 * have at least a default mobile policy defined.
1419 */
Felipe Lemef0823852016-06-08 13:43:08 -07001420 private void ensureActiveMobilePolicyNL() {
1421 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001422 if (mSuppressDefaultPolicy) return;
1423
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001424 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001425 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001426
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 final int[] subIds = sub.getActiveSubscriptionIdList();
1428 for (int subId : subIds) {
1429 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001430 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001431 }
1432 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001433
Felipe Lemef0823852016-06-08 13:43:08 -07001434 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001435 // Poke around to see if we already have a policy
1436 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001437 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001438 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1439 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1440 if (template.matches(probeIdent)) {
1441 if (LOGD) {
1442 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1443 + NetworkIdentity.scrubSubscriberId(subscriberId));
1444 }
1445 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001446 }
1447 }
1448
Jeff Sharkey32566012014-12-02 18:30:14 -08001449 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1450 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001451
Jeff Sharkey32566012014-12-02 18:30:14 -08001452 // Build default mobile policy, and assume usage cycle starts today
1453 final long warningBytes = mContext.getResources().getInteger(
1454 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001455
Jeff Sharkey32566012014-12-02 18:30:14 -08001456 final Time time = new Time();
1457 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001458
Jeff Sharkey32566012014-12-02 18:30:14 -08001459 final int cycleDay = time.monthDay;
1460 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001461
Jeff Sharkey32566012014-12-02 18:30:14 -08001462 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1463 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1464 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001465 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001466 }
1467
Felipe Lemef0823852016-06-08 13:43:08 -07001468 private void readPolicyAL() {
1469 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001470
1471 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001472 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001473 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001474
1475 FileInputStream fis = null;
1476 try {
1477 fis = mPolicyFile.openRead();
1478 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001479 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480
1481 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001482 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001483 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001484 while ((type = in.next()) != END_DOCUMENT) {
1485 final String tag = in.getName();
1486 if (type == START_TAG) {
1487 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001488 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001489 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001490 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1491 mRestrictBackground = readBooleanAttribute(
1492 in, ATTR_RESTRICT_BACKGROUND);
1493 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001494 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001495 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001496 if (mRestrictBackground != oldValue) {
1497 // Some early services may have read the default value,
1498 // so notify them that it's changed
1499 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1500 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1501 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001502
1503 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1504 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1505 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001506 final String networkId;
1507 if (version >= VERSION_ADDED_NETWORK_ID) {
1508 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1509 } else {
1510 networkId = null;
1511 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001513 final String cycleTimezone;
1514 if (version >= VERSION_ADDED_TIMEZONE) {
1515 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1516 } else {
1517 cycleTimezone = Time.TIMEZONE_UTC;
1518 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001519 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1520 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001521 final long lastLimitSnooze;
1522 if (version >= VERSION_SPLIT_SNOOZE) {
1523 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1524 } else if (version >= VERSION_ADDED_SNOOZE) {
1525 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001526 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001527 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001528 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001529 final boolean metered;
1530 if (version >= VERSION_ADDED_METERED) {
1531 metered = readBooleanAttribute(in, ATTR_METERED);
1532 } else {
1533 switch (networkTemplate) {
1534 case MATCH_MOBILE_3G_LOWER:
1535 case MATCH_MOBILE_4G:
1536 case MATCH_MOBILE_ALL:
1537 metered = true;
1538 break;
1539 default:
1540 metered = false;
1541 }
1542 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001543 final long lastWarningSnooze;
1544 if (version >= VERSION_SPLIT_SNOOZE) {
1545 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1546 } else {
1547 lastWarningSnooze = SNOOZE_NEVER;
1548 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001549 final boolean inferred;
1550 if (version >= VERSION_ADDED_INFERRED) {
1551 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1552 } else {
1553 inferred = false;
1554 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555
Jeff Sharkey32566012014-12-02 18:30:14 -08001556 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1557 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001558 if (template.isPersistable()) {
1559 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1560 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1561 lastLimitSnooze, metered, inferred));
1562 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001563
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001564 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001565 final int uid = readIntAttribute(in, ATTR_UID);
1566 final int policy = readIntAttribute(in, ATTR_POLICY);
1567
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001568 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001569 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001570 } else {
1571 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1572 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001573 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001574 final int appId = readIntAttribute(in, ATTR_APP_ID);
1575 final int policy = readIntAttribute(in, ATTR_POLICY);
1576
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001577 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001578 // app policy is deprecated so this is only used in pre system user split.
1579 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001580 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001581 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001582 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001583 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001584 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001585 } else if (TAG_WHITELIST.equals(tag)) {
1586 insideWhitelist = true;
1587 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1588 final int uid = readIntAttribute(in, ATTR_UID);
1589 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001590 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1591 final int uid = readIntAttribute(in, ATTR_UID);
1592 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001594 } else if (type == END_TAG) {
1595 if (TAG_WHITELIST.equals(tag)) {
1596 insideWhitelist = false;
1597 }
1598
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599 }
1600 }
1601
1602 } catch (FileNotFoundException e) {
1603 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001604 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 } catch (IOException 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 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001608 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 } finally {
1610 IoUtils.closeQuietly(fis);
1611 }
1612 }
1613
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001614 /**
1615 * Upgrade legacy background data flags, notifying listeners of one last
1616 * change to always-true.
1617 */
Felipe Lemef0823852016-06-08 13:43:08 -07001618 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001619 mRestrictBackground = Settings.Secure.getInt(
1620 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1621
1622 // kick off one last broadcast if restricted
1623 if (mRestrictBackground) {
1624 final Intent broadcast = new Intent(
1625 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001626 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001627 }
1628 }
1629
Felipe Lemef0823852016-06-08 13:43:08 -07001630 void writePolicyAL() {
1631 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001632
1633 FileOutputStream fos = null;
1634 try {
1635 fos = mPolicyFile.startWrite();
1636
1637 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001638 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639 out.startDocument(null, true);
1640
1641 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001642 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001643 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644
1645 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001646 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1647 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001648 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001649 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001650
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001652 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1653 final String subscriberId = template.getSubscriberId();
1654 if (subscriberId != null) {
1655 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001657 final String networkId = template.getNetworkId();
1658 if (networkId != null) {
1659 out.attribute(null, ATTR_NETWORK_ID, networkId);
1660 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001661 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001662 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001663 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1664 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001665 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1666 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001667 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001668 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 out.endTag(null, TAG_NETWORK_POLICY);
1670 }
1671
1672 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001673 for (int i = 0; i < mUidPolicy.size(); i++) {
1674 final int uid = mUidPolicy.keyAt(i);
1675 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001676
Jeff Sharkey497e4432011-06-14 17:27:29 -07001677 // skip writing empty policies
1678 if (policy == POLICY_NONE) continue;
1679
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001680 out.startTag(null, TAG_UID_POLICY);
1681 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001682 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001683 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001684 }
1685
1686 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001687
1688 // write all whitelists
1689 out.startTag(null, TAG_WHITELIST);
1690
1691 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001692 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001693 for (int i = 0; i < size; i++) {
1694 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1695 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1696 writeIntAttribute(out, ATTR_UID, uid);
1697 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1698 }
1699
Felipe Lemea9505cc2016-02-26 10:28:41 -08001700 // revoked restrict background whitelist
1701 size = mRestrictBackgroundWhitelistRevokedUids.size();
1702 for (int i = 0; i < size; i++) {
1703 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1704 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1705 writeIntAttribute(out, ATTR_UID, uid);
1706 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1707 }
1708
Felipe Lemeb85a6372016-01-14 16:16:16 -08001709 out.endTag(null, TAG_WHITELIST);
1710
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001711 out.endDocument();
1712
1713 mPolicyFile.finishWrite(fos);
1714 } catch (IOException e) {
1715 if (fos != null) {
1716 mPolicyFile.failWrite(fos);
1717 }
1718 }
1719 }
1720
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001721 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001722 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001723 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001724
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001725 if (!UserHandle.isApp(uid)) {
1726 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001727 }
Felipe Lemef0823852016-06-08 13:43:08 -07001728 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001729 final long token = Binder.clearCallingIdentity();
1730 try {
1731 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1732 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001733 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001734 }
1735 } finally {
1736 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001737 }
1738 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001739 }
1740
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001741 @Override
1742 public void addUidPolicy(int uid, int policy) {
1743 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001744
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001745 if (!UserHandle.isApp(uid)) {
1746 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1747 }
1748
Felipe Lemef0823852016-06-08 13:43:08 -07001749 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001750 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1751 policy |= oldPolicy;
1752 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001753 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001754 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001755 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001756 }
1757
1758 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001759 public void removeUidPolicy(int uid, int policy) {
1760 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1761
1762 if (!UserHandle.isApp(uid)) {
1763 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1764 }
1765
Felipe Lemef0823852016-06-08 13:43:08 -07001766 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001767 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1768 policy = oldPolicy & ~policy;
1769 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001770 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001771 }
1772 }
1773 }
1774
Felipe Lemef0823852016-06-08 13:43:08 -07001775 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1776 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001777
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001778 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1779 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1780 isBlacklisted ? 1 : 0).sendToTarget();
1781
1782 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001783 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001784 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1785 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001786 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001787 .sendToTarget();
1788 }
1789 }
1790
Felipe Lemef0823852016-06-08 13:43:08 -07001791 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001792 mUidPolicy.put(uid, policy);
1793
1794 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001795 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001796 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001797 synchronized (mNetworkPoliciesSecondLock) {
1798 writePolicyAL();
1799 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001800 }
1801 }
1802
1803 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001804 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001805 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1806
Felipe Lemef0823852016-06-08 13:43:08 -07001807 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001808 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001809 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001810 }
1811
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001812 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001813 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001814 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1815
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001816 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001817 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001818 for (int i = 0; i < mUidPolicy.size(); i++) {
1819 final int uid = mUidPolicy.keyAt(i);
1820 final int uidPolicy = mUidPolicy.valueAt(i);
1821 if (uidPolicy == policy) {
1822 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001823 }
1824 }
1825 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001826 return uids;
1827 }
1828
1829 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001830 * Removes any persistable state associated with given {@link UserHandle}, persisting
1831 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001832 */
Felipe Lemef0823852016-06-08 13:43:08 -07001833 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001834
Felipe Lemef0823852016-06-08 13:43:08 -07001835 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001836 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001837
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001838 // Remove entries from restricted background UID whitelist
1839 int[] wlUids = new int[0];
1840 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1841 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1842 if (UserHandle.getUserId(uid) == userId) {
1843 wlUids = appendInt(wlUids, uid);
1844 }
1845 }
1846
1847 if (wlUids.length > 0) {
1848 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001849 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001850 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001851 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001852 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001853
1854 // Remove entries from revoked default restricted background UID whitelist
1855 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1856 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1857 if (UserHandle.getUserId(uid) == userId) {
1858 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001859 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001860 }
1861 }
1862
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001863 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001864 int[] uids = new int[0];
1865 for (int i = 0; i < mUidPolicy.size(); i++) {
1866 final int uid = mUidPolicy.keyAt(i);
1867 if (UserHandle.getUserId(uid) == userId) {
1868 uids = appendInt(uids, uid);
1869 }
1870 }
1871
1872 if (uids.length > 0) {
1873 for (int uid : uids) {
1874 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001875 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001876 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001877 }
Felipe Lemef0823852016-06-08 13:43:08 -07001878 synchronized (mNetworkPoliciesSecondLock) {
1879 updateRulesForGlobalChangeAL(true);
1880 if (writePolicy && changed) {
1881 writePolicyAL();
1882 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001883 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001884 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001885 }
1886
1887 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001888 public void setConnectivityListener(INetworkPolicyListener listener) {
1889 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1890 if (mConnectivityListener != null) {
1891 throw new IllegalStateException("Connectivity listener already registered");
1892 }
1893 mConnectivityListener = listener;
1894 }
1895
1896 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001897 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001898 // TODO: create permission for observing network policy
1899 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001900 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001901 }
1902
1903 @Override
1904 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001905 // TODO: create permission for observing network policy
1906 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001907 mListeners.unregister(listener);
1908 }
1909
Jeff Sharkey1b861272011-05-22 00:34:52 -07001910 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001911 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001912 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1913
Felipe Leme6a05eee2016-02-19 14:43:51 -08001914 final long token = Binder.clearCallingIdentity();
1915 try {
1916 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001917 synchronized (mUidRulesFirstLock) {
1918 synchronized (mNetworkPoliciesSecondLock) {
1919 normalizePoliciesNL(policies);
1920 updateNetworkEnabledNL();
1921 updateNetworkRulesNL();
1922 updateNotificationsNL();
1923 writePolicyAL();
1924 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001925 }
1926 } finally {
1927 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001928 }
1929 }
1930
Felipe Lemef0823852016-06-08 13:43:08 -07001931 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001932 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001933 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1934 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001935 }
1936
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001937 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001938 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001940 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001941 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1942 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1943 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001944 } catch (SecurityException e) {
1945 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001946
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001947 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1948 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1949 return new NetworkPolicy[0];
1950 }
Svet Ganov16a16892015-04-16 10:32:04 -07001951 }
1952
Felipe Lemef0823852016-06-08 13:43:08 -07001953 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001954 final int size = mNetworkPolicy.size();
1955 final NetworkPolicy[] policies = new NetworkPolicy[size];
1956 for (int i = 0; i < size; i++) {
1957 policies[i] = mNetworkPolicy.valueAt(i);
1958 }
1959 return policies;
1960 }
1961 }
1962
Felipe Lemef0823852016-06-08 13:43:08 -07001963 private void normalizePoliciesNL() {
1964 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001965 }
1966
Felipe Lemef0823852016-06-08 13:43:08 -07001967 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001968 final TelephonyManager tele = TelephonyManager.from(mContext);
1969 final String[] merged = tele.getMergedSubscriberIds();
1970
1971 mNetworkPolicy.clear();
1972 for (NetworkPolicy policy : policies) {
1973 // When two normalized templates conflict, prefer the most
1974 // restrictive policy
1975 policy.template = NetworkTemplate.normalize(policy.template, merged);
1976 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1977 if (existing == null || existing.compareTo(policy) > 0) {
1978 if (existing != null) {
1979 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1980 }
1981 mNetworkPolicy.put(policy.template, policy);
1982 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001983 }
1984 }
1985
1986 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001987 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001988 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001989
1990 final long token = Binder.clearCallingIdentity();
1991 try {
1992 performSnooze(template, TYPE_LIMIT);
1993 } finally {
1994 Binder.restoreCallingIdentity(token);
1995 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001996 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001997
Dianne Hackborn497175b2014-07-01 12:56:08 -07001998 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001999 maybeRefreshTrustedTime();
2000 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002001 synchronized (mUidRulesFirstLock) {
2002 synchronized (mNetworkPoliciesSecondLock) {
2003 // find and snooze local policy that matches
2004 final NetworkPolicy policy = mNetworkPolicy.get(template);
2005 if (policy == null) {
2006 throw new IllegalArgumentException("unable to find policy for " + template);
2007 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002008
Felipe Lemef0823852016-06-08 13:43:08 -07002009 switch (type) {
2010 case TYPE_WARNING:
2011 policy.lastWarningSnooze = currentTime;
2012 break;
2013 case TYPE_LIMIT:
2014 policy.lastLimitSnooze = currentTime;
2015 break;
2016 default:
2017 throw new IllegalArgumentException("unexpected type");
2018 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002019
Felipe Lemef0823852016-06-08 13:43:08 -07002020 normalizePoliciesNL();
2021 updateNetworkEnabledNL();
2022 updateNetworkRulesNL();
2023 updateNotificationsNL();
2024 writePolicyAL();
2025 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002026 }
2027 }
2028
2029 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002030 public void onTetheringChanged(String iface, boolean tethering) {
2031 // No need to enforce permission because setRestrictBackground() will do it.
2032 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002033 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002034 if (mRestrictBackground && tethering) {
2035 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2036 setRestrictBackground(false);
2037 }
2038 }
2039 }
2040
2041 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002042 public void setRestrictBackground(boolean restrictBackground) {
2043 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002044 final long token = Binder.clearCallingIdentity();
2045 try {
2046 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002047 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002048 if (restrictBackground == mRestrictBackground) {
2049 // Ideally, UI should never allow this scenario...
2050 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2051 return;
2052 }
Felipe Lemef0823852016-06-08 13:43:08 -07002053 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002054 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002055
Felipe Leme6a05eee2016-02-19 14:43:51 -08002056 } finally {
2057 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002058 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002059
2060 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2061 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002062 }
2063
Felipe Lemef0823852016-06-08 13:43:08 -07002064 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002065 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002066 final boolean oldRestrictBackground = mRestrictBackground;
2067 mRestrictBackground = restrictBackground;
2068 // Must whitelist foreground apps before turning data saver mode on.
2069 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2070 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002071 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002072 try {
2073 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2074 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2075 mRestrictBackground = oldRestrictBackground;
2076 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002077 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002078 return;
2079 }
2080 } catch (RemoteException e) {
2081 // ignored; service lives in system_server
2082 }
Felipe Lemef0823852016-06-08 13:43:08 -07002083 synchronized (mNetworkPoliciesSecondLock) {
2084 updateNotificationsNL();
2085 writePolicyAL();
2086 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002087 }
2088
Jeff Sharkey46645002011-07-27 21:11:21 -07002089 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002090 public void addRestrictBackgroundWhitelistedUid(int uid) {
2091 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002092 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002093 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002094 int changed;
2095 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002096 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002097 if (oldStatus) {
2098 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2099 return;
2100 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002101 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002102 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002103 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002104 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2105 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2106 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2107 + " from revoked restrict background whitelist");
2108 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2109 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002110 if (needFirewallRules) {
2111 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002112 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002113 }
2114 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002115 synchronized (mNetworkPoliciesSecondLock) {
2116 writePolicyAL();
2117 }
2118 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002119 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002120 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2121 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002122 }
2123
2124 @Override
2125 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2126 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002127 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002128 synchronized (mUidRulesFirstLock) {
2129 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002130 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002131 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2132 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002133 }
2134
Felipe Leme70c57c22016-03-29 10:45:13 -07002135 /**
2136 * Removes a uid from the restricted background whitelist, returning whether its current
2137 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2138 */
Felipe Lemef0823852016-06-08 13:43:08 -07002139 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002140 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002141 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002142 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002143 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2144 return false;
2145 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002146 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002147 if (oldStatus) {
2148 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2149 mRestrictBackgroundWhitelistUids.delete(uid);
2150 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002151 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2152 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2153 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2154 + " to revoked restrict background whitelist");
2155 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2156 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002157 if (needFirewallRules) {
2158 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002159 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002160 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002161 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002162 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002163 synchronized (mNetworkPoliciesSecondLock) {
2164 writePolicyAL();
2165 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002166 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002167 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2168 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002169 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002170 }
2171
2172 @Override
2173 public int[] getRestrictBackgroundWhitelistedUids() {
2174 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002175 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002176 final int size = mRestrictBackgroundWhitelistUids.size();
2177 final int[] whitelist = new int[size];
2178 for (int i = 0; i < size; i++) {
2179 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2180 }
2181 if (LOGV) {
2182 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2183 + mRestrictBackgroundWhitelistUids);
2184 }
2185 return whitelist;
2186 }
2187 }
2188
2189 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002190 public int getRestrictBackgroundByCaller() {
2191 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2192 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002193
Felipe Lemef0823852016-06-08 13:43:08 -07002194 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002195 // Must clear identity because getUidPolicy() is restricted to system.
2196 final long token = Binder.clearCallingIdentity();
2197 final int policy;
2198 try {
2199 policy = getUidPolicy(uid);
2200 } finally {
2201 Binder.restoreCallingIdentity(token);
2202 }
2203 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2204 // App is blacklisted.
2205 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2206 }
Felipe Leme1b103232016-01-22 09:44:57 -08002207 if (!mRestrictBackground) {
2208 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2209 }
2210 return mRestrictBackgroundWhitelistUids.get(uid)
2211 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2212 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2213 }
2214 }
2215
2216 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002217 public boolean getRestrictBackground() {
2218 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2219
Felipe Lemef0823852016-06-08 13:43:08 -07002220 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002221 return mRestrictBackground;
2222 }
2223 }
2224
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002225 @Override
2226 public void setDeviceIdleMode(boolean enabled) {
2227 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2228
Felipe Lemef0823852016-06-08 13:43:08 -07002229 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002230 if (mDeviceIdleMode != enabled) {
2231 mDeviceIdleMode = enabled;
2232 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002233 // Device idle change means we need to rebuild rules for all
2234 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002235 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002236 }
2237 if (enabled) {
2238 EventLogTags.writeDeviceIdleOnPhase("net");
2239 } else {
2240 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002241 }
2242 }
2243 }
2244 }
2245
Felipe Lemef0823852016-06-08 13:43:08 -07002246 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002247 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2248 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002249 if (policy.template.matches(ident)) {
2250 return policy;
2251 }
2252 }
2253 return null;
2254 }
2255
2256 @Override
2257 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2258 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2259
2260 // only returns usage summary, so we don't require caller to have
2261 // READ_NETWORK_USAGE_HISTORY.
2262 final long token = Binder.clearCallingIdentity();
2263 try {
2264 return getNetworkQuotaInfoUnchecked(state);
2265 } finally {
2266 Binder.restoreCallingIdentity(token);
2267 }
2268 }
2269
2270 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2271 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2272
2273 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002274 synchronized (mNetworkPoliciesSecondLock) {
2275 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002276 }
2277
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002278 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002279 // missing policy means we can't derive useful quota info
2280 return null;
2281 }
2282
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002283 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002284
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002285 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002286 final long start = computeLastCycleBoundary(currentTime, policy);
2287 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002288 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002289
2290 // report soft and hard limits under policy
2291 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2292 : NetworkQuotaInfo.NO_LIMIT;
2293 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2294 : NetworkQuotaInfo.NO_LIMIT;
2295
2296 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2297 }
2298
Jeff Sharkey46645002011-07-27 21:11:21 -07002299 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002300 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002301 if (state.networkInfo == null) {
2302 return false;
2303 }
2304
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002305 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2306
2307 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002308 synchronized (mNetworkPoliciesSecondLock) {
2309 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002310 }
2311
2312 if (policy != null) {
2313 return policy.metered;
2314 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002315 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002316 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002317 return true;
2318 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002319 return false;
2320 }
2321 }
2322
2323 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002324 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002325 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002326
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002327 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2328
Dianne Hackborn497175b2014-07-01 12:56:08 -07002329 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002330 for (String arg : args) {
2331 argSet.add(arg);
2332 }
2333
Felipe Lemef0823852016-06-08 13:43:08 -07002334 synchronized (mUidRulesFirstLock) {
2335 synchronized (mNetworkPoliciesSecondLock) {
2336 if (argSet.contains("--unsnooze")) {
2337 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2338 mNetworkPolicy.valueAt(i).clearSnooze();
2339 }
2340
2341 normalizePoliciesNL();
2342 updateNetworkEnabledNL();
2343 updateNetworkRulesNL();
2344 updateNotificationsNL();
2345 writePolicyAL();
2346
2347 fout.println("Cleared snooze timestamps");
2348 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002349 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002350
Felipe Lemef0823852016-06-08 13:43:08 -07002351 fout.print("System ready: "); fout.println(mSystemReady);
2352 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2353 fout.print("Restrict power: "); fout.println(mRestrictPower);
2354 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2355 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002356 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002357 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2358 fout.println(mNetworkPolicy.valueAt(i).toString());
2359 }
2360 fout.decreaseIndent();
2361
2362 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2363
2364 fout.println("Policy for UIDs:");
2365 fout.increaseIndent();
2366 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002367 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002368 final int uid = mUidPolicy.keyAt(i);
2369 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002370 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002371 fout.print(uid);
2372 fout.print(" policy=");
2373 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2374 fout.println();
2375 }
2376 fout.decreaseIndent();
2377
2378 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2379 if (size > 0) {
2380 fout.println("Power save whitelist (except idle) app ids:");
2381 fout.increaseIndent();
2382 for (int i = 0; i < size; i++) {
2383 fout.print("UID=");
2384 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2385 fout.print(": ");
2386 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2387 fout.println();
2388 }
2389 fout.decreaseIndent();
2390 }
2391
2392 size = mPowerSaveWhitelistAppIds.size();
2393 if (size > 0) {
2394 fout.println("Power save whitelist app ids:");
2395 fout.increaseIndent();
2396 for (int i = 0; i < size; i++) {
2397 fout.print("UID=");
2398 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2399 fout.print(": ");
2400 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2401 fout.println();
2402 }
2403 fout.decreaseIndent();
2404 }
2405
2406 size = mRestrictBackgroundWhitelistUids.size();
2407 if (size > 0) {
2408 fout.println("Restrict background whitelist uids:");
2409 fout.increaseIndent();
2410 for (int i = 0; i < size; i++) {
2411 fout.print("UID=");
2412 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2413 fout.println();
2414 }
2415 fout.decreaseIndent();
2416 }
2417
2418 size = mDefaultRestrictBackgroundWhitelistUids.size();
2419 if (size > 0) {
2420 fout.println("Default restrict background whitelist uids:");
2421 fout.increaseIndent();
2422 for (int i = 0; i < size; i++) {
2423 fout.print("UID=");
2424 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2425 fout.println();
2426 }
2427 fout.decreaseIndent();
2428 }
2429
2430 size = mRestrictBackgroundWhitelistRevokedUids.size();
2431 if (size > 0) {
2432 fout.println("Default restrict background whitelist uids revoked by users:");
2433 fout.increaseIndent();
2434 for (int i = 0; i < size; i++) {
2435 fout.print("UID=");
2436 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2437 fout.println();
2438 }
2439 fout.decreaseIndent();
2440 }
2441
2442 final SparseBooleanArray knownUids = new SparseBooleanArray();
2443 collectKeys(mUidState, knownUids);
2444 collectKeys(mUidRules, knownUids);
2445
2446 fout.println("Status for all known UIDs:");
2447 fout.increaseIndent();
2448 size = knownUids.size();
2449 for (int i = 0; i < size; i++) {
2450 final int uid = knownUids.keyAt(i);
2451 fout.print("UID=");
2452 fout.print(uid);
2453
2454 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2455 fout.print(" state=");
2456 fout.print(state);
2457 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2458 fout.print(" (fg)");
2459 } else {
2460 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2461 ? " (fg svc)" : " (bg)");
2462 }
2463
2464 final int uidRules = mUidRules.get(uid, RULE_NONE);
2465 fout.print(" rules=");
2466 fout.print(uidRulesToString(uidRules));
2467 fout.println();
2468 }
2469 fout.decreaseIndent();
2470
2471 fout.println("Status for just UIDs with rules:");
2472 fout.increaseIndent();
2473 size = mUidRules.size();
2474 for (int i = 0; i < size; i++) {
2475 final int uid = mUidRules.keyAt(i);
2476 fout.print("UID=");
2477 fout.print(uid);
2478 final int uidRules = mUidRules.get(uid, RULE_NONE);
2479 fout.print(" rules=");
2480 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002481 fout.println();
2482 }
2483 fout.decreaseIndent();
2484 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002485 }
2486 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002487
2488 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002489 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2490 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002491 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002492 this, in, out, err, args, resultReceiver);
2493 }
2494
2495 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002496 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002497 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2498
Felipe Lemef0823852016-06-08 13:43:08 -07002499 synchronized (mUidRulesFirstLock) {
2500 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002501 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002502 }
2503
Felipe Lemef0823852016-06-08 13:43:08 -07002504 private boolean isUidForegroundUL(int uid) {
2505 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002506 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2507 }
2508
Felipe Lemef0823852016-06-08 13:43:08 -07002509 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002510 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002511 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002512 }
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002515 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2516 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2517 }
2518
Felipe Lemef0823852016-06-08 13:43:08 -07002519 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002520 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002521 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002522 }
2523
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002524 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002525 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002526 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2527 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002528 */
Felipe Lemef0823852016-06-08 13:43:08 -07002529 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002530 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2531 if (oldUidState != uidState) {
2532 // state changed, push updated rules
2533 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002534 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002535 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2536 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002537 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002538 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002539 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002540 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002541 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002542 }
2543 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002544 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002545 }
Felipe Lemef0823852016-06-08 13:43:08 -07002546 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002547 }
Felipe Lemef0823852016-06-08 13:43:08 -07002548 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002549 }
2550 }
2551
Felipe Lemef0823852016-06-08 13:43:08 -07002552 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002553 final int index = mUidState.indexOfKey(uid);
2554 if (index >= 0) {
2555 final int oldUidState = mUidState.valueAt(index);
2556 mUidState.removeAt(index);
2557 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002558 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002559 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002560 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002561 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002562 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002563 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002564 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002565 }
Felipe Lemef0823852016-06-08 13:43:08 -07002566 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002567 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002568 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002569 }
2570 }
2571
Felipe Lemef28983d2016-03-25 12:18:23 -07002572 // adjust stats accounting based on foreground status
2573 private void updateNetworkStats(int uid, boolean uidForeground) {
2574 try {
2575 mNetworkStats.setUidForeground(uid, uidForeground);
2576 } catch (RemoteException e) {
2577 // ignored; service lives in system_server
2578 }
2579 }
2580
Felipe Lemef0823852016-06-08 13:43:08 -07002581 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002582 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002583 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002584 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002585 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002586 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002587 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002588 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002589 }
2590 }
2591
Jeff Sharkeya4620792011-05-20 15:29:23 -07002592 private void updateScreenOn() {
Felipe Lemef0823852016-06-08 13:43:08 -07002593 synchronized (mUidRulesFirstLock) {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002594 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002595 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002596 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002597 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002598 }
Felipe Lemef0823852016-06-08 13:43:08 -07002599 updateRulesForScreenUL();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002600 }
2601 }
2602
2603 /**
2604 * Update rules that might be changed by {@link #mScreenOn} value.
2605 */
Felipe Lemef0823852016-06-08 13:43:08 -07002606 private void updateRulesForScreenUL() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002607 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002608 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002609 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002610 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002611 final int uid = mUidState.keyAt(i);
Felipe Lemef0823852016-06-08 13:43:08 -07002612 updateRestrictionRulesForUidUL(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002613 }
2614 }
2615 }
2616
Felipe Leme011b98f2016-02-10 17:28:31 -08002617 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002618 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2619 }
2620
Felipe Lemef0823852016-06-08 13:43:08 -07002621 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002622 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2623 }
2624
Felipe Lemef0823852016-06-08 13:43:08 -07002625 void updateRulesForPowerSaveUL() {
2626 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002627 mUidFirewallPowerSaveRules);
2628 }
2629
Felipe Lemef0823852016-06-08 13:43:08 -07002630 void updateRuleForRestrictPowerUL(int uid) {
2631 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002632 }
2633
Felipe Lemef0823852016-06-08 13:43:08 -07002634 void updateRulesForDeviceIdleUL() {
2635 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002636 mUidFirewallDozableRules);
2637 }
2638
Felipe Lemef0823852016-06-08 13:43:08 -07002639 void updateRuleForDeviceIdleUL(int uid) {
2640 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002641 }
2642
Felipe Lemef28983d2016-03-25 12:18:23 -07002643 // NOTE: since both fw_dozable and fw_powersave uses the same map
2644 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002645 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002646 SparseIntArray rules) {
2647 if (enabled) {
2648 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002649 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002650 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002651 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002652 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002653 for (int ui = users.size() - 1; ui >= 0; ui--) {
2654 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002655 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002656 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2657 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2658 int uid = UserHandle.getUid(user.id, appId);
2659 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2660 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002661 }
2662 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2663 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2664 int uid = UserHandle.getUid(user.id, appId);
2665 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2666 }
2667 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002668 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002669 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002670 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2671 }
2672 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002673 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002674 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002675
Felipe Lemef0823852016-06-08 13:43:08 -07002676 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002677 }
2678
Felipe Lemef0823852016-06-08 13:43:08 -07002679 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002680 final int appId = UserHandle.getAppId(uid);
2681 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2682 }
2683
Felipe Lemef28983d2016-03-25 12:18:23 -07002684 // NOTE: since both fw_dozable and fw_powersave uses the same map
2685 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002686 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002687 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002688 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002689 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2690 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002691 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002692 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002693 }
2694 }
2695 }
2696
Felipe Lemef0823852016-06-08 13:43:08 -07002697 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002698 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2699 uidRules.clear();
2700
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002701 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002702 final List<UserInfo> users = mUserManager.getUsers();
2703 for (int ui = users.size() - 1; ui >= 0; ui--) {
2704 UserInfo user = users.get(ui);
2705 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2706 for (int uid : idleUids) {
2707 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002708 // quick check: if this uid doesn't have INTERNET permission, it
2709 // doesn't have network access anyway, so it is a waste to mess
2710 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002711 if (hasInternetPermissions(uid)) {
2712 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002713 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002714 }
2715 }
2716 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002717
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002718 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2719 }
2720
Felipe Lemef0823852016-06-08 13:43:08 -07002721 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002722 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002723
2724 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002725 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002726 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002727 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2728 } else {
2729 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2730 }
2731 }
2732
Felipe Lemef0823852016-06-08 13:43:08 -07002733 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002734 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002735 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002736 }
2737
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002738 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002739 * Update rules that might be changed by {@link #mRestrictBackground},
2740 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002741 */
Felipe Lemef0823852016-06-08 13:43:08 -07002742 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002743 long start;
2744 if (LOGD) start = System.currentTimeMillis();
2745
Felipe Lemef0823852016-06-08 13:43:08 -07002746 updateRulesForRestrictPowerUL();
2747 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002748
2749 // If the set of restricted networks may have changed, re-evaluate those.
2750 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002751 normalizePoliciesNL();
2752 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002753 }
2754 if (LOGD) {
2755 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002756 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002757 + delta + "ms");
2758 }
2759 }
2760
Felipe Lemef0823852016-06-08 13:43:08 -07002761 private void updateRulesForRestrictPowerUL() {
2762 updateRulesForDeviceIdleUL();
2763 updateRulesForAppIdleUL();
2764 updateRulesForPowerSaveUL();
2765 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002766 }
2767
Felipe Lemef0823852016-06-08 13:43:08 -07002768 private void updateRulesForRestrictBackgroundUL() {
2769 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002770 }
2771
2772 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2773 private static final int TYPE_RESTRICT_POWER = 2;
2774 @Retention(RetentionPolicy.SOURCE)
2775 @IntDef(flag = false, value = {
2776 TYPE_RESTRICT_BACKGROUND,
2777 TYPE_RESTRICT_POWER,
2778 })
2779 public @interface RestrictType {
2780 }
2781
2782 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002783 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002784 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002785
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002786 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002787 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002788 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002789 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2790 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2791 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002792
Felipe Leme03e689d2016-03-02 16:17:38 -08002793 final int usersSize = users.size();
2794 final int appsSize = apps.size();
2795 for (int i = 0; i < usersSize; i++) {
2796 final UserInfo user = users.get(i);
2797 for (int j = 0; j < appsSize; j++) {
2798 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002799 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002800 switch (type) {
2801 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002802 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002803 break;
2804 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002805 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002806 break;
2807 default:
2808 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2809 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002810 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002811 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002812 }
2813
Felipe Lemef0823852016-06-08 13:43:08 -07002814 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002815 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002816 for (int i = 0; i < users.size(); i++) {
2817 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002818 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002819 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002820 int uid = UserHandle.getUid(user.id, appId);
Felipe Lemef0823852016-06-08 13:43:08 -07002821 updateRulesForRestrictPowerUL();
Felipe Leme781ba142016-05-09 16:24:48 -07002822 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002823 updateRuleForAppIdleUL(uid);
2824 updateRuleForDeviceIdleUL(uid);
2825 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002826 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002827 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002828 }
2829 }
2830 }
2831
Felipe Leme70c57c22016-03-29 10:45:13 -07002832 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2833 // methods below could be merged into a isUidValidForRules() method.
2834 private boolean isUidValidForBlacklistRules(int uid) {
2835 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002836 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002837 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002838 return true;
2839 }
2840
2841 return false;
2842 }
2843
Felipe Leme70c57c22016-03-29 10:45:13 -07002844 private boolean isUidValidForWhitelistRules(int uid) {
2845 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2846 }
2847
Amith Yamasani15e472352015-04-24 19:06:07 -07002848 private boolean isUidIdle(int uid) {
2849 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2850 final int userId = UserHandle.getUserId(uid);
2851
songjinshi0655edd2016-05-18 19:55:32 +08002852 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002853 for (String packageName : packages) {
2854 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2855 return false;
2856 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002857 }
2858 }
2859 return true;
2860 }
2861
2862 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002863 * Checks if an uid has INTERNET permissions.
2864 * <p>
2865 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002866 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002867 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002868 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002869 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002870 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002871 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002872 }
2873 } catch (RemoteException e) {
2874 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002875 return true;
2876 }
2877
2878 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002879 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002880 *
Felipe Leme781ba142016-05-09 16:24:48 -07002881 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002882 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002883 * <li>Doze mode
2884 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002885 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002886 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002887 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002888 *
2889 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002890 */
Felipe Lemef0823852016-06-08 13:43:08 -07002891 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002892 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002893 updateRuleForDeviceIdleUL(uid);
2894 updateRuleForAppIdleUL(uid);
2895 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002896
2897 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002898 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002899
2900 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002901 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002902 }
2903
Felipe Leme70c57c22016-03-29 10:45:13 -07002904 /**
2905 * Applies network rules to bandwidth controllers based on process state and user-defined
2906 * restrictions (blacklist / whitelist).
2907 *
2908 * <p>
2909 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2910 * networks:
2911 * <ul>
2912 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2913 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2914 * also blacklisted.
2915 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2916 * no UIDs other those whitelisted will have access.
2917 * <ul>
2918 *
2919 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2920 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2921 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2922 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002923 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002924 * {@link INetworkManagementService}, but this method should also be called in events (like
2925 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2926 * following rules should also be applied:
2927 *
2928 * <ul>
2929 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2930 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2931 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2932 * {@code bw_penalty_box}.
2933 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2934 * </ul>
2935 *
2936 * <p>For optimization, the rules are only applied on user apps that have internet access
2937 * permission, since there is no need to change the {@code iptables} rule if the app does not
2938 * have permission to use the internet.
2939 *
2940 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002941 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002942 */
Felipe Lemef0823852016-06-08 13:43:08 -07002943 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2944 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002945 }
2946
2947 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002948 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002949 * app is removed - it ignores the UID validity check.
2950 */
Felipe Lemef0823852016-06-08 13:43:08 -07002951 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002952 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2953 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2954 return;
2955 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002956
Dianne Hackborn497175b2014-07-01 12:56:08 -07002957 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002958 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002959 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002960
Felipe Leme781ba142016-05-09 16:24:48 -07002961 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2962 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2963 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2964 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002965
Felipe Leme70c57c22016-03-29 10:45:13 -07002966 // First step: define the new rule based on user restrictions and foreground state.
2967 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002968 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2969 newRule = RULE_TEMPORARY_ALLOW_METERED;
2970 } else if (isWhitelisted) {
2971 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002972 }
2973 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002974 if (isBlacklisted) {
2975 newRule = RULE_REJECT_METERED;
2976 } else if (mRestrictBackground && isWhitelisted) {
2977 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002978 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002979 }
Felipe Leme781ba142016-05-09 16:24:48 -07002980 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002981
Felipe Lemef28983d2016-03-25 12:18:23 -07002982 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002983 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002984 + ": isForeground=" +isForeground
2985 + ", isBlacklisted=" + isBlacklisted
2986 + ", isWhitelisted=" + isWhitelisted
2987 + ", oldRule=" + uidRulesToString(oldRule)
2988 + ", newRule=" + uidRulesToString(newRule)
2989 + ", newUidRules=" + uidRulesToString(newUidRules)
2990 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002991 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002992
Felipe Leme46c4fc32016-05-04 09:21:43 -07002993 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002994 mUidRules.delete(uid);
2995 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002996 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002997 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002998
Felipe Lemed31a97f2016-05-06 14:53:50 -07002999 boolean changed = false;
3000
Felipe Leme70c57c22016-03-29 10:45:13 -07003001 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003002 if (newRule != oldRule) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003003 changed = true;
3004
Felipe Leme781ba142016-05-09 16:24:48 -07003005 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003006 // Temporarily whitelist foreground app, removing from blacklist if necessary
3007 // (since bw_penalty_box prevails over bw_happy_box).
3008
3009 setMeteredNetworkWhitelist(uid, true);
3010 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3011 // but ideally it should be just:
3012 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003013 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003014 setMeteredNetworkBlacklist(uid, false);
3015 }
Felipe Leme781ba142016-05-09 16:24:48 -07003016 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003017 // Remove temporary whitelist from app that is not on foreground anymore.
3018
3019 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3020 // but ideally they should be just:
3021 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3022 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003023 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003024 setMeteredNetworkWhitelist(uid, false);
3025 }
Felipe Leme781ba142016-05-09 16:24:48 -07003026 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003027 setMeteredNetworkBlacklist(uid, true);
3028 }
Felipe Leme781ba142016-05-09 16:24:48 -07003029 } else if ((newRule & RULE_REJECT_METERED) != 0
3030 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003031 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003032 setMeteredNetworkBlacklist(uid, isBlacklisted);
3033 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003034 // Since blacklist prevails over whitelist, we need to handle the special case
3035 // where app is whitelisted and blacklisted at the same time (although such
3036 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003037 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003038 }
Felipe Leme781ba142016-05-09 16:24:48 -07003039 } else if ((newRule & RULE_ALLOW_METERED) != 0
3040 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003041 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003042 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003043 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003044 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003045 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3046 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003047 + ", whitelisted=" + isWhitelisted
3048 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003049 + ", newRule=" + uidRulesToString(newUidRules)
3050 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003051 }
Felipe Leme781ba142016-05-09 16:24:48 -07003052
3053 // Dispatch changed rule to existing listeners.
3054 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3055 }
3056 }
3057
3058 /**
3059 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3060 * listeners in case of change.
3061 * <p>
3062 * There are 3 power-related rules that affects whether an app has background access on
3063 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3064 * restriction, it's added to the equivalent firewall chain:
3065 * <ul>
3066 * <li>App is idle: {@code fw_standby} firewall chain.
3067 * <li>Device is idle: {@code fw_dozable} firewall chain.
3068 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3069 * </ul>
3070 * <p>
3071 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3072 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3073 * <p>
3074 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3075 */
Felipe Lemef0823852016-06-08 13:43:08 -07003076 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003077 if (!isUidValidForBlacklistRules(uid)) {
3078 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3079 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003080 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003081
Felipe Leme781ba142016-05-09 16:24:48 -07003082 final boolean isIdle = isUidIdle(uid);
3083 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
3084 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
3085 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003086 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003087
Felipe Lemef0823852016-06-08 13:43:08 -07003088 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003089 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3090 int newRule = RULE_NONE;
3091
3092 // First step: define the new rule based on user restrictions and foreground state.
3093
3094 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3095 // by considering the foreground and non-foreground states.
3096 if (isForeground) {
3097 if (restrictMode) {
3098 newRule = RULE_ALLOW_ALL;
3099 }
3100 } else if (restrictMode) {
3101 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3102 }
3103
3104 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3105
3106 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003107 Log.v(TAG, "updateRulesForNonMeteredNetworksUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003108 + ", isIdle: " + isIdle
3109 + ", mRestrictPower: " + mRestrictPower
3110 + ", mDeviceIdleMode: " + mDeviceIdleMode
3111 + ", isForeground=" + isForeground
3112 + ", isWhitelisted=" + isWhitelisted
3113 + ", oldRule=" + uidRulesToString(oldRule)
3114 + ", newRule=" + uidRulesToString(newRule)
3115 + ", newUidRules=" + uidRulesToString(newUidRules)
3116 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3117 }
3118
3119 if (newUidRules == RULE_NONE) {
3120 mUidRules.delete(uid);
3121 } else {
3122 mUidRules.put(uid, newUidRules);
3123 }
3124
3125 // Second step: notify listeners if state changed.
3126 if (newRule != oldRule) {
3127 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003128 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003129 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003130 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3131 } else {
3132 // All scenarios should have been covered above
3133 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3134 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003135 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003136 + ", newRule=" + uidRulesToString(newUidRules)
3137 + ", oldRule=" + uidRulesToString(oldUidRules));
3138 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003139 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003140 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003141 }
3142
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003143 private class AppIdleStateChangeListener
3144 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3145
3146 @Override
3147 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3148 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003149 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3150 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003151 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003152 synchronized (mUidRulesFirstLock) {
3153 updateRuleForAppIdleUL(uid);
3154 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003155 }
3156 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003157 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003158 }
3159
3160 @Override
3161 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003162 synchronized (mUidRulesFirstLock) {
3163 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003164 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003165 }
3166 }
3167
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003168 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3169 if (listener != null) {
3170 try {
3171 listener.onUidRulesChanged(uid, uidRules);
3172 } catch (RemoteException ignored) {
3173 }
3174 }
3175 }
3176
3177 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3178 String[] meteredIfaces) {
3179 if (listener != null) {
3180 try {
3181 listener.onMeteredIfacesChanged(meteredIfaces);
3182 } catch (RemoteException ignored) {
3183 }
3184 }
3185 }
3186
3187 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3188 boolean restrictBackground) {
3189 if (listener != null) {
3190 try {
3191 listener.onRestrictBackgroundChanged(restrictBackground);
3192 } catch (RemoteException ignored) {
3193 }
3194 }
3195 }
3196
3197 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3198 int uid, boolean whitelisted) {
3199 if (listener != null) {
3200 try {
3201 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3202 } catch (RemoteException ignored) {
3203 }
3204 }
3205 }
3206
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003207 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3208 int uid, boolean blacklisted) {
3209 if (listener != null) {
3210 try {
3211 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3212 } catch (RemoteException ignored) {
3213 }
3214 }
3215 }
3216
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003217 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003218 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003219 public boolean handleMessage(Message msg) {
3220 switch (msg.what) {
3221 case MSG_RULES_CHANGED: {
3222 final int uid = msg.arg1;
3223 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003224 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003225 final int length = mListeners.beginBroadcast();
3226 for (int i = 0; i < length; i++) {
3227 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003228 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003229 }
3230 mListeners.finishBroadcast();
3231 return true;
3232 }
3233 case MSG_METERED_IFACES_CHANGED: {
3234 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003235 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003236 final int length = mListeners.beginBroadcast();
3237 for (int i = 0; i < length; i++) {
3238 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003239 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003240 }
3241 mListeners.finishBroadcast();
3242 return true;
3243 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003244 case MSG_LIMIT_REACHED: {
3245 final String iface = (String) msg.obj;
3246
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003247 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003248 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003249 if (mMeteredIfaces.contains(iface)) {
3250 try {
3251 // force stats update to make sure we have
3252 // numbers that caused alert to trigger.
3253 mNetworkStats.forceUpdate();
3254 } catch (RemoteException e) {
3255 // ignored; service lives in system_server
3256 }
3257
Felipe Lemef0823852016-06-08 13:43:08 -07003258 updateNetworkEnabledNL();
3259 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003260 }
3261 }
3262 return true;
3263 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003264 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3265 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003266 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003267 final int length = mListeners.beginBroadcast();
3268 for (int i = 0; i < length; i++) {
3269 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003270 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003271 }
3272 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003273 final Intent intent =
3274 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3275 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3276 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3277 return true;
3278 }
3279 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003280 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3281 // - when an app is whitelisted
3282 // - when an app is blacklisted
3283 //
3284 // Whether the internal listeners (INetworkPolicyListener implementations) or
3285 // app broadcast receivers are notified depend on the following rules:
3286 //
3287 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3288 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3289 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003290 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003291 final boolean changed = msg.arg2 == 1;
3292 final Boolean whitelisted = (Boolean) msg.obj;
3293
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003294 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003295 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003296 final boolean whitelistedBool = whitelisted.booleanValue();
3297 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3298 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003299 final int length = mListeners.beginBroadcast();
3300 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003301 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003302 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3303 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003304 }
3305 mListeners.finishBroadcast();
3306 }
Felipe Leme9778f762016-01-27 14:46:39 -08003307 final PackageManager pm = mContext.getPackageManager();
3308 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003309 if (changed && packages != null) {
3310 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003311 final int userId = UserHandle.getUserId(uid);
3312 for (String packageName : packages) {
3313 final Intent intent = new Intent(
3314 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3315 intent.setPackage(packageName);
3316 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3317 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3318 }
Felipe Leme9778f762016-01-27 14:46:39 -08003319 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003320 return true;
3321 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003322 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3323 final int uid = msg.arg1;
3324 final boolean blacklisted = msg.arg2 == 1;
3325
3326 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3327 blacklisted);
3328 final int length = mListeners.beginBroadcast();
3329 for (int i = 0; i < length; i++) {
3330 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3331 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3332 blacklisted);
3333 }
3334 mListeners.finishBroadcast();
3335 return true;
3336 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003337 case MSG_ADVISE_PERSIST_THRESHOLD: {
3338 final long lowestRule = (Long) msg.obj;
3339 try {
3340 // make sure stats are recorded frequently enough; we aim
3341 // for 2MB threshold for 2GB/month rules.
3342 final long persistThreshold = lowestRule / 1000;
3343 mNetworkStats.advisePersistThreshold(persistThreshold);
3344 } catch (RemoteException e) {
3345 // ignored; service lives in system_server
3346 }
3347 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003348 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003349 case MSG_SCREEN_ON_CHANGED: {
3350 updateScreenOn();
3351 return true;
3352 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003353 case MSG_UPDATE_INTERFACE_QUOTA: {
3354 removeInterfaceQuota((String) msg.obj);
3355 // int params need to be stitched back into a long
3356 setInterfaceQuota((String) msg.obj,
3357 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3358 return true;
3359 }
3360 case MSG_REMOVE_INTERFACE_QUOTA: {
3361 removeInterfaceQuota((String) msg.obj);
3362 return true;
3363 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003364 default: {
3365 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003366 }
3367 }
3368 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003369 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003370
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003371 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003372 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003373 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003374 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003375 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003376 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003377 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003378 }
3379 }
3380
3381 private void removeInterfaceQuota(String iface) {
3382 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003383 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003384 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003385 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003386 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003387 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003388 }
3389 }
3390
Felipe Leme70c57c22016-03-29 10:45:13 -07003391 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3392 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003393 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003394 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003395 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003396 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3397 } catch (RemoteException e) {
3398 // ignored; service lives in system_server
3399 }
3400 }
3401
3402 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3403 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3404 try {
3405 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3406 } catch (IllegalStateException e) {
3407 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003408 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003409 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003410 }
3411 }
3412
Amith Yamasani15e472352015-04-24 19:06:07 -07003413 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003414 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3415 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3416 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003417 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003418 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003419 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003420 int size = uidRules.size();
3421 int[] uids = new int[size];
3422 int[] rules = new int[size];
3423 for(int index = size - 1; index >= 0; --index) {
3424 uids[index] = uidRules.keyAt(index);
3425 rules[index] = uidRules.valueAt(index);
3426 }
3427 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003428 } catch (IllegalStateException e) {
3429 Log.wtf(TAG, "problem setting firewall uid rules", e);
3430 } catch (RemoteException e) {
3431 // ignored; service lives in system_server
3432 }
3433 }
3434
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003435 /**
3436 * Add or remove a uid to the firewall blacklist for all network ifaces.
3437 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003438 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003439 if (chain == FIREWALL_CHAIN_DOZABLE) {
3440 mUidFirewallDozableRules.put(uid, rule);
3441 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3442 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003443 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3444 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003445 }
3446
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003447 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003448 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003449 } catch (IllegalStateException e) {
3450 Log.wtf(TAG, "problem setting firewall uid rules", e);
3451 } catch (RemoteException e) {
3452 // ignored; service lives in system_server
3453 }
3454 }
3455
3456 /**
3457 * Add or remove a uid to the firewall blacklist for all network ifaces.
3458 */
Felipe Lemef0823852016-06-08 13:43:08 -07003459 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003460 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3461 mFirewallChainStates.get(chain) == enable) {
3462 // All is the same, nothing to do.
3463 return;
3464 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003465 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003466 try {
3467 mNetworkManager.setFirewallChainEnabled(chain, enable);
3468 } catch (IllegalStateException e) {
3469 Log.wtf(TAG, "problem enable firewall chain", e);
3470 } catch (RemoteException e) {
3471 // ignored; service lives in system_server
3472 }
3473 }
3474
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003475 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3476 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003477 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003478 } catch (RuntimeException e) {
3479 Slog.w(TAG, "problem reading network stats: " + e);
3480 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003481 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003482 // ignored; service lives in system_server
3483 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003484 }
3485 }
3486
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003487 private boolean isBandwidthControlEnabled() {
3488 final long token = Binder.clearCallingIdentity();
3489 try {
3490 return mNetworkManager.isBandwidthControlEnabled();
3491 } catch (RemoteException e) {
3492 // ignored; service lives in system_server
3493 return false;
3494 } finally {
3495 Binder.restoreCallingIdentity(token);
3496 }
3497 }
3498
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003499 /**
3500 * Try refreshing {@link #mTime} when stale.
3501 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003502 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003503 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003504 mTime.forceRefresh();
3505 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003506 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003507
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003508 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003509 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3510 }
3511
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003512 private static Intent buildAllowBackgroundDataIntent() {
3513 return new Intent(ACTION_ALLOW_BACKGROUND);
3514 }
3515
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003516 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3517 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3518 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3519 return intent;
3520 }
3521
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003522 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3523 final Intent intent = new Intent();
3524 intent.setComponent(new ComponentName(
3525 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3526 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3527 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3528 return intent;
3529 }
3530
3531 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3532 final Intent intent = new Intent();
3533 intent.setComponent(new ComponentName(
3534 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3535 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3536 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3537 return intent;
3538 }
3539
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003540 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003541 public void addIdleHandler(IdleHandler handler) {
3542 mHandler.getLooper().getQueue().addIdleHandler(handler);
3543 }
3544
Jeff Sharkey1b861272011-05-22 00:34:52 -07003545 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3546 final int size = source.size();
3547 for (int i = 0; i < size; i++) {
3548 target.put(source.keyAt(i), true);
3549 }
3550 }
3551
Stuart Scottf1fb3972015-04-02 18:00:02 -07003552 @Override
3553 public void factoryReset(String subscriber) {
3554 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3555
Stuart Scotte3e314d2015-04-20 14:07:45 -07003556 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3557 return;
3558 }
3559
Stuart Scottf1fb3972015-04-02 18:00:02 -07003560 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003561 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003562 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3563 for (NetworkPolicy policy : policies) {
3564 if (policy.template.equals(template)) {
3565 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3566 policy.inferred = false;
3567 policy.clearSnooze();
3568 }
3569 }
3570 setNetworkPolicies(policies);
3571
3572 // Turn restrict background data off
3573 setRestrictBackground(false);
3574
Stuart Scotte3e314d2015-04-20 14:07:45 -07003575 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3576 // Remove app's "restrict background data" flag
3577 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3578 setUidPolicy(uid, POLICY_NONE);
3579 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003580 }
3581 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003582
3583 private class MyPackageMonitor extends PackageMonitor {
3584
3585 @Override
3586 public void onPackageRemoved(String packageName, int uid) {
3587 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003588 synchronized (mUidRulesFirstLock) {
3589 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3590 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003591 }
3592 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003593 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003594
3595 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3596
3597 @Override
3598 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003599 synchronized (mUidRulesFirstLock) {
3600 boolean changed = removeUserStateUL(userId, false);
3601 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003602 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003603 synchronized (mNetworkPoliciesSecondLock) {
3604 writePolicyAL();
3605 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003606 }
3607 }
3608 }
3609 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003610}