blob: d5da66be3860abf3c2fc423f04465186fdf28fc4 [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 Sharkey4414cea2011-06-24 17:05:24 -0700136import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700137import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700141import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600142import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700144import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700145import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700146import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800147import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700148import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700149import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700150import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700151import android.util.ArrayMap;
152import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700153import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700154import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700155import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700156import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700157import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700158import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700159import android.util.SparseBooleanArray;
160import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161import android.util.TrustedTime;
162import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700163
Jeff Sharkey497e4432011-06-14 17:27:29 -0700164import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700165import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800166import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800167import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800168import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700169import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700170import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700171import com.android.server.DeviceIdleController;
172import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700173import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800174import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600175
176import libcore.io.IoUtils;
177
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179
180import org.xmlpull.v1.XmlPullParser;
181import org.xmlpull.v1.XmlPullParserException;
182import org.xmlpull.v1.XmlSerializer;
183
184import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700185import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import java.io.FileInputStream;
187import java.io.FileNotFoundException;
188import java.io.FileOutputStream;
189import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700190import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700191import java.lang.annotation.Retention;
192import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100193import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700194import java.util.ArrayList;
195import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700196import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700198/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700199 * Service that maintains low-level network policy rules, using
200 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700201 * <p>
202 * Derives active rules by combining a given policy with other system status,
203 * and delivers to listeners, such as {@link ConnectivityManager}, for
204 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700205 *
206 * <p>
207 * This class uses 2-3 locks to synchronize state:
208 * <ul>
209 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
210 * rules).
211 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
212 * as network policies).
213 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
214 * must be held.
215 * </ul>
216 *
217 * <p>
218 * As such, methods that require synchronization have the following prefixes:
219 * <ul>
220 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
221 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
222 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
223 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
224 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700225 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700226public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800227 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700228 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700229 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700230
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700231 private static final int VERSION_INIT = 1;
232 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700233 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800234 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800235 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800236 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700237 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700238 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700239 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700240 private static final int VERSION_SWITCH_UID = 10;
241 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700242
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800243 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700244 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700248 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700249
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700250 private static final String TAG_POLICY_LIST = "policy-list";
251 private static final String TAG_NETWORK_POLICY = "network-policy";
252 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700253 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800254 private static final String TAG_WHITELIST = "whitelist";
255 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800256 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700257
258 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700259 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700260 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
261 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700262 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800264 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265 private static final String ATTR_WARNING_BYTES = "warningBytes";
266 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700267 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800268 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
269 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800270 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700271 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700272 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700273 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_POLICY = "policy";
275
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800277 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800279 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700280
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700281 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
282
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700283 private static final int MSG_RULES_CHANGED = 1;
284 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800285 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800286 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700287 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Felipe Leme9778f762016-01-27 14:46:39 -0800288 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700289 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
290 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700291 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700292
Jeff Sharkey75279902011-05-24 18:39:45 -0700293 private final Context mContext;
294 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700295 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700296 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700297 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700298 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700299 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700300
301 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700302 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700303 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700304 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700305
Felipe Lemef0823852016-06-08 13:43:08 -0700306 // See main javadoc for instructions on how to use these locks.
307 final Object mUidRulesFirstLock = new Object();
308 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700309
Felipe Lemef0823852016-06-08 13:43:08 -0700310 @GuardedBy("allLocks") volatile boolean mSystemReady;
311
Felipe Lemef0823852016-06-08 13:43:08 -0700312 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
313 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
314 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700315
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700316 private final boolean mSuppressDefaultPolicy;
317
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700318 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800319 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700320 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800321 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700322
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700323 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700324 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700325 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700326 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700327
Felipe Lemef0823852016-06-08 13:43:08 -0700328 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700329 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700330 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700331 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700332 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800333 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700334
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700335 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700337 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
338
Jeff Sharkey32566012014-12-02 18:30:14 -0800339 /**
340 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700341 * in power save mode, except device idle (doze) still applies.
342 * TODO: An int array might be sufficient
343 */
Felipe Lemef0823852016-06-08 13:43:08 -0700344 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700345 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
346
347 /**
348 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700350 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800351 */
Felipe Lemef0823852016-06-08 13:43:08 -0700352 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700353 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700354
Felipe Lemef0823852016-06-08 13:43:08 -0700355 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700356 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
357
Felipe Lemeb85a6372016-01-14 16:16:16 -0800358 /**
359 * UIDs that have been white-listed to avoid restricted background.
360 */
Felipe Lemef0823852016-06-08 13:43:08 -0700361 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800362 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
363
Felipe Lemea9505cc2016-02-26 10:28:41 -0800364 /**
365 * UIDs that have been initially white-listed by system to avoid restricted background.
366 */
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800368 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
369 new SparseBooleanArray();
370
371 /**
372 * UIDs that have been initially white-listed by system to avoid restricted background,
373 * but later revoked by user.
374 */
Felipe Lemef0823852016-06-08 13:43:08 -0700375 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800376 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
377 new SparseBooleanArray();
378
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700379 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700380 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800381 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700382 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800384 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700385
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700386 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700388 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700389
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700390 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800392 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700393
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600394 /** Higher priority listener before general event dispatch */
395 private INetworkPolicyListener mConnectivityListener;
396
Jeff Sharkey32566012014-12-02 18:30:14 -0800397 private final RemoteCallbackList<INetworkPolicyListener>
398 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700399
Dianne Hackborn497175b2014-07-01 12:56:08 -0700400 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401
Felipe Lemef0823852016-06-08 13:43:08 -0700402 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700404
Svet Ganov16a16892015-04-16 10:32:04 -0700405 private final AppOpsManager mAppOps;
406
Felipe Lemeb85a6372016-01-14 16:16:16 -0800407 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800408 private final IPackageManager mIPm;
409
Felipe Lemeb85a6372016-01-14 16:16:16 -0800410
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700411 // TODO: keep whitelist of system-critical services that should never have
412 // rules enforced, such as system, phone, and radio UIDs.
413
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700414 // TODO: migrate notifications to SystemUI
415
Jeff Sharkey75279902011-05-24 18:39:45 -0700416 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Lemef8dd7b42016-08-10 13:00:32 -0700417 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
418 this(context, activityManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700419 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700420 }
421
422 private static File getSystemDir() {
423 return new File(Environment.getDataDirectory(), "system");
424 }
425
426 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Lemef8dd7b42016-08-10 13:00:32 -0700427 INetworkStatsService networkStats, INetworkManagementService networkManagement,
428 TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700429 mContext = checkNotNull(context, "missing context");
430 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700431 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700432 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700433 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700434 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700435 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700436 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800437 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700438
Amith Yamasani450a16b2013-09-18 16:28:50 -0700439 HandlerThread thread = new HandlerThread(TAG);
440 thread.start();
441 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700442
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700443 mSuppressDefaultPolicy = suppressDefaultPolicy;
444
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700445 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700446
447 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800448
449 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700450
451 // Expose private service for system components to use.
452 LocalServices.addService(NetworkPolicyManagerInternal.class,
453 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700454 }
455
456 public void bindConnectivityManager(IConnectivityManager connManager) {
457 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700458 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700459
Jeff Sharkey497e4432011-06-14 17:27:29 -0700460 public void bindNotificationManager(INotificationManager notifManager) {
461 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
462 }
463
Felipe Lemef0823852016-06-08 13:43:08 -0700464 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700465 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700466 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
467 mPowerSaveWhitelistExceptIdleAppIds.clear();
468 if (whitelist != null) {
469 for (int uid : whitelist) {
470 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
471 }
472 }
473 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700474 mPowerSaveWhitelistAppIds.clear();
475 if (whitelist != null) {
476 for (int uid : whitelist) {
477 mPowerSaveWhitelistAppIds.put(uid, true);
478 }
479 }
480 } catch (RemoteException e) {
481 }
482 }
483
Felipe Lemea9505cc2016-02-26 10:28:41 -0800484 /**
485 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
486 * revoke the whitelist.
487 *
488 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
489 */
Felipe Lemef0823852016-06-08 13:43:08 -0700490 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800491 final List<UserInfo> users = mUserManager.getUsers();
492 final int numberUsers = users.size();
493
Felipe Lemea110eec2016-04-29 09:58:06 -0700494 boolean changed = false;
495 for (int i = 0; i < numberUsers; i++) {
496 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700497 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700498 }
499 return changed;
500 }
501
Felipe Lemef0823852016-06-08 13:43:08 -0700502 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700503 final SystemConfig sysConfig = SystemConfig.getInstance();
504 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800505 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
506 boolean changed = false;
507 for (int i = 0; i < allowDataUsage.size(); i++) {
508 final String pkg = allowDataUsage.valueAt(i);
509 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700510 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
511 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800512 final ApplicationInfo app;
513 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700514 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800515 } catch (PackageManager.NameNotFoundException e) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700516 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
517 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800518 continue;
519 }
520 if (!app.isPrivilegedApp()) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700521 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
522 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800523 continue;
524 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700525 final int uid = UserHandle.getUid(userId, app.uid);
526 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
527 if (LOGD)
528 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
529 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800530 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700531 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700532 if (LOGD)
533 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
534 + userId + ") to restrict background whitelist");
Felipe Lemea110eec2016-04-29 09:58:06 -0700535 mRestrictBackgroundWhitelistUids.append(uid, true);
536 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800537 }
538 }
539 return changed;
540 }
541
Felipe Lemef0823852016-06-08 13:43:08 -0700542 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700543 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700544 // Clear the states of the current whitelist
545 final int N = mPowerSaveTempWhitelistAppIds.size();
546 for (int i = 0; i < N; i++) {
547 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
548 }
549 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700550 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700551 if (whitelist != null) {
552 for (int uid : whitelist) {
553 mPowerSaveTempWhitelistAppIds.put(uid, true);
554 }
555 }
556 } catch (RemoteException e) {
557 }
558 }
559
Amith Yamasani06f08062015-06-12 13:23:33 -0700560 /**
561 * Remove unnecessary entries in the temp whitelist
562 */
Felipe Lemef0823852016-06-08 13:43:08 -0700563 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700564 final int N = mPowerSaveTempWhitelistAppIds.size();
565 for (int i = N - 1; i >= 0; i--) {
566 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
567 mPowerSaveTempWhitelistAppIds.removeAt(i);
568 }
569 }
570 }
571
Jeff Sharkeya4620792011-05-20 15:29:23 -0700572 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700573 if (!isBandwidthControlEnabled()) {
574 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
575 return;
576 }
577
Amith Yamasani15e472352015-04-24 19:06:07 -0700578 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
579
Felipe Lemeb85a6372016-01-14 16:16:16 -0800580 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
581
Felipe Lemef0823852016-06-08 13:43:08 -0700582 synchronized (mUidRulesFirstLock) {
583 synchronized (mNetworkPoliciesSecondLock) {
584 updatePowerSaveWhitelistUL();
585 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
586 mPowerManagerInternal.registerLowPowerModeObserver(
587 new PowerManagerInternal.LowPowerModeListener() {
588 @Override
589 public void onLowPowerModeChanged(boolean enabled) {
590 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
591 synchronized (mUidRulesFirstLock) {
592 if (mRestrictPower != enabled) {
593 mRestrictPower = enabled;
594 updateRulesForRestrictPowerUL();
595 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700596 }
597 }
Felipe Lemef0823852016-06-08 13:43:08 -0700598 });
599 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
600
601 mSystemReady = true;
602
603 // read policy from disk
604 readPolicyAL();
605
606 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
607 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700608 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700609
Felipe Lemef0823852016-06-08 13:43:08 -0700610 setRestrictBackgroundUL(mRestrictBackground);
611 updateRulesForGlobalChangeAL(false);
612 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800613 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700614 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700615
Jeff Sharkeya4620792011-05-20 15:29:23 -0700616 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700617 mActivityManager.registerUidObserver(mUidObserver,
618 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700619 mNetworkManager.registerObserver(mAlertObserver);
620 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700621 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700622 }
623
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700624 // listen for changes to power save whitelist
625 final IntentFilter whitelistFilter = new IntentFilter(
626 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
627 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
628
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700629 DeviceIdleController.LocalService deviceIdleService
630 = LocalServices.getService(DeviceIdleController.LocalService.class);
631 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
632
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700633 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900634 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700635 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
636
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700637 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700638 final IntentFilter packageFilter = new IntentFilter();
639 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700640 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700641 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700642
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700643 // listen for UID changes to update policy
644 mContext.registerReceiver(
645 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
646
647 // listen for user changes to update policy
648 final IntentFilter userFilter = new IntentFilter();
649 userFilter.addAction(ACTION_USER_ADDED);
650 userFilter.addAction(ACTION_USER_REMOVED);
651 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
652
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700653 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700654 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
655 mContext.registerReceiver(
656 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
657
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700658 // listen for restrict background changes from notifications
659 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
660 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
661
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800662 // listen for snooze warning from notifications
663 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
664 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
665 MANAGE_NETWORK_POLICY, mHandler);
666
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700667 // listen for configured wifi networks to be removed
668 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700669 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700670
671 // listen for wifi state changes to catch metered hint
672 final IntentFilter wifiStateFilter = new IntentFilter(
673 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700674 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700675
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700676 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700677
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700678 }
679
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700680 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700681 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700682 synchronized (mUidRulesFirstLock) {
683 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700684 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700685 }
686
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700687 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700688 synchronized (mUidRulesFirstLock) {
689 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700690 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700691 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700692
693 @Override public void onUidActive(int uid) throws RemoteException {
694 }
695
696 @Override public void onUidIdle(int uid) throws RemoteException {
697 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700698 };
699
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700700 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700701 @Override
702 public void onReceive(Context context, Intent intent) {
703 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700704 synchronized (mUidRulesFirstLock) {
705 updatePowerSaveWhitelistUL();
706 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700707 }
708 }
709 };
710
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700711 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
712 @Override
713 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700714 synchronized (mUidRulesFirstLock) {
715 updatePowerSaveTempWhitelistUL();
716 updateRulesForTempWhitelistChangeUL();
717 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700718 }
719 }
720 };
721
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700722 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700723 @Override
724 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700725 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700726
727 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700728 final int uid = intent.getIntExtra(EXTRA_UID, -1);
729 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700730
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700731 if (ACTION_PACKAGE_ADDED.equals(action)) {
732 // update rules for UID, since it might be subject to
733 // global background data policy
734 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700735 synchronized (mUidRulesFirstLock) {
736 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700737 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700738 }
739 }
740 };
741
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700742 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700743 @Override
744 public void onReceive(Context context, Intent intent) {
745 // on background handler thread, and UID_REMOVED is protected
746
747 final int uid = intent.getIntExtra(EXTRA_UID, -1);
748 if (uid == -1) return;
749
750 // remove any policy and update rules to clean up
751 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700752 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700753 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700754 updateRestrictionRulesForUidUL(uid);
755 synchronized (mNetworkPoliciesSecondLock) {
756 writePolicyAL();
757 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700758 }
759 }
760 };
761
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700762 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700763 @Override
764 public void onReceive(Context context, Intent intent) {
765 // on background handler thread, and USER_ADDED and USER_REMOVED
766 // broadcasts are protected
767
768 final String action = intent.getAction();
769 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
770 if (userId == -1) return;
771
Amith Yamasani15e472352015-04-24 19:06:07 -0700772 switch (action) {
773 case ACTION_USER_REMOVED:
774 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700775 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800776 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700777 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700778 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700779 if (action == ACTION_USER_ADDED) {
780 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700781 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700782 }
783 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700784 synchronized (mNetworkPoliciesSecondLock) {
785 updateRulesForGlobalChangeAL(true);
786 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700787 }
788 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700789 }
790 }
791 };
792
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700793 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700794 * Receiver that watches for {@link INetworkStatsService} updates, which we
795 * use to check against {@link NetworkPolicy#warningBytes}.
796 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700797 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700798 @Override
799 public void onReceive(Context context, Intent intent) {
800 // on background handler thread, and verified
801 // READ_NETWORK_USAGE_HISTORY permission above.
802
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800803 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700804 synchronized (mNetworkPoliciesSecondLock) {
805 updateNetworkEnabledNL();
806 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 }
808 }
809 };
810
811 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700812 * Receiver that watches for {@link Notification} control of
813 * {@link #mRestrictBackground}.
814 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700815 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700816 @Override
817 public void onReceive(Context context, Intent intent) {
818 // on background handler thread, and verified MANAGE_NETWORK_POLICY
819 // permission above.
820
821 setRestrictBackground(false);
822 }
823 };
824
825 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800826 * Receiver that watches for {@link Notification} control of
827 * {@link NetworkPolicy#lastWarningSnooze}.
828 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700829 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800830 @Override
831 public void onReceive(Context context, Intent intent) {
832 // on background handler thread, and verified MANAGE_NETWORK_POLICY
833 // permission above.
834
835 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
836 performSnooze(template, TYPE_WARNING);
837 }
838 };
839
840 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700841 * Receiver that watches for {@link WifiConfiguration} to be changed.
842 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700843 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700844 @Override
845 public void onReceive(Context context, Intent intent) {
846 // on background handler thread, and verified CONNECTIVITY_INTERNAL
847 // permission above.
848
849 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
850 if (reason == CHANGE_REASON_REMOVED) {
851 final WifiConfiguration config = intent.getParcelableExtra(
852 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700853 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800854 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700855 synchronized (mUidRulesFirstLock) {
856 synchronized (mNetworkPoliciesSecondLock) {
857 if (mNetworkPolicy.containsKey(template)) {
858 mNetworkPolicy.remove(template);
859 writePolicyAL();
860 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700861 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700862 }
863 }
864 }
865 }
866 };
867
868 /**
869 * Receiver that watches {@link WifiInfo} state changes to infer metered
870 * state. Ignores hints when policy is user-defined.
871 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700872 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700873 @Override
874 public void onReceive(Context context, Intent intent) {
875 // on background handler thread, and verified CONNECTIVITY_INTERNAL
876 // permission above.
877
878 // ignore when not connected
879 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
880 if (!netInfo.isConnected()) return;
881
882 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
883 final boolean meteredHint = info.getMeteredHint();
884
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800885 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700886 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700887 NetworkPolicy policy = mNetworkPolicy.get(template);
888 if (policy == null && meteredHint) {
889 // policy doesn't exist, and AP is hinting that it's
890 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800891 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700892 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700893
894 } else if (policy != null && policy.inferred) {
895 // policy exists, and was inferred: update its current
896 // metered state.
897 policy.metered = meteredHint;
898
899 // since this is inferred for each wifi session, just update
900 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700901 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700902 }
903 }
904 }
905 };
906
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800907 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
908 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
909 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
910 metered, true);
911 }
912
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700913 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700914 * Observer that watches for {@link INetworkManagementService} alerts.
915 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700916 final private INetworkManagementEventObserver mAlertObserver
917 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700918 @Override
919 public void limitReached(String limitName, String iface) {
920 // only someone like NMS should be calling us
921 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
922
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800923 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
924 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700925 }
926 }
927 };
928
929 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700930 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
931 * to show visible notifications as needed.
932 */
Felipe Lemef0823852016-06-08 13:43:08 -0700933 void updateNotificationsNL() {
934 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700935
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700936 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700937 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700938 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939
940 // TODO: when switching to kernel notifications, compute next future
941 // cycle boundary to recompute notifications.
942
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700943 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800944 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700945 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
946 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947 // ignore policies that aren't relevant to user
948 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700949 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 final long start = computeLastCycleBoundary(currentTime, policy);
952 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700953 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700954
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700955 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800956 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700957 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
958 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700959 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700960 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700961 }
962
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700964 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700965
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800966 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700968 }
969 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700970 }
971
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700973 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
974 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700975 if (!mActiveNotifs.contains(tag)) {
976 cancelNotification(tag);
977 }
978 }
979 }
980
981 /**
982 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700983 * current device state, such as when
984 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
985 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700986 */
987 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800988 if (template.isMatchRuleMobile()) {
989 final TelephonyManager tele = TelephonyManager.from(mContext);
990 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700991
Jeff Sharkey32566012014-12-02 18:30:14 -0800992 // Mobile template is relevant when any active subscriber matches
993 final int[] subIds = sub.getActiveSubscriptionIdList();
994 for (int subId : subIds) {
995 final String subscriberId = tele.getSubscriberId(subId);
996 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700997 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800998 if (template.matches(probeIdent)) {
999 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001000 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001001 }
1002 return false;
1003 } else {
1004 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001005 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006 }
1007
1008 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001009 * Notify that given {@link NetworkTemplate} is over
1010 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1011 */
Felipe Lemef0823852016-06-08 13:43:08 -07001012 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 if (!mOverLimitNotified.contains(template)) {
1014 mContext.startActivity(buildNetworkOverLimitIntent(template));
1015 mOverLimitNotified.add(template);
1016 }
1017 }
1018
Felipe Lemef0823852016-06-08 13:43:08 -07001019 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001020 mOverLimitNotified.remove(template);
1021 }
1022
1023 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001024 * Build unique tag that identifies an active {@link NetworkPolicy}
1025 * notification of a specific type, like {@link #TYPE_LIMIT}.
1026 */
1027 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001028 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001029 }
1030
1031 /**
1032 * Show notification for combined {@link NetworkPolicy} and specific type,
1033 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1034 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001035 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036 final String tag = buildNotificationTag(policy, type);
1037 final Notification.Builder builder = new Notification.Builder(mContext);
1038 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001039 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001040 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001041 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042
1043 final Resources res = mContext.getResources();
1044 switch (type) {
1045 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001047 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001049 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001050 builder.setTicker(title);
1051 builder.setContentTitle(title);
1052 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001053 builder.setDefaults(Notification.DEFAULT_ALL);
1054 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001055
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001056 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1057 builder.setDeleteIntent(PendingIntent.getBroadcast(
1058 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1059
1060 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001061 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001062 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1063
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064 break;
1065 }
1066 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1068
1069 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001070 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001071 switch (policy.template.getMatchRule()) {
1072 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001075 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001078 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001080 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001081 case MATCH_WIFI:
1082 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001083 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001084 break;
1085 default:
1086 title = null;
1087 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 }
1089
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001090 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001091 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001092 builder.setTicker(title);
1093 builder.setContentTitle(title);
1094 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001095
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001096 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1097 builder.setContentIntent(PendingIntent.getActivity(
1098 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1099 break;
1100 }
1101 case TYPE_LIMIT_SNOOZED: {
1102 final long overBytes = totalBytes - policy.limitBytes;
1103 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1104 Formatter.formatFileSize(mContext, overBytes));
1105
1106 final CharSequence title;
1107 switch (policy.template.getMatchRule()) {
1108 case MATCH_MOBILE_3G_LOWER:
1109 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1110 break;
1111 case MATCH_MOBILE_4G:
1112 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1113 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001114 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001115 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1116 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001117 case MATCH_WIFI:
1118 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1119 break;
1120 default:
1121 title = null;
1122 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 }
1124
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001125 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001126 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 builder.setTicker(title);
1128 builder.setContentTitle(title);
1129 builder.setContentText(body);
1130
1131 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001132 builder.setContentIntent(PendingIntent.getActivity(
1133 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 break;
1135 }
1136 }
1137
1138 // TODO: move to NotificationManager once we can mock it
1139 try {
1140 final String packageName = mContext.getPackageName();
1141 final int[] idReceived = new int[1];
1142 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001143 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001144 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001145 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001147 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 }
1149 }
1150
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001151 private void cancelNotification(String tag) {
1152 // TODO: move to NotificationManager once we can mock it
1153 try {
1154 final String packageName = mContext.getPackageName();
1155 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001156 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001157 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001158 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001159 }
1160 }
1161
1162 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001163 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001164 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001165 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001166 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 @Override
1168 public void onReceive(Context context, Intent intent) {
1169 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1170 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001171
1172 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001173 synchronized (mNetworkPoliciesSecondLock) {
1174 ensureActiveMobilePolicyNL();
1175 normalizePoliciesNL();
1176 updateNetworkEnabledNL();
1177 updateNetworkRulesNL();
1178 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001179 }
1180 }
1181 };
1182
1183 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001184 * Proactively control network data connections when they exceed
1185 * {@link NetworkPolicy#limitBytes}.
1186 */
Felipe Lemef0823852016-06-08 13:43:08 -07001187 void updateNetworkEnabledNL() {
1188 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189
1190 // TODO: reset any policy-disabled networks when any policy is removed
1191 // completely, which is currently rare case.
1192
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001193 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001194 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1195 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001196 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001197 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 setNetworkTemplateEnabled(policy.template, true);
1199 continue;
1200 }
1201
1202 final long start = computeLastCycleBoundary(currentTime, policy);
1203 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001204 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001205
1206 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001207 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1208 && policy.lastLimitSnooze < start;
1209 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001210
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001211 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001212 }
1213 }
1214
1215 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001216 * Proactively disable networks that match the given
1217 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 */
1219 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001220 // TODO: reach into ConnectivityManager to proactively disable bringing
1221 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001222
1223 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1224 // If mobile data usage hits the limit or if the user resumes the data, we need to
1225 // notify telephony.
1226 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1227 final TelephonyManager tm = TelephonyManager.from(mContext);
1228
1229 final int[] subIds = sm.getActiveSubscriptionIdList();
1230 for (int subId : subIds) {
1231 final String subscriberId = tm.getSubscriberId(subId);
1232 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1233 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1234 // Template is matched when subscriber id matches.
1235 if (template.matches(probeIdent)) {
1236 tm.setPolicyDataEnabled(enabled, subId);
1237 }
1238 }
1239 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 }
1241
1242 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 * Examine all connected {@link NetworkState}, looking for
1244 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1245 * remaining quota based on usage cycle and historical stats.
1246 */
Felipe Lemef0823852016-06-08 13:43:08 -07001247 void updateNetworkRulesNL() {
1248 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001249
1250 final NetworkState[] states;
1251 try {
1252 states = mConnManager.getAllNetworkState();
1253 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001254 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001255 return;
1256 }
1257
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001258 // First, generate identities of all connected networks so we can
1259 // quickly compare them against all defined policies below.
1260 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001261 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001262 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001263 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001265
1266 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001267 if (baseIface != null) {
1268 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001269 }
1270
1271 // Stacked interfaces are considered to have same identity as
1272 // their parent network.
1273 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1274 for (LinkProperties stackedLink : stackedLinks) {
1275 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001276 if (stackedIface != null) {
1277 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001278 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001279 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001280 }
1281 }
1282
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001283 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001284 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001286 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001287 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001288
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001290 for (int j = connIdents.size() - 1; j >= 0; j--) {
1291 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1292 if (policy.template.matches(ident.second)) {
1293 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 }
1295 }
1296
1297 if (ifaceList.size() > 0) {
1298 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001299 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001300 }
1301 }
1302
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001303 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001304 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001305
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001306 // apply each policy that we found ifaces for; compute remaining data
1307 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001308 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001309 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1310 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1311 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001312
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001313 final long start;
1314 final long totalBytes;
1315 if (policy.hasCycle()) {
1316 start = computeLastCycleBoundary(currentTime, policy);
1317 totalBytes = getTotalBytes(policy.template, start, currentTime);
1318 } else {
1319 start = Long.MAX_VALUE;
1320 totalBytes = 0;
1321 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001323 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001324 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 }
1326
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001327 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001328 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001329 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001330 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001331 if (!hasLimit) {
1332 // metered network, but no policy limit; we still need to
1333 // restrict apps, so push really high quota.
1334 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001335 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001336 // snoozing past quota, but we still need to restrict apps,
1337 // so push really high quota.
1338 quotaBytes = Long.MAX_VALUE;
1339 } else {
1340 // remaining "quota" bytes are based on total usage in
1341 // current cycle. kernel doesn't like 0-byte rules, so we
1342 // set 1-byte quota and disable the radio later.
1343 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1344 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001345
1346 if (ifaces.length > 1) {
1347 // TODO: switch to shared quota once NMS supports
1348 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001349 }
1350
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001351 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001352 // long quotaBytes split up into two ints to fit in message
1353 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1354 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1355 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001356 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001357 }
1358 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001359
1360 // keep track of lowest warning or limit of active policies
1361 if (hasWarning && policy.warningBytes < lowestRule) {
1362 lowestRule = policy.warningBytes;
1363 }
1364 if (hasLimit && policy.limitBytes < lowestRule) {
1365 lowestRule = policy.limitBytes;
1366 }
1367 }
1368
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001369 for (int i = connIfaces.size()-1; i >= 0; i--) {
1370 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001371 // long quotaBytes split up into two ints to fit in message
1372 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1373 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1374 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001375 newMeteredIfaces.add(iface);
1376 }
1377
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001378 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001379
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001380 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001381 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1382 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001383 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001384 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1385 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001386 }
1387 }
1388 mMeteredIfaces = newMeteredIfaces;
1389
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001390 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001391 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001392 }
1393
1394 /**
1395 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1396 * have at least a default mobile policy defined.
1397 */
Felipe Lemef0823852016-06-08 13:43:08 -07001398 private void ensureActiveMobilePolicyNL() {
1399 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001400 if (mSuppressDefaultPolicy) return;
1401
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001402 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001403 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001404
Jeff Sharkey32566012014-12-02 18:30:14 -08001405 final int[] subIds = sub.getActiveSubscriptionIdList();
1406 for (int subId : subIds) {
1407 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001408 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001409 }
1410 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001411
Felipe Lemef0823852016-06-08 13:43:08 -07001412 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001413 // Poke around to see if we already have a policy
1414 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001415 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001416 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1417 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1418 if (template.matches(probeIdent)) {
1419 if (LOGD) {
1420 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1421 + NetworkIdentity.scrubSubscriberId(subscriberId));
1422 }
1423 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001424 }
1425 }
1426
Jeff Sharkey32566012014-12-02 18:30:14 -08001427 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1428 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001429
Jeff Sharkey32566012014-12-02 18:30:14 -08001430 // Build default mobile policy, and assume usage cycle starts today
1431 final long warningBytes = mContext.getResources().getInteger(
1432 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001433
Jeff Sharkey32566012014-12-02 18:30:14 -08001434 final Time time = new Time();
1435 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001436
Jeff Sharkey32566012014-12-02 18:30:14 -08001437 final int cycleDay = time.monthDay;
1438 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001439
Jeff Sharkey32566012014-12-02 18:30:14 -08001440 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1441 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1442 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001443 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001444 }
1445
Felipe Lemef0823852016-06-08 13:43:08 -07001446 private void readPolicyAL() {
1447 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001448
1449 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001450 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001451 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001452
1453 FileInputStream fis = null;
1454 try {
1455 fis = mPolicyFile.openRead();
1456 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001457 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001458
1459 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001460 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001461 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001462 while ((type = in.next()) != END_DOCUMENT) {
1463 final String tag = in.getName();
1464 if (type == START_TAG) {
1465 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001466 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001468 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1469 mRestrictBackground = readBooleanAttribute(
1470 in, ATTR_RESTRICT_BACKGROUND);
1471 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001472 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001473 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001474 if (mRestrictBackground != oldValue) {
1475 // Some early services may have read the default value,
1476 // so notify them that it's changed
1477 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1478 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1479 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480
1481 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1482 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1483 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001484 final String networkId;
1485 if (version >= VERSION_ADDED_NETWORK_ID) {
1486 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1487 } else {
1488 networkId = null;
1489 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001491 final String cycleTimezone;
1492 if (version >= VERSION_ADDED_TIMEZONE) {
1493 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1494 } else {
1495 cycleTimezone = Time.TIMEZONE_UTC;
1496 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001497 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1498 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001499 final long lastLimitSnooze;
1500 if (version >= VERSION_SPLIT_SNOOZE) {
1501 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1502 } else if (version >= VERSION_ADDED_SNOOZE) {
1503 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001504 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001505 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001506 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001507 final boolean metered;
1508 if (version >= VERSION_ADDED_METERED) {
1509 metered = readBooleanAttribute(in, ATTR_METERED);
1510 } else {
1511 switch (networkTemplate) {
1512 case MATCH_MOBILE_3G_LOWER:
1513 case MATCH_MOBILE_4G:
1514 case MATCH_MOBILE_ALL:
1515 metered = true;
1516 break;
1517 default:
1518 metered = false;
1519 }
1520 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001521 final long lastWarningSnooze;
1522 if (version >= VERSION_SPLIT_SNOOZE) {
1523 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1524 } else {
1525 lastWarningSnooze = SNOOZE_NEVER;
1526 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001527 final boolean inferred;
1528 if (version >= VERSION_ADDED_INFERRED) {
1529 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1530 } else {
1531 inferred = false;
1532 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001533
Jeff Sharkey32566012014-12-02 18:30:14 -08001534 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1535 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001536 if (template.isPersistable()) {
1537 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1538 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1539 lastLimitSnooze, metered, inferred));
1540 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001542 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001543 final int uid = readIntAttribute(in, ATTR_UID);
1544 final int policy = readIntAttribute(in, ATTR_POLICY);
1545
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001546 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001547 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001548 } else {
1549 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1550 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001551 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001552 final int appId = readIntAttribute(in, ATTR_APP_ID);
1553 final int policy = readIntAttribute(in, ATTR_POLICY);
1554
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001555 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001556 // app policy is deprecated so this is only used in pre system user split.
1557 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001558 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001559 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001560 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001562 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001563 } else if (TAG_WHITELIST.equals(tag)) {
1564 insideWhitelist = true;
1565 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1566 final int uid = readIntAttribute(in, ATTR_UID);
1567 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001568 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1569 final int uid = readIntAttribute(in, ATTR_UID);
1570 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001571 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001572 } else if (type == END_TAG) {
1573 if (TAG_WHITELIST.equals(tag)) {
1574 insideWhitelist = false;
1575 }
1576
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 }
1578 }
1579
1580 } catch (FileNotFoundException e) {
1581 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001582 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001584 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001586 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 } finally {
1588 IoUtils.closeQuietly(fis);
1589 }
1590 }
1591
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001592 /**
1593 * Upgrade legacy background data flags, notifying listeners of one last
1594 * change to always-true.
1595 */
Felipe Lemef0823852016-06-08 13:43:08 -07001596 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001597 mRestrictBackground = Settings.Secure.getInt(
1598 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1599
1600 // kick off one last broadcast if restricted
1601 if (mRestrictBackground) {
1602 final Intent broadcast = new Intent(
1603 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001604 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001605 }
1606 }
1607
Felipe Lemef0823852016-06-08 13:43:08 -07001608 void writePolicyAL() {
1609 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610
1611 FileOutputStream fos = null;
1612 try {
1613 fos = mPolicyFile.startWrite();
1614
1615 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001616 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001617 out.startDocument(null, true);
1618
1619 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001620 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001621 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001622
1623 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001624 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1625 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001626 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001627 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001628
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001629 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001630 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1631 final String subscriberId = template.getSubscriberId();
1632 if (subscriberId != null) {
1633 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001634 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001635 final String networkId = template.getNetworkId();
1636 if (networkId != null) {
1637 out.attribute(null, ATTR_NETWORK_ID, networkId);
1638 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001640 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001641 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1642 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001643 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1644 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001645 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001646 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647 out.endTag(null, TAG_NETWORK_POLICY);
1648 }
1649
1650 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001651 for (int i = 0; i < mUidPolicy.size(); i++) {
1652 final int uid = mUidPolicy.keyAt(i);
1653 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654
Jeff Sharkey497e4432011-06-14 17:27:29 -07001655 // skip writing empty policies
1656 if (policy == POLICY_NONE) continue;
1657
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001658 out.startTag(null, TAG_UID_POLICY);
1659 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001660 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001661 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 }
1663
1664 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001665
1666 // write all whitelists
1667 out.startTag(null, TAG_WHITELIST);
1668
1669 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001670 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001671 for (int i = 0; i < size; i++) {
1672 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1673 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1674 writeIntAttribute(out, ATTR_UID, uid);
1675 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1676 }
1677
Felipe Lemea9505cc2016-02-26 10:28:41 -08001678 // revoked restrict background whitelist
1679 size = mRestrictBackgroundWhitelistRevokedUids.size();
1680 for (int i = 0; i < size; i++) {
1681 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1682 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1683 writeIntAttribute(out, ATTR_UID, uid);
1684 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1685 }
1686
Felipe Lemeb85a6372016-01-14 16:16:16 -08001687 out.endTag(null, TAG_WHITELIST);
1688
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001689 out.endDocument();
1690
1691 mPolicyFile.finishWrite(fos);
1692 } catch (IOException e) {
1693 if (fos != null) {
1694 mPolicyFile.failWrite(fos);
1695 }
1696 }
1697 }
1698
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001699 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001700 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001701 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001702
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001703 if (!UserHandle.isApp(uid)) {
1704 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001705 }
Felipe Lemef0823852016-06-08 13:43:08 -07001706 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001707 final long token = Binder.clearCallingIdentity();
1708 try {
1709 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1710 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001711 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001712 }
1713 } finally {
1714 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001715 }
1716 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001717 }
1718
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001719 @Override
1720 public void addUidPolicy(int uid, int policy) {
1721 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001722
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001723 if (!UserHandle.isApp(uid)) {
1724 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1725 }
1726
Felipe Lemef0823852016-06-08 13:43:08 -07001727 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001728 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1729 policy |= oldPolicy;
1730 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001731 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001732 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001733 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001734 }
1735
1736 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001737 public void removeUidPolicy(int uid, int policy) {
1738 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1739
1740 if (!UserHandle.isApp(uid)) {
1741 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1742 }
1743
Felipe Lemef0823852016-06-08 13:43:08 -07001744 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001745 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1746 policy = oldPolicy & ~policy;
1747 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001748 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001749 }
1750 }
1751 }
1752
Felipe Lemef0823852016-06-08 13:43:08 -07001753 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1754 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001755
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001756 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1757 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1758 isBlacklisted ? 1 : 0).sendToTarget();
1759
1760 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001761 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001762 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1763 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001764 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001765 .sendToTarget();
1766 }
1767 }
1768
Felipe Lemef0823852016-06-08 13:43:08 -07001769 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001770 mUidPolicy.put(uid, policy);
1771
1772 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001773 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001774 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001775 synchronized (mNetworkPoliciesSecondLock) {
1776 writePolicyAL();
1777 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001778 }
1779 }
1780
1781 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001782 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001783 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1784
Felipe Lemef0823852016-06-08 13:43:08 -07001785 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001786 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001787 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001788 }
1789
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001790 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001791 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001792 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1793
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001794 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001795 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001796 for (int i = 0; i < mUidPolicy.size(); i++) {
1797 final int uid = mUidPolicy.keyAt(i);
1798 final int uidPolicy = mUidPolicy.valueAt(i);
1799 if (uidPolicy == policy) {
1800 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001801 }
1802 }
1803 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001804 return uids;
1805 }
1806
1807 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001808 * Removes any persistable state associated with given {@link UserHandle}, persisting
1809 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001810 */
Felipe Lemef0823852016-06-08 13:43:08 -07001811 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001812
Felipe Lemef0823852016-06-08 13:43:08 -07001813 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001814 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001815
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001816 // Remove entries from restricted background UID whitelist
1817 int[] wlUids = new int[0];
1818 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1819 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1820 if (UserHandle.getUserId(uid) == userId) {
1821 wlUids = appendInt(wlUids, uid);
1822 }
1823 }
1824
1825 if (wlUids.length > 0) {
1826 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001827 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001828 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001829 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001830 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001831
1832 // Remove entries from revoked default restricted background UID whitelist
1833 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1834 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1835 if (UserHandle.getUserId(uid) == userId) {
1836 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001837 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001838 }
1839 }
1840
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001841 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001842 int[] uids = new int[0];
1843 for (int i = 0; i < mUidPolicy.size(); i++) {
1844 final int uid = mUidPolicy.keyAt(i);
1845 if (UserHandle.getUserId(uid) == userId) {
1846 uids = appendInt(uids, uid);
1847 }
1848 }
1849
1850 if (uids.length > 0) {
1851 for (int uid : uids) {
1852 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001853 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001854 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001855 }
Felipe Lemef0823852016-06-08 13:43:08 -07001856 synchronized (mNetworkPoliciesSecondLock) {
1857 updateRulesForGlobalChangeAL(true);
1858 if (writePolicy && changed) {
1859 writePolicyAL();
1860 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001861 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001862 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001863 }
1864
1865 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001866 public void setConnectivityListener(INetworkPolicyListener listener) {
1867 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1868 if (mConnectivityListener != null) {
1869 throw new IllegalStateException("Connectivity listener already registered");
1870 }
1871 mConnectivityListener = listener;
1872 }
1873
1874 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001875 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001876 // TODO: create permission for observing network policy
1877 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001878 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001879 }
1880
1881 @Override
1882 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001883 // TODO: create permission for observing network policy
1884 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001885 mListeners.unregister(listener);
1886 }
1887
Jeff Sharkey1b861272011-05-22 00:34:52 -07001888 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001889 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001890 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1891
Felipe Leme6a05eee2016-02-19 14:43:51 -08001892 final long token = Binder.clearCallingIdentity();
1893 try {
1894 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001895 synchronized (mUidRulesFirstLock) {
1896 synchronized (mNetworkPoliciesSecondLock) {
1897 normalizePoliciesNL(policies);
1898 updateNetworkEnabledNL();
1899 updateNetworkRulesNL();
1900 updateNotificationsNL();
1901 writePolicyAL();
1902 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001903 }
1904 } finally {
1905 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001906 }
1907 }
1908
Felipe Lemef0823852016-06-08 13:43:08 -07001909 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001910 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001911 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1912 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001913 }
1914
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001915 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001916 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001917 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001918 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001919 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1920 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1921 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001922 } catch (SecurityException e) {
1923 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001924
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001925 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1926 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1927 return new NetworkPolicy[0];
1928 }
Svet Ganov16a16892015-04-16 10:32:04 -07001929 }
1930
Felipe Lemef0823852016-06-08 13:43:08 -07001931 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001932 final int size = mNetworkPolicy.size();
1933 final NetworkPolicy[] policies = new NetworkPolicy[size];
1934 for (int i = 0; i < size; i++) {
1935 policies[i] = mNetworkPolicy.valueAt(i);
1936 }
1937 return policies;
1938 }
1939 }
1940
Felipe Lemef0823852016-06-08 13:43:08 -07001941 private void normalizePoliciesNL() {
1942 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001943 }
1944
Felipe Lemef0823852016-06-08 13:43:08 -07001945 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001946 final TelephonyManager tele = TelephonyManager.from(mContext);
1947 final String[] merged = tele.getMergedSubscriberIds();
1948
1949 mNetworkPolicy.clear();
1950 for (NetworkPolicy policy : policies) {
1951 // When two normalized templates conflict, prefer the most
1952 // restrictive policy
1953 policy.template = NetworkTemplate.normalize(policy.template, merged);
1954 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1955 if (existing == null || existing.compareTo(policy) > 0) {
1956 if (existing != null) {
1957 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1958 }
1959 mNetworkPolicy.put(policy.template, policy);
1960 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001961 }
1962 }
1963
1964 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001965 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001966 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001967
1968 final long token = Binder.clearCallingIdentity();
1969 try {
1970 performSnooze(template, TYPE_LIMIT);
1971 } finally {
1972 Binder.restoreCallingIdentity(token);
1973 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001974 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001975
Dianne Hackborn497175b2014-07-01 12:56:08 -07001976 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001977 maybeRefreshTrustedTime();
1978 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001979 synchronized (mUidRulesFirstLock) {
1980 synchronized (mNetworkPoliciesSecondLock) {
1981 // find and snooze local policy that matches
1982 final NetworkPolicy policy = mNetworkPolicy.get(template);
1983 if (policy == null) {
1984 throw new IllegalArgumentException("unable to find policy for " + template);
1985 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001986
Felipe Lemef0823852016-06-08 13:43:08 -07001987 switch (type) {
1988 case TYPE_WARNING:
1989 policy.lastWarningSnooze = currentTime;
1990 break;
1991 case TYPE_LIMIT:
1992 policy.lastLimitSnooze = currentTime;
1993 break;
1994 default:
1995 throw new IllegalArgumentException("unexpected type");
1996 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001997
Felipe Lemef0823852016-06-08 13:43:08 -07001998 normalizePoliciesNL();
1999 updateNetworkEnabledNL();
2000 updateNetworkRulesNL();
2001 updateNotificationsNL();
2002 writePolicyAL();
2003 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002004 }
2005 }
2006
2007 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002008 public void onTetheringChanged(String iface, boolean tethering) {
2009 // No need to enforce permission because setRestrictBackground() will do it.
2010 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002011 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002012 if (mRestrictBackground && tethering) {
2013 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2014 setRestrictBackground(false);
2015 }
2016 }
2017 }
2018
2019 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002020 public void setRestrictBackground(boolean restrictBackground) {
2021 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002022 final long token = Binder.clearCallingIdentity();
2023 try {
2024 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002025 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002026 if (restrictBackground == mRestrictBackground) {
2027 // Ideally, UI should never allow this scenario...
2028 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2029 return;
2030 }
Felipe Lemef0823852016-06-08 13:43:08 -07002031 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002032 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002033
Felipe Leme6a05eee2016-02-19 14:43:51 -08002034 } finally {
2035 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002036 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002037
2038 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2039 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002040 }
2041
Felipe Lemef0823852016-06-08 13:43:08 -07002042 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Lemea1540892016-06-21 13:08:55 -07002043 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002044 final boolean oldRestrictBackground = mRestrictBackground;
2045 mRestrictBackground = restrictBackground;
2046 // Must whitelist foreground apps before turning data saver mode on.
2047 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2048 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002049 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002050 try {
2051 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2052 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2053 mRestrictBackground = oldRestrictBackground;
2054 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002055 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002056 return;
2057 }
2058 } catch (RemoteException e) {
2059 // ignored; service lives in system_server
2060 }
Felipe Lemef0823852016-06-08 13:43:08 -07002061 synchronized (mNetworkPoliciesSecondLock) {
2062 updateNotificationsNL();
2063 writePolicyAL();
2064 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002065 }
2066
Jeff Sharkey46645002011-07-27 21:11:21 -07002067 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002068 public void addRestrictBackgroundWhitelistedUid(int uid) {
2069 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002070 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002071 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002072 int changed;
2073 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002074 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002075 if (oldStatus) {
2076 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2077 return;
2078 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002079 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002080 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002081 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002082 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2083 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2084 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2085 + " from revoked restrict background whitelist");
2086 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2087 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002088 if (needFirewallRules) {
2089 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002090 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002091 }
2092 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002093 synchronized (mNetworkPoliciesSecondLock) {
2094 writePolicyAL();
2095 }
2096 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002097 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002098 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2099 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002100 }
2101
2102 @Override
2103 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2104 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002105 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002106 synchronized (mUidRulesFirstLock) {
2107 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002108 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002109 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2110 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002111 }
2112
Felipe Leme70c57c22016-03-29 10:45:13 -07002113 /**
2114 * Removes a uid from the restricted background whitelist, returning whether its current
2115 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2116 */
Felipe Lemef0823852016-06-08 13:43:08 -07002117 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002118 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002119 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002120 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002121 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2122 return false;
2123 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002124 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002125 if (oldStatus) {
2126 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2127 mRestrictBackgroundWhitelistUids.delete(uid);
2128 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002129 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2130 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2131 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2132 + " to revoked restrict background whitelist");
2133 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2134 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002135 if (needFirewallRules) {
2136 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002137 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002138 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002139 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002140 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002141 synchronized (mNetworkPoliciesSecondLock) {
2142 writePolicyAL();
2143 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002144 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002145 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2146 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002147 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002148 }
2149
2150 @Override
2151 public int[] getRestrictBackgroundWhitelistedUids() {
2152 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002153 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002154 final int size = mRestrictBackgroundWhitelistUids.size();
2155 final int[] whitelist = new int[size];
2156 for (int i = 0; i < size; i++) {
2157 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2158 }
2159 if (LOGV) {
2160 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2161 + mRestrictBackgroundWhitelistUids);
2162 }
2163 return whitelist;
2164 }
2165 }
2166
2167 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002168 public int getRestrictBackgroundByCaller() {
2169 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2170 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002171
Felipe Lemef0823852016-06-08 13:43:08 -07002172 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002173 // Must clear identity because getUidPolicy() is restricted to system.
2174 final long token = Binder.clearCallingIdentity();
2175 final int policy;
2176 try {
2177 policy = getUidPolicy(uid);
2178 } finally {
2179 Binder.restoreCallingIdentity(token);
2180 }
2181 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2182 // App is blacklisted.
2183 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2184 }
Felipe Leme1b103232016-01-22 09:44:57 -08002185 if (!mRestrictBackground) {
2186 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2187 }
2188 return mRestrictBackgroundWhitelistUids.get(uid)
2189 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2190 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2191 }
2192 }
2193
2194 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002195 public boolean getRestrictBackground() {
2196 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2197
Felipe Lemef0823852016-06-08 13:43:08 -07002198 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002199 return mRestrictBackground;
2200 }
2201 }
2202
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002203 @Override
2204 public void setDeviceIdleMode(boolean enabled) {
2205 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2206
Felipe Lemef0823852016-06-08 13:43:08 -07002207 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002208 if (mDeviceIdleMode != enabled) {
2209 mDeviceIdleMode = enabled;
2210 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002211 // Device idle change means we need to rebuild rules for all
2212 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002213 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002214 }
2215 if (enabled) {
2216 EventLogTags.writeDeviceIdleOnPhase("net");
2217 } else {
2218 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002219 }
2220 }
2221 }
2222 }
2223
Felipe Lemef0823852016-06-08 13:43:08 -07002224 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002225 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2226 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002227 if (policy.template.matches(ident)) {
2228 return policy;
2229 }
2230 }
2231 return null;
2232 }
2233
2234 @Override
2235 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2236 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2237
2238 // only returns usage summary, so we don't require caller to have
2239 // READ_NETWORK_USAGE_HISTORY.
2240 final long token = Binder.clearCallingIdentity();
2241 try {
2242 return getNetworkQuotaInfoUnchecked(state);
2243 } finally {
2244 Binder.restoreCallingIdentity(token);
2245 }
2246 }
2247
2248 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2249 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2250
2251 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002252 synchronized (mNetworkPoliciesSecondLock) {
2253 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002254 }
2255
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002256 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002257 // missing policy means we can't derive useful quota info
2258 return null;
2259 }
2260
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002261 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002262
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002263 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002264 final long start = computeLastCycleBoundary(currentTime, policy);
2265 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002266 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002267
2268 // report soft and hard limits under policy
2269 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2270 : NetworkQuotaInfo.NO_LIMIT;
2271 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2272 : NetworkQuotaInfo.NO_LIMIT;
2273
2274 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2275 }
2276
Jeff Sharkey46645002011-07-27 21:11:21 -07002277 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002278 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002279 if (state.networkInfo == null) {
2280 return false;
2281 }
2282
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002283 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2284
2285 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002286 synchronized (mNetworkPoliciesSecondLock) {
2287 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002288 }
2289
2290 if (policy != null) {
2291 return policy.metered;
2292 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002293 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002294 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002295 return true;
2296 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002297 return false;
2298 }
2299 }
2300
2301 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002302 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002303 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002304
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002305 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2306
Dianne Hackborn497175b2014-07-01 12:56:08 -07002307 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002308 for (String arg : args) {
2309 argSet.add(arg);
2310 }
2311
Felipe Lemef0823852016-06-08 13:43:08 -07002312 synchronized (mUidRulesFirstLock) {
2313 synchronized (mNetworkPoliciesSecondLock) {
2314 if (argSet.contains("--unsnooze")) {
2315 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2316 mNetworkPolicy.valueAt(i).clearSnooze();
2317 }
2318
2319 normalizePoliciesNL();
2320 updateNetworkEnabledNL();
2321 updateNetworkRulesNL();
2322 updateNotificationsNL();
2323 writePolicyAL();
2324
2325 fout.println("Cleared snooze timestamps");
2326 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002327 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002328
Felipe Lemef0823852016-06-08 13:43:08 -07002329 fout.print("System ready: "); fout.println(mSystemReady);
2330 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2331 fout.print("Restrict power: "); fout.println(mRestrictPower);
2332 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2333 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002334 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002335 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2336 fout.println(mNetworkPolicy.valueAt(i).toString());
2337 }
2338 fout.decreaseIndent();
2339
2340 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2341
2342 fout.println("Policy for UIDs:");
2343 fout.increaseIndent();
2344 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002345 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002346 final int uid = mUidPolicy.keyAt(i);
2347 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002348 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002349 fout.print(uid);
2350 fout.print(" policy=");
2351 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2352 fout.println();
2353 }
2354 fout.decreaseIndent();
2355
2356 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2357 if (size > 0) {
2358 fout.println("Power save whitelist (except idle) app ids:");
2359 fout.increaseIndent();
2360 for (int i = 0; i < size; i++) {
2361 fout.print("UID=");
2362 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2363 fout.print(": ");
2364 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2365 fout.println();
2366 }
2367 fout.decreaseIndent();
2368 }
2369
2370 size = mPowerSaveWhitelistAppIds.size();
2371 if (size > 0) {
2372 fout.println("Power save whitelist app ids:");
2373 fout.increaseIndent();
2374 for (int i = 0; i < size; i++) {
2375 fout.print("UID=");
2376 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2377 fout.print(": ");
2378 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2379 fout.println();
2380 }
2381 fout.decreaseIndent();
2382 }
2383
2384 size = mRestrictBackgroundWhitelistUids.size();
2385 if (size > 0) {
2386 fout.println("Restrict background whitelist uids:");
2387 fout.increaseIndent();
2388 for (int i = 0; i < size; i++) {
2389 fout.print("UID=");
2390 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2391 fout.println();
2392 }
2393 fout.decreaseIndent();
2394 }
2395
2396 size = mDefaultRestrictBackgroundWhitelistUids.size();
2397 if (size > 0) {
2398 fout.println("Default restrict background whitelist uids:");
2399 fout.increaseIndent();
2400 for (int i = 0; i < size; i++) {
2401 fout.print("UID=");
2402 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2403 fout.println();
2404 }
2405 fout.decreaseIndent();
2406 }
2407
2408 size = mRestrictBackgroundWhitelistRevokedUids.size();
2409 if (size > 0) {
2410 fout.println("Default restrict background whitelist uids revoked by users:");
2411 fout.increaseIndent();
2412 for (int i = 0; i < size; i++) {
2413 fout.print("UID=");
2414 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2415 fout.println();
2416 }
2417 fout.decreaseIndent();
2418 }
2419
2420 final SparseBooleanArray knownUids = new SparseBooleanArray();
2421 collectKeys(mUidState, knownUids);
2422 collectKeys(mUidRules, knownUids);
2423
2424 fout.println("Status for all known UIDs:");
2425 fout.increaseIndent();
2426 size = knownUids.size();
2427 for (int i = 0; i < size; i++) {
2428 final int uid = knownUids.keyAt(i);
2429 fout.print("UID=");
2430 fout.print(uid);
2431
2432 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2433 fout.print(" state=");
2434 fout.print(state);
2435 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2436 fout.print(" (fg)");
2437 } else {
2438 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2439 ? " (fg svc)" : " (bg)");
2440 }
2441
2442 final int uidRules = mUidRules.get(uid, RULE_NONE);
2443 fout.print(" rules=");
2444 fout.print(uidRulesToString(uidRules));
2445 fout.println();
2446 }
2447 fout.decreaseIndent();
2448
2449 fout.println("Status for just UIDs with rules:");
2450 fout.increaseIndent();
2451 size = mUidRules.size();
2452 for (int i = 0; i < size; i++) {
2453 final int uid = mUidRules.keyAt(i);
2454 fout.print("UID=");
2455 fout.print(uid);
2456 final int uidRules = mUidRules.get(uid, RULE_NONE);
2457 fout.print(" rules=");
2458 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002459 fout.println();
2460 }
2461 fout.decreaseIndent();
2462 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002463 }
2464 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002465
2466 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002467 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2468 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002469 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002470 this, in, out, err, args, resultReceiver);
2471 }
2472
2473 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002474 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002475 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2476
Felipe Lemef0823852016-06-08 13:43:08 -07002477 synchronized (mUidRulesFirstLock) {
2478 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002479 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002480 }
2481
Felipe Lemef0823852016-06-08 13:43:08 -07002482 private boolean isUidForegroundUL(int uid) {
2483 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002484 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2485 }
2486
Felipe Lemef0823852016-06-08 13:43:08 -07002487 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002488 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002489 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002490 }
2491
Felipe Lemef0823852016-06-08 13:43:08 -07002492 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002493 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2494 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2495 }
2496
Felipe Lemef0823852016-06-08 13:43:08 -07002497 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002498 // only really in foreground when screen is also on
Felipe Lemef8dd7b42016-08-10 13:00:32 -07002499 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002500 }
2501
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002502 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002503 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002504 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2505 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002506 */
Felipe Lemef0823852016-06-08 13:43:08 -07002507 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002508 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2509 if (oldUidState != uidState) {
2510 // state changed, push updated rules
2511 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002512 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002513 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2514 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002515 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002516 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002517 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002518 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002519 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002520 }
2521 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002522 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002523 }
Felipe Lemef0823852016-06-08 13:43:08 -07002524 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002525 }
Felipe Lemef0823852016-06-08 13:43:08 -07002526 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002527 }
2528 }
2529
Felipe Lemef0823852016-06-08 13:43:08 -07002530 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002531 final int index = mUidState.indexOfKey(uid);
2532 if (index >= 0) {
2533 final int oldUidState = mUidState.valueAt(index);
2534 mUidState.removeAt(index);
2535 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002536 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002537 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002538 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002539 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002540 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002541 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002542 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002543 }
Felipe Lemef0823852016-06-08 13:43:08 -07002544 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002545 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002546 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002547 }
2548 }
2549
Felipe Lemef28983d2016-03-25 12:18:23 -07002550 // adjust stats accounting based on foreground status
2551 private void updateNetworkStats(int uid, boolean uidForeground) {
2552 try {
2553 mNetworkStats.setUidForeground(uid, uidForeground);
2554 } catch (RemoteException e) {
2555 // ignored; service lives in system_server
2556 }
2557 }
2558
Felipe Lemef0823852016-06-08 13:43:08 -07002559 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002560 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002561 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002562 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002563 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002564 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002565 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002566 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002567 }
2568 }
2569
Felipe Leme011b98f2016-02-10 17:28:31 -08002570 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002571 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2572 }
2573
Felipe Lemef0823852016-06-08 13:43:08 -07002574 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002575 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2576 }
2577
Felipe Lemef0823852016-06-08 13:43:08 -07002578 void updateRulesForPowerSaveUL() {
2579 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002580 mUidFirewallPowerSaveRules);
2581 }
2582
Felipe Lemef0823852016-06-08 13:43:08 -07002583 void updateRuleForRestrictPowerUL(int uid) {
2584 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002585 }
2586
Felipe Lemef0823852016-06-08 13:43:08 -07002587 void updateRulesForDeviceIdleUL() {
2588 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002589 mUidFirewallDozableRules);
2590 }
2591
Felipe Lemef0823852016-06-08 13:43:08 -07002592 void updateRuleForDeviceIdleUL(int uid) {
2593 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002594 }
2595
Felipe Lemef28983d2016-03-25 12:18:23 -07002596 // NOTE: since both fw_dozable and fw_powersave uses the same map
2597 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002598 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002599 SparseIntArray rules) {
2600 if (enabled) {
2601 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002602 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002603 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002604 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002605 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002606 for (int ui = users.size() - 1; ui >= 0; ui--) {
2607 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002608 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002609 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2610 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2611 int uid = UserHandle.getUid(user.id, appId);
2612 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2613 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002614 }
2615 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2616 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2617 int uid = UserHandle.getUid(user.id, appId);
2618 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2619 }
2620 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002621 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002622 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002623 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2624 }
2625 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002626 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002627 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002628
Felipe Lemef0823852016-06-08 13:43:08 -07002629 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002630 }
2631
Felipe Lemef0823852016-06-08 13:43:08 -07002632 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002633 final int appId = UserHandle.getAppId(uid);
2634 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2635 }
2636
Felipe Lemef28983d2016-03-25 12:18:23 -07002637 // NOTE: since both fw_dozable and fw_powersave uses the same map
2638 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002639 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002640 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002641 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002642 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2643 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002644 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002645 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002646 }
2647 }
2648 }
2649
Felipe Lemef0823852016-06-08 13:43:08 -07002650 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002651 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2652 uidRules.clear();
2653
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002654 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002655 final List<UserInfo> users = mUserManager.getUsers();
2656 for (int ui = users.size() - 1; ui >= 0; ui--) {
2657 UserInfo user = users.get(ui);
2658 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2659 for (int uid : idleUids) {
2660 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002661 // quick check: if this uid doesn't have INTERNET permission, it
2662 // doesn't have network access anyway, so it is a waste to mess
2663 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002664 if (hasInternetPermissions(uid)) {
2665 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002666 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002667 }
2668 }
2669 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002670
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002671 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2672 }
2673
Felipe Lemef0823852016-06-08 13:43:08 -07002674 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002675 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002676
2677 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002678 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002679 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002680 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2681 } else {
2682 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2683 }
2684 }
2685
Felipe Lemef0823852016-06-08 13:43:08 -07002686 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002687 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002688 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002689 }
2690
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002691 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002692 * Update rules that might be changed by {@link #mRestrictBackground},
2693 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002694 */
Felipe Lemef0823852016-06-08 13:43:08 -07002695 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002696 long start;
2697 if (LOGD) start = System.currentTimeMillis();
2698
Felipe Lemef0823852016-06-08 13:43:08 -07002699 updateRulesForRestrictPowerUL();
2700 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002701
2702 // If the set of restricted networks may have changed, re-evaluate those.
2703 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002704 normalizePoliciesNL();
2705 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002706 }
2707 if (LOGD) {
2708 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002709 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002710 + delta + "ms");
2711 }
2712 }
2713
Felipe Lemef0823852016-06-08 13:43:08 -07002714 private void updateRulesForRestrictPowerUL() {
2715 updateRulesForDeviceIdleUL();
2716 updateRulesForAppIdleUL();
2717 updateRulesForPowerSaveUL();
2718 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002719 }
2720
Felipe Lemef0823852016-06-08 13:43:08 -07002721 private void updateRulesForRestrictBackgroundUL() {
2722 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002723 }
2724
2725 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2726 private static final int TYPE_RESTRICT_POWER = 2;
2727 @Retention(RetentionPolicy.SOURCE)
2728 @IntDef(flag = false, value = {
2729 TYPE_RESTRICT_BACKGROUND,
2730 TYPE_RESTRICT_POWER,
2731 })
2732 public @interface RestrictType {
2733 }
2734
2735 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002736 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002737 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002738
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002739 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002740 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002741 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002742 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2743 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2744 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002745
Felipe Leme03e689d2016-03-02 16:17:38 -08002746 final int usersSize = users.size();
2747 final int appsSize = apps.size();
2748 for (int i = 0; i < usersSize; i++) {
2749 final UserInfo user = users.get(i);
2750 for (int j = 0; j < appsSize; j++) {
2751 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002752 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002753 switch (type) {
2754 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002755 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002756 break;
2757 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002758 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002759 break;
2760 default:
2761 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2762 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002763 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002764 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002765 }
2766
Felipe Lemef0823852016-06-08 13:43:08 -07002767 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002768 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002769 for (int i = 0; i < users.size(); i++) {
2770 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002771 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002772 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002773 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002774 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002775 updateRuleForAppIdleUL(uid);
2776 updateRuleForDeviceIdleUL(uid);
2777 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002778 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002779 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002780 }
2781 }
2782 }
2783
Felipe Leme70c57c22016-03-29 10:45:13 -07002784 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2785 // methods below could be merged into a isUidValidForRules() method.
2786 private boolean isUidValidForBlacklistRules(int uid) {
2787 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002788 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002789 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002790 return true;
2791 }
2792
2793 return false;
2794 }
2795
Felipe Leme70c57c22016-03-29 10:45:13 -07002796 private boolean isUidValidForWhitelistRules(int uid) {
2797 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2798 }
2799
Amith Yamasani15e472352015-04-24 19:06:07 -07002800 private boolean isUidIdle(int uid) {
2801 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2802 final int userId = UserHandle.getUserId(uid);
2803
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002804 if (!ArrayUtils.isEmpty(packages)) {
2805 for (String packageName : packages) {
2806 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2807 return false;
2808 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002809 }
2810 }
2811 return true;
2812 }
2813
2814 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002815 * Checks if an uid has INTERNET permissions.
2816 * <p>
2817 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002818 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002819 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002820 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002821 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002822 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002823 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002824 }
2825 } catch (RemoteException e) {
2826 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002827 return true;
2828 }
2829
2830 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002831 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002832 *
Felipe Leme781ba142016-05-09 16:24:48 -07002833 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002834 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002835 * <li>Doze mode
2836 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002837 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002838 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002839 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002840 *
2841 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002842 */
Felipe Lemef0823852016-06-08 13:43:08 -07002843 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002844 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002845 updateRuleForDeviceIdleUL(uid);
2846 updateRuleForAppIdleUL(uid);
2847 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002848
2849 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002850 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002851
2852 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002853 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002854 }
2855
Felipe Leme70c57c22016-03-29 10:45:13 -07002856 /**
2857 * Applies network rules to bandwidth controllers based on process state and user-defined
2858 * restrictions (blacklist / whitelist).
2859 *
2860 * <p>
2861 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2862 * networks:
2863 * <ul>
2864 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2865 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2866 * also blacklisted.
2867 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2868 * no UIDs other those whitelisted will have access.
2869 * <ul>
2870 *
2871 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2872 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2873 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2874 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002875 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002876 * {@link INetworkManagementService}, but this method should also be called in events (like
2877 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2878 * following rules should also be applied:
2879 *
2880 * <ul>
2881 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2882 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2883 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2884 * {@code bw_penalty_box}.
2885 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2886 * </ul>
2887 *
2888 * <p>For optimization, the rules are only applied on user apps that have internet access
2889 * permission, since there is no need to change the {@code iptables} rule if the app does not
2890 * have permission to use the internet.
2891 *
2892 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002893 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002894 */
Felipe Lemef0823852016-06-08 13:43:08 -07002895 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2896 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002897 }
2898
2899 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002900 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002901 * app is removed - it ignores the UID validity check.
2902 */
Felipe Lemef0823852016-06-08 13:43:08 -07002903 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002904 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2905 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2906 return;
2907 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002908
Dianne Hackborn497175b2014-07-01 12:56:08 -07002909 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002910 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002911 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002912
Felipe Leme781ba142016-05-09 16:24:48 -07002913 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2914 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2915 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2916 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002917
Felipe Leme70c57c22016-03-29 10:45:13 -07002918 // First step: define the new rule based on user restrictions and foreground state.
2919 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002920 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2921 newRule = RULE_TEMPORARY_ALLOW_METERED;
2922 } else if (isWhitelisted) {
2923 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002924 }
2925 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002926 if (isBlacklisted) {
2927 newRule = RULE_REJECT_METERED;
2928 } else if (mRestrictBackground && isWhitelisted) {
2929 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002930 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002931 }
Felipe Leme781ba142016-05-09 16:24:48 -07002932 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002933
Felipe Lemef28983d2016-03-25 12:18:23 -07002934 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002935 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002936 + ": isForeground=" +isForeground
2937 + ", isBlacklisted=" + isBlacklisted
2938 + ", isWhitelisted=" + isWhitelisted
2939 + ", oldRule=" + uidRulesToString(oldRule)
2940 + ", newRule=" + uidRulesToString(newRule)
2941 + ", newUidRules=" + uidRulesToString(newUidRules)
2942 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002943 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002944
Felipe Leme46c4fc32016-05-04 09:21:43 -07002945 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002946 mUidRules.delete(uid);
2947 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002948 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002949 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002950
Felipe Leme70c57c22016-03-29 10:45:13 -07002951 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002952 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002953 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002954 // Temporarily whitelist foreground app, removing from blacklist if necessary
2955 // (since bw_penalty_box prevails over bw_happy_box).
2956
2957 setMeteredNetworkWhitelist(uid, true);
2958 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2959 // but ideally it should be just:
2960 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002961 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002962 setMeteredNetworkBlacklist(uid, false);
2963 }
Felipe Leme781ba142016-05-09 16:24:48 -07002964 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002965 // Remove temporary whitelist from app that is not on foreground anymore.
2966
2967 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2968 // but ideally they should be just:
2969 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2970 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002971 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002972 setMeteredNetworkWhitelist(uid, false);
2973 }
Felipe Leme781ba142016-05-09 16:24:48 -07002974 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002975 setMeteredNetworkBlacklist(uid, true);
2976 }
Felipe Leme781ba142016-05-09 16:24:48 -07002977 } else if ((newRule & RULE_REJECT_METERED) != 0
2978 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002979 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002980 setMeteredNetworkBlacklist(uid, isBlacklisted);
2981 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002982 // Since blacklist prevails over whitelist, we need to handle the special case
2983 // where app is whitelisted and blacklisted at the same time (although such
2984 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07002985 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002986 }
Felipe Leme781ba142016-05-09 16:24:48 -07002987 } else if ((newRule & RULE_ALLOW_METERED) != 0
2988 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002989 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07002990 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002991 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002992 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002993 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2994 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07002995 + ", whitelisted=" + isWhitelisted
2996 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07002997 + ", newRule=" + uidRulesToString(newUidRules)
2998 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07002999 }
Felipe Leme781ba142016-05-09 16:24:48 -07003000
3001 // Dispatch changed rule to existing listeners.
3002 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3003 }
3004 }
3005
3006 /**
3007 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3008 * listeners in case of change.
3009 * <p>
3010 * There are 3 power-related rules that affects whether an app has background access on
3011 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3012 * restriction, it's added to the equivalent firewall chain:
3013 * <ul>
3014 * <li>App is idle: {@code fw_standby} firewall chain.
3015 * <li>Device is idle: {@code fw_dozable} firewall chain.
3016 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3017 * </ul>
3018 * <p>
3019 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3020 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3021 * <p>
3022 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3023 */
Felipe Lemef0823852016-06-08 13:43:08 -07003024 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003025 if (!isUidValidForBlacklistRules(uid)) {
3026 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3027 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003028 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003029
Felipe Leme781ba142016-05-09 16:24:48 -07003030 final boolean isIdle = isUidIdle(uid);
3031 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Leme781ba142016-05-09 16:24:48 -07003032 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003033 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003034
Felipe Lemef0823852016-06-08 13:43:08 -07003035 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003036 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3037 int newRule = RULE_NONE;
3038
3039 // First step: define the new rule based on user restrictions and foreground state.
3040
3041 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3042 // by considering the foreground and non-foreground states.
3043 if (isForeground) {
3044 if (restrictMode) {
3045 newRule = RULE_ALLOW_ALL;
3046 }
3047 } else if (restrictMode) {
3048 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3049 }
3050
3051 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3052
3053 if (LOGV) {
Felipe Lemef8dd7b42016-08-10 13:00:32 -07003054 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003055 + ", isIdle: " + isIdle
3056 + ", mRestrictPower: " + mRestrictPower
3057 + ", mDeviceIdleMode: " + mDeviceIdleMode
3058 + ", isForeground=" + isForeground
3059 + ", isWhitelisted=" + isWhitelisted
3060 + ", oldRule=" + uidRulesToString(oldRule)
3061 + ", newRule=" + uidRulesToString(newRule)
3062 + ", newUidRules=" + uidRulesToString(newUidRules)
3063 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3064 }
3065
3066 if (newUidRules == RULE_NONE) {
3067 mUidRules.delete(uid);
3068 } else {
3069 mUidRules.put(uid, newUidRules);
3070 }
3071
3072 // Second step: notify listeners if state changed.
3073 if (newRule != oldRule) {
3074 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003075 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003076 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003077 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3078 } else {
3079 // All scenarios should have been covered above
3080 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3081 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003082 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003083 + ", newRule=" + uidRulesToString(newUidRules)
3084 + ", oldRule=" + uidRulesToString(oldUidRules));
3085 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003086 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003087 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003088 }
3089
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003090 private class AppIdleStateChangeListener
3091 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3092
3093 @Override
3094 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3095 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003096 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3097 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003098 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003099 synchronized (mUidRulesFirstLock) {
3100 updateRuleForAppIdleUL(uid);
3101 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003102 }
3103 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003104 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003105 }
3106
3107 @Override
3108 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003109 synchronized (mUidRulesFirstLock) {
3110 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003111 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003112 }
3113 }
3114
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003115 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3116 if (listener != null) {
3117 try {
3118 listener.onUidRulesChanged(uid, uidRules);
3119 } catch (RemoteException ignored) {
3120 }
3121 }
3122 }
3123
3124 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3125 String[] meteredIfaces) {
3126 if (listener != null) {
3127 try {
3128 listener.onMeteredIfacesChanged(meteredIfaces);
3129 } catch (RemoteException ignored) {
3130 }
3131 }
3132 }
3133
3134 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3135 boolean restrictBackground) {
3136 if (listener != null) {
3137 try {
3138 listener.onRestrictBackgroundChanged(restrictBackground);
3139 } catch (RemoteException ignored) {
3140 }
3141 }
3142 }
3143
3144 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3145 int uid, boolean whitelisted) {
3146 if (listener != null) {
3147 try {
3148 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3149 } catch (RemoteException ignored) {
3150 }
3151 }
3152 }
3153
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003154 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3155 int uid, boolean blacklisted) {
3156 if (listener != null) {
3157 try {
3158 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3159 } catch (RemoteException ignored) {
3160 }
3161 }
3162 }
3163
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003164 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003165 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003166 public boolean handleMessage(Message msg) {
3167 switch (msg.what) {
3168 case MSG_RULES_CHANGED: {
3169 final int uid = msg.arg1;
3170 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003171 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003172 final int length = mListeners.beginBroadcast();
3173 for (int i = 0; i < length; i++) {
3174 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003175 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003176 }
3177 mListeners.finishBroadcast();
3178 return true;
3179 }
3180 case MSG_METERED_IFACES_CHANGED: {
3181 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003182 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003183 final int length = mListeners.beginBroadcast();
3184 for (int i = 0; i < length; i++) {
3185 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003186 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003187 }
3188 mListeners.finishBroadcast();
3189 return true;
3190 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003191 case MSG_LIMIT_REACHED: {
3192 final String iface = (String) msg.obj;
3193
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003194 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003195 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003196 if (mMeteredIfaces.contains(iface)) {
3197 try {
3198 // force stats update to make sure we have
3199 // numbers that caused alert to trigger.
3200 mNetworkStats.forceUpdate();
3201 } catch (RemoteException e) {
3202 // ignored; service lives in system_server
3203 }
3204
Felipe Lemef0823852016-06-08 13:43:08 -07003205 updateNetworkEnabledNL();
3206 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003207 }
3208 }
3209 return true;
3210 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003211 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3212 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003213 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003214 final int length = mListeners.beginBroadcast();
3215 for (int i = 0; i < length; i++) {
3216 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003217 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003218 }
3219 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003220 final Intent intent =
3221 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3222 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3223 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3224 return true;
3225 }
3226 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003227 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3228 // - when an app is whitelisted
3229 // - when an app is blacklisted
3230 //
3231 // Whether the internal listeners (INetworkPolicyListener implementations) or
3232 // app broadcast receivers are notified depend on the following rules:
3233 //
3234 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3235 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3236 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003237 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003238 final boolean changed = msg.arg2 == 1;
3239 final Boolean whitelisted = (Boolean) msg.obj;
3240
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003241 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003242 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003243 final boolean whitelistedBool = whitelisted.booleanValue();
3244 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3245 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003246 final int length = mListeners.beginBroadcast();
3247 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003248 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003249 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3250 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003251 }
3252 mListeners.finishBroadcast();
3253 }
Felipe Leme9778f762016-01-27 14:46:39 -08003254 final PackageManager pm = mContext.getPackageManager();
3255 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003256 if (changed && packages != null) {
3257 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003258 final int userId = UserHandle.getUserId(uid);
3259 for (String packageName : packages) {
3260 final Intent intent = new Intent(
3261 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3262 intent.setPackage(packageName);
3263 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3264 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3265 }
Felipe Leme9778f762016-01-27 14:46:39 -08003266 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003267 return true;
3268 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003269 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3270 final int uid = msg.arg1;
3271 final boolean blacklisted = msg.arg2 == 1;
3272
3273 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3274 blacklisted);
3275 final int length = mListeners.beginBroadcast();
3276 for (int i = 0; i < length; i++) {
3277 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3278 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3279 blacklisted);
3280 }
3281 mListeners.finishBroadcast();
3282 return true;
3283 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003284 case MSG_ADVISE_PERSIST_THRESHOLD: {
3285 final long lowestRule = (Long) msg.obj;
3286 try {
3287 // make sure stats are recorded frequently enough; we aim
3288 // for 2MB threshold for 2GB/month rules.
3289 final long persistThreshold = lowestRule / 1000;
3290 mNetworkStats.advisePersistThreshold(persistThreshold);
3291 } catch (RemoteException e) {
3292 // ignored; service lives in system_server
3293 }
3294 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003295 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003296 case MSG_UPDATE_INTERFACE_QUOTA: {
3297 removeInterfaceQuota((String) msg.obj);
3298 // int params need to be stitched back into a long
3299 setInterfaceQuota((String) msg.obj,
3300 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3301 return true;
3302 }
3303 case MSG_REMOVE_INTERFACE_QUOTA: {
3304 removeInterfaceQuota((String) msg.obj);
3305 return true;
3306 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003307 default: {
3308 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003309 }
3310 }
3311 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003312 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003313
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003314 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003315 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003316 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003317 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003318 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003319 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003320 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003321 }
3322 }
3323
3324 private void removeInterfaceQuota(String iface) {
3325 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003326 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003327 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003328 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003329 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003330 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003331 }
3332 }
3333
Felipe Leme70c57c22016-03-29 10:45:13 -07003334 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3335 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003336 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003337 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003338 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003339 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3340 } catch (RemoteException e) {
3341 // ignored; service lives in system_server
3342 }
3343 }
3344
3345 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3346 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3347 try {
3348 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3349 } catch (IllegalStateException e) {
3350 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003351 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003352 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003353 }
3354 }
3355
Amith Yamasani15e472352015-04-24 19:06:07 -07003356 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003357 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3358 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3359 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003360 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003361 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003362 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003363 int size = uidRules.size();
3364 int[] uids = new int[size];
3365 int[] rules = new int[size];
3366 for(int index = size - 1; index >= 0; --index) {
3367 uids[index] = uidRules.keyAt(index);
3368 rules[index] = uidRules.valueAt(index);
3369 }
3370 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003371 } catch (IllegalStateException e) {
3372 Log.wtf(TAG, "problem setting firewall uid rules", e);
3373 } catch (RemoteException e) {
3374 // ignored; service lives in system_server
3375 }
3376 }
3377
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003378 /**
3379 * Add or remove a uid to the firewall blacklist for all network ifaces.
3380 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003381 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003382 if (chain == FIREWALL_CHAIN_DOZABLE) {
3383 mUidFirewallDozableRules.put(uid, rule);
3384 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3385 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003386 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3387 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003388 }
3389
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003390 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003391 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003392 } catch (IllegalStateException e) {
3393 Log.wtf(TAG, "problem setting firewall uid rules", e);
3394 } catch (RemoteException e) {
3395 // ignored; service lives in system_server
3396 }
3397 }
3398
3399 /**
3400 * Add or remove a uid to the firewall blacklist for all network ifaces.
3401 */
Felipe Lemef0823852016-06-08 13:43:08 -07003402 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003403 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3404 mFirewallChainStates.get(chain) == enable) {
3405 // All is the same, nothing to do.
3406 return;
3407 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003408 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003409 try {
3410 mNetworkManager.setFirewallChainEnabled(chain, enable);
3411 } catch (IllegalStateException e) {
3412 Log.wtf(TAG, "problem enable firewall chain", e);
3413 } catch (RemoteException e) {
3414 // ignored; service lives in system_server
3415 }
3416 }
3417
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003418 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3419 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003420 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003421 } catch (RuntimeException e) {
3422 Slog.w(TAG, "problem reading network stats: " + e);
3423 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003424 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003425 // ignored; service lives in system_server
3426 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003427 }
3428 }
3429
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003430 private boolean isBandwidthControlEnabled() {
3431 final long token = Binder.clearCallingIdentity();
3432 try {
3433 return mNetworkManager.isBandwidthControlEnabled();
3434 } catch (RemoteException e) {
3435 // ignored; service lives in system_server
3436 return false;
3437 } finally {
3438 Binder.restoreCallingIdentity(token);
3439 }
3440 }
3441
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003442 /**
3443 * Try refreshing {@link #mTime} when stale.
3444 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003445 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003446 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003447 mTime.forceRefresh();
3448 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003449 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003450
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003451 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003452 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3453 }
3454
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003455 private static Intent buildAllowBackgroundDataIntent() {
3456 return new Intent(ACTION_ALLOW_BACKGROUND);
3457 }
3458
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003459 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3460 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3461 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3462 return intent;
3463 }
3464
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003465 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3466 final Intent intent = new Intent();
3467 intent.setComponent(new ComponentName(
3468 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3469 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3470 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3471 return intent;
3472 }
3473
3474 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3475 final Intent intent = new Intent();
3476 intent.setComponent(new ComponentName(
3477 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3478 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3479 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3480 return intent;
3481 }
3482
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003483 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003484 public void addIdleHandler(IdleHandler handler) {
3485 mHandler.getLooper().getQueue().addIdleHandler(handler);
3486 }
3487
Jeff Sharkey1b861272011-05-22 00:34:52 -07003488 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3489 final int size = source.size();
3490 for (int i = 0; i < size; i++) {
3491 target.put(source.keyAt(i), true);
3492 }
3493 }
3494
Stuart Scottf1fb3972015-04-02 18:00:02 -07003495 @Override
3496 public void factoryReset(String subscriber) {
3497 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3498
Stuart Scotte3e314d2015-04-20 14:07:45 -07003499 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3500 return;
3501 }
3502
Stuart Scottf1fb3972015-04-02 18:00:02 -07003503 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003504 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003505 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3506 for (NetworkPolicy policy : policies) {
3507 if (policy.template.equals(template)) {
3508 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3509 policy.inferred = false;
3510 policy.clearSnooze();
3511 }
3512 }
3513 setNetworkPolicies(policies);
3514
3515 // Turn restrict background data off
3516 setRestrictBackground(false);
3517
Stuart Scotte3e314d2015-04-20 14:07:45 -07003518 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3519 // Remove app's "restrict background data" flag
3520 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3521 setUidPolicy(uid, POLICY_NONE);
3522 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003523 }
3524 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003525
3526 private class MyPackageMonitor extends PackageMonitor {
3527
3528 @Override
3529 public void onPackageRemoved(String packageName, int uid) {
3530 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003531 synchronized (mUidRulesFirstLock) {
3532 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3533 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003534 }
3535 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003536 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003537
3538 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3539
3540 @Override
3541 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003542 synchronized (mUidRulesFirstLock) {
3543 boolean changed = removeUserStateUL(userId, false);
3544 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003545 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003546 synchronized (mNetworkPoliciesSecondLock) {
3547 writePolicyAL();
3548 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003549 }
3550 }
3551 }
3552 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003553}