blob: b382a3b395842d432c54b8a72bd52a50ece71be8 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
128import android.net.wifi.WifiInfo;
129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700136import android.os.IPowerManager;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700141import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700142import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600143import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700145import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700146import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700147import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800148import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700149import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400150import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700151import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700152import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700153import android.util.ArrayMap;
154import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700155import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700156import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700157import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700159import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700160import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161import android.util.SparseBooleanArray;
162import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.TrustedTime;
164import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165
Jeff Sharkey497e4432011-06-14 17:27:29 -0700166import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700167import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800168import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800169import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800170import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700172import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700173import com.android.server.DeviceIdleController;
174import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800176import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600177
178import libcore.io.IoUtils;
179
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181
182import org.xmlpull.v1.XmlPullParser;
183import org.xmlpull.v1.XmlPullParserException;
184import org.xmlpull.v1.XmlSerializer;
185
186import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700187import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import java.io.FileInputStream;
189import java.io.FileNotFoundException;
190import java.io.FileOutputStream;
191import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700192import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700193import java.lang.annotation.Retention;
194import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100195import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import java.util.ArrayList;
197import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700198import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700200/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700201 * Service that maintains low-level network policy rules, using
202 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 * <p>
204 * Derives active rules by combining a given policy with other system status,
205 * and delivers to listeners, such as {@link ConnectivityManager}, for
206 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700207 *
208 * <p>
209 * This class uses 2-3 locks to synchronize state:
210 * <ul>
211 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
212 * rules).
213 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
214 * as network policies).
215 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
216 * must be held.
217 * </ul>
218 *
219 * <p>
220 * As such, methods that require synchronization have the following prefixes:
221 * <ul>
222 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
223 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
224 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
225 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
226 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700227 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700228public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800229 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700230 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700231 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700232
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700233 private static final int VERSION_INIT = 1;
234 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700235 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800236 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800237 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800238 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700239 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700240 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700241 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700242 private static final int VERSION_SWITCH_UID = 10;
243 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700248 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700250 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700251
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700252 private static final String TAG_POLICY_LIST = "policy-list";
253 private static final String TAG_NETWORK_POLICY = "network-policy";
254 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700255 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800256 private static final String TAG_WHITELIST = "whitelist";
257 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800258 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259
260 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700261 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700262 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
263 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700264 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800266 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267 private static final String ATTR_WARNING_BYTES = "warningBytes";
268 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700269 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800270 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
271 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800272 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700273 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700275 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 private static final String ATTR_POLICY = "policy";
277
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800279 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800280 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800281 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
284
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700285 private static final int MSG_RULES_CHANGED = 1;
286 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800287 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800288 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700289 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700290 private static final int MSG_SCREEN_ON_CHANGED = 8;
Felipe Leme9778f762016-01-27 14:46:39 -0800291 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700292 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
293 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700294 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700295
Jeff Sharkey75279902011-05-24 18:39:45 -0700296 private final Context mContext;
297 private final IActivityManager mActivityManager;
298 private final IPowerManager mPowerManager;
299 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700300 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700301 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700303 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304
305 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700306 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700307 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700308 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700309
Felipe Lemef0823852016-06-08 13:43:08 -0700310 // See main javadoc for instructions on how to use these locks.
311 final Object mUidRulesFirstLock = new Object();
312 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700313
Felipe Lemef0823852016-06-08 13:43:08 -0700314 @GuardedBy("allLocks") volatile boolean mSystemReady;
315
316 @GuardedBy("mUidRulesFirstLock") volatile boolean mScreenOn;
317 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
318 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
319 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700320
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700321 private final boolean mSuppressDefaultPolicy;
322
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700323 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800324 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700325 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800326 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700327
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700328 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700329 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700331 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700332
Felipe Lemef0823852016-06-08 13:43:08 -0700333 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700334 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700335 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700336 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700337 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800338 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700339
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700340 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700341 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700342 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
343
Jeff Sharkey32566012014-12-02 18:30:14 -0800344 /**
345 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700346 * in power save mode, except device idle (doze) still applies.
347 * TODO: An int array might be sufficient
348 */
Felipe Lemef0823852016-06-08 13:43:08 -0700349 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700350 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
351
352 /**
353 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800354 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700355 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800356 */
Felipe Lemef0823852016-06-08 13:43:08 -0700357 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700358 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700359
Felipe Lemef0823852016-06-08 13:43:08 -0700360 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700361 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
362
Felipe Lemeb85a6372016-01-14 16:16:16 -0800363 /**
364 * UIDs that have been white-listed to avoid restricted background.
365 */
Felipe Lemef0823852016-06-08 13:43:08 -0700366 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800367 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
368
Felipe Lemea9505cc2016-02-26 10:28:41 -0800369 /**
370 * UIDs that have been initially white-listed by system to avoid restricted background.
371 */
Felipe Lemef0823852016-06-08 13:43:08 -0700372 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800373 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
374 new SparseBooleanArray();
375
376 /**
377 * UIDs that have been initially white-listed by system to avoid restricted background,
378 * but later revoked by user.
379 */
Felipe Lemef0823852016-06-08 13:43:08 -0700380 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800381 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
382 new SparseBooleanArray();
383
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700384 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800386 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700387 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800389 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700390
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700391 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700393 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700394
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700395 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700396 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800397 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700398
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600399 /** Higher priority listener before general event dispatch */
400 private INetworkPolicyListener mConnectivityListener;
401
Jeff Sharkey32566012014-12-02 18:30:14 -0800402 private final RemoteCallbackList<INetworkPolicyListener>
403 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700404
Dianne Hackborn497175b2014-07-01 12:56:08 -0700405 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700406
Felipe Lemef0823852016-06-08 13:43:08 -0700407 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700408 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700409
Svet Ganov16a16892015-04-16 10:32:04 -0700410 private final AppOpsManager mAppOps;
411
Felipe Lemeb85a6372016-01-14 16:16:16 -0800412 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800413 private final IPackageManager mIPm;
414
Felipe Lemeb85a6372016-01-14 16:16:16 -0800415
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700416 // TODO: keep whitelist of system-critical services that should never have
417 // rules enforced, such as system, phone, and radio UIDs.
418
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 // TODO: migrate notifications to SystemUI
420
Jeff Sharkey75279902011-05-24 18:39:45 -0700421 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700422 IPowerManager powerManager, INetworkStatsService networkStats,
423 INetworkManagementService networkManagement) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700424 this(context, activityManager, powerManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700425 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700426 }
427
428 private static File getSystemDir() {
429 return new File(Environment.getDataDirectory(), "system");
430 }
431
432 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700433 IPowerManager powerManager, INetworkStatsService networkStats,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700434 INetworkManagementService networkManagement, TrustedTime time, File systemDir,
435 boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700436 mContext = checkNotNull(context, "missing context");
437 mActivityManager = checkNotNull(activityManager, "missing activityManager");
438 mPowerManager = checkNotNull(powerManager, "missing powerManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700439 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700440 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700441 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700442 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700444 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800445 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700446
Amith Yamasani450a16b2013-09-18 16:28:50 -0700447 HandlerThread thread = new HandlerThread(TAG);
448 thread.start();
449 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700450
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700451 mSuppressDefaultPolicy = suppressDefaultPolicy;
452
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700453 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700454
455 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800456
457 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700458
459 // Expose private service for system components to use.
460 LocalServices.addService(NetworkPolicyManagerInternal.class,
461 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700462 }
463
464 public void bindConnectivityManager(IConnectivityManager connManager) {
465 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700466 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700467
Jeff Sharkey497e4432011-06-14 17:27:29 -0700468 public void bindNotificationManager(INotificationManager notifManager) {
469 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
470 }
471
Felipe Lemef0823852016-06-08 13:43:08 -0700472 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700473 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700474 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
475 mPowerSaveWhitelistExceptIdleAppIds.clear();
476 if (whitelist != null) {
477 for (int uid : whitelist) {
478 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
479 }
480 }
481 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700482 mPowerSaveWhitelistAppIds.clear();
483 if (whitelist != null) {
484 for (int uid : whitelist) {
485 mPowerSaveWhitelistAppIds.put(uid, true);
486 }
487 }
488 } catch (RemoteException e) {
489 }
490 }
491
Felipe Lemea9505cc2016-02-26 10:28:41 -0800492 /**
493 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
494 * revoke the whitelist.
495 *
496 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
497 */
Felipe Lemef0823852016-06-08 13:43:08 -0700498 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800499 final List<UserInfo> users = mUserManager.getUsers();
500 final int numberUsers = users.size();
501
Felipe Lemea110eec2016-04-29 09:58:06 -0700502 boolean changed = false;
503 for (int i = 0; i < numberUsers; i++) {
504 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700505 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700506 }
507 return changed;
508 }
509
Felipe Lemef0823852016-06-08 13:43:08 -0700510 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700511 final SystemConfig sysConfig = SystemConfig.getInstance();
512 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800513 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
514 boolean changed = false;
515 for (int i = 0; i < allowDataUsage.size(); i++) {
516 final String pkg = allowDataUsage.valueAt(i);
517 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700518 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
519 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800520 final ApplicationInfo app;
521 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700522 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800523 } catch (PackageManager.NameNotFoundException e) {
524 // Should not happen
525 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
526 continue;
527 }
528 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700529 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800530 continue;
531 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700532 final int uid = UserHandle.getUid(userId, app.uid);
533 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
534 if (LOGD)
535 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
536 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800537 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700538 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
539 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
540 + userId + ") to restrict background whitelist");
541 mRestrictBackgroundWhitelistUids.append(uid, true);
542 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800543 }
544 }
545 return changed;
546 }
547
Felipe Lemef0823852016-06-08 13:43:08 -0700548 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700549 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700550 // Clear the states of the current whitelist
551 final int N = mPowerSaveTempWhitelistAppIds.size();
552 for (int i = 0; i < N; i++) {
553 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
554 }
555 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700556 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700557 if (whitelist != null) {
558 for (int uid : whitelist) {
559 mPowerSaveTempWhitelistAppIds.put(uid, true);
560 }
561 }
562 } catch (RemoteException e) {
563 }
564 }
565
Amith Yamasani06f08062015-06-12 13:23:33 -0700566 /**
567 * Remove unnecessary entries in the temp whitelist
568 */
Felipe Lemef0823852016-06-08 13:43:08 -0700569 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700570 final int N = mPowerSaveTempWhitelistAppIds.size();
571 for (int i = N - 1; i >= 0; i--) {
572 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
573 mPowerSaveTempWhitelistAppIds.removeAt(i);
574 }
575 }
576 }
577
Jeff Sharkeya4620792011-05-20 15:29:23 -0700578 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700579 if (!isBandwidthControlEnabled()) {
580 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
581 return;
582 }
583
Amith Yamasani15e472352015-04-24 19:06:07 -0700584 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
585
Felipe Lemeb85a6372016-01-14 16:16:16 -0800586 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
587
Felipe Lemef0823852016-06-08 13:43:08 -0700588 synchronized (mUidRulesFirstLock) {
589 synchronized (mNetworkPoliciesSecondLock) {
590 updatePowerSaveWhitelistUL();
591 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
592 mPowerManagerInternal.registerLowPowerModeObserver(
593 new PowerManagerInternal.LowPowerModeListener() {
594 @Override
595 public void onLowPowerModeChanged(boolean enabled) {
596 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
597 synchronized (mUidRulesFirstLock) {
598 if (mRestrictPower != enabled) {
599 mRestrictPower = enabled;
600 updateRulesForRestrictPowerUL();
601 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700602 }
603 }
Felipe Lemef0823852016-06-08 13:43:08 -0700604 });
605 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
606
607 mSystemReady = true;
608
609 // read policy from disk
610 readPolicyAL();
611
612 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
613 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700614 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700615
Felipe Lemef0823852016-06-08 13:43:08 -0700616 setRestrictBackgroundUL(mRestrictBackground);
617 updateRulesForGlobalChangeAL(false);
618 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700620 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700621
Jeff Sharkeya4620792011-05-20 15:29:23 -0700622 updateScreenOn();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700623
Jeff Sharkeya4620792011-05-20 15:29:23 -0700624 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700625 mActivityManager.registerUidObserver(mUidObserver,
626 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700627 mNetworkManager.registerObserver(mAlertObserver);
628 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700629 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700630 }
631
Jeff Sharkeya4620792011-05-20 15:29:23 -0700632 // TODO: traverse existing processes to know foreground state, or have
633 // activitymanager dispatch current state when new observer attached.
634
635 final IntentFilter screenFilter = new IntentFilter();
636 screenFilter.addAction(Intent.ACTION_SCREEN_ON);
637 screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
Jeff Sharkey0abe5562012-06-19 13:32:22 -0700638 mContext.registerReceiver(mScreenReceiver, screenFilter);
Jeff Sharkeya4620792011-05-20 15:29:23 -0700639
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700640 // listen for changes to power save whitelist
641 final IntentFilter whitelistFilter = new IntentFilter(
642 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
643 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
644
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700645 DeviceIdleController.LocalService deviceIdleService
646 = LocalServices.getService(DeviceIdleController.LocalService.class);
647 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
648
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700649 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900650 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700651 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
652
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700653 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700654 final IntentFilter packageFilter = new IntentFilter();
655 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700656 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700657 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700658
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700659 // listen for UID changes to update policy
660 mContext.registerReceiver(
661 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
662
663 // listen for user changes to update policy
664 final IntentFilter userFilter = new IntentFilter();
665 userFilter.addAction(ACTION_USER_ADDED);
666 userFilter.addAction(ACTION_USER_REMOVED);
667 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
668
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700669 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700670 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
671 mContext.registerReceiver(
672 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
673
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700674 // listen for restrict background changes from notifications
675 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
676 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
677
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800678 // listen for snooze warning from notifications
679 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
680 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
681 MANAGE_NETWORK_POLICY, mHandler);
682
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700683 // listen for configured wifi networks to be removed
684 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700685 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700686
687 // listen for wifi state changes to catch metered hint
688 final IntentFilter wifiStateFilter = new IntentFilter(
689 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700690 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700691
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700692 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700693
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700694 }
695
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700696 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700697 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700698 synchronized (mUidRulesFirstLock) {
699 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700700 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700701 }
702
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700703 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700704 synchronized (mUidRulesFirstLock) {
705 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700706 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700707 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700708
709 @Override public void onUidActive(int uid) throws RemoteException {
710 }
711
712 @Override public void onUidIdle(int uid) throws RemoteException {
713 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700714 };
715
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700716 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700717 @Override
718 public void onReceive(Context context, Intent intent) {
719 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700720 synchronized (mUidRulesFirstLock) {
721 updatePowerSaveWhitelistUL();
722 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700723 }
724 }
725 };
726
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700727 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
728 @Override
729 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700730 synchronized (mUidRulesFirstLock) {
731 updatePowerSaveTempWhitelistUL();
732 updateRulesForTempWhitelistChangeUL();
733 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700734 }
735 }
736 };
737
738 final private BroadcastReceiver mScreenReceiver = new BroadcastReceiver() {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700739 @Override
740 public void onReceive(Context context, Intent intent) {
Jeff Sharkey29afa142012-12-04 17:21:21 -0800741 // screen-related broadcasts are protected by system, no need
742 // for permissions check.
743 mHandler.obtainMessage(MSG_SCREEN_ON_CHANGED).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700744 }
745 };
746
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700747 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700748 @Override
749 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700750 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700751
752 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700753 final int uid = intent.getIntExtra(EXTRA_UID, -1);
754 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700755
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700756 if (ACTION_PACKAGE_ADDED.equals(action)) {
757 // update rules for UID, since it might be subject to
758 // global background data policy
759 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700760 synchronized (mUidRulesFirstLock) {
761 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700762 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700763 }
764 }
765 };
766
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700767 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700768 @Override
769 public void onReceive(Context context, Intent intent) {
770 // on background handler thread, and UID_REMOVED is protected
771
772 final int uid = intent.getIntExtra(EXTRA_UID, -1);
773 if (uid == -1) return;
774
775 // remove any policy and update rules to clean up
776 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700777 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700778 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700779 updateRestrictionRulesForUidUL(uid);
780 synchronized (mNetworkPoliciesSecondLock) {
781 writePolicyAL();
782 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700783 }
784 }
785 };
786
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700787 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700788 @Override
789 public void onReceive(Context context, Intent intent) {
790 // on background handler thread, and USER_ADDED and USER_REMOVED
791 // broadcasts are protected
792
793 final String action = intent.getAction();
794 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
795 if (userId == -1) return;
796
Amith Yamasani15e472352015-04-24 19:06:07 -0700797 switch (action) {
798 case ACTION_USER_REMOVED:
799 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700800 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800801 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700802 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700803 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700804 if (action == ACTION_USER_ADDED) {
805 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700806 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700807 }
808 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700809 synchronized (mNetworkPoliciesSecondLock) {
810 updateRulesForGlobalChangeAL(true);
811 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700812 }
813 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700814 }
815 }
816 };
817
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700818 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700819 * Receiver that watches for {@link INetworkStatsService} updates, which we
820 * use to check against {@link NetworkPolicy#warningBytes}.
821 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700822 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700823 @Override
824 public void onReceive(Context context, Intent intent) {
825 // on background handler thread, and verified
826 // READ_NETWORK_USAGE_HISTORY permission above.
827
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800828 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700829 synchronized (mNetworkPoliciesSecondLock) {
830 updateNetworkEnabledNL();
831 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700832 }
833 }
834 };
835
836 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700837 * Receiver that watches for {@link Notification} control of
838 * {@link #mRestrictBackground}.
839 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700840 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700841 @Override
842 public void onReceive(Context context, Intent intent) {
843 // on background handler thread, and verified MANAGE_NETWORK_POLICY
844 // permission above.
845
846 setRestrictBackground(false);
847 }
848 };
849
850 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800851 * Receiver that watches for {@link Notification} control of
852 * {@link NetworkPolicy#lastWarningSnooze}.
853 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700854 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800855 @Override
856 public void onReceive(Context context, Intent intent) {
857 // on background handler thread, and verified MANAGE_NETWORK_POLICY
858 // permission above.
859
860 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
861 performSnooze(template, TYPE_WARNING);
862 }
863 };
864
865 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700866 * Receiver that watches for {@link WifiConfiguration} to be changed.
867 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700868 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700869 @Override
870 public void onReceive(Context context, Intent intent) {
871 // on background handler thread, and verified CONNECTIVITY_INTERNAL
872 // permission above.
873
874 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
875 if (reason == CHANGE_REASON_REMOVED) {
876 final WifiConfiguration config = intent.getParcelableExtra(
877 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700878 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800879 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700880 synchronized (mUidRulesFirstLock) {
881 synchronized (mNetworkPoliciesSecondLock) {
882 if (mNetworkPolicy.containsKey(template)) {
883 mNetworkPolicy.remove(template);
884 writePolicyAL();
885 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700886 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700887 }
888 }
889 }
890 }
891 };
892
893 /**
894 * Receiver that watches {@link WifiInfo} state changes to infer metered
895 * state. Ignores hints when policy is user-defined.
896 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700897 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700898 @Override
899 public void onReceive(Context context, Intent intent) {
900 // on background handler thread, and verified CONNECTIVITY_INTERNAL
901 // permission above.
902
903 // ignore when not connected
904 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
905 if (!netInfo.isConnected()) return;
906
907 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
908 final boolean meteredHint = info.getMeteredHint();
909
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800910 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700911 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700912 NetworkPolicy policy = mNetworkPolicy.get(template);
913 if (policy == null && meteredHint) {
914 // policy doesn't exist, and AP is hinting that it's
915 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800916 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700917 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700918
919 } else if (policy != null && policy.inferred) {
920 // policy exists, and was inferred: update its current
921 // metered state.
922 policy.metered = meteredHint;
923
924 // since this is inferred for each wifi session, just update
925 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700926 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700927 }
928 }
929 }
930 };
931
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800932 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
933 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
934 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
935 metered, true);
936 }
937
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700938 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700939 * Observer that watches for {@link INetworkManagementService} alerts.
940 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private INetworkManagementEventObserver mAlertObserver
942 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700943 @Override
944 public void limitReached(String limitName, String iface) {
945 // only someone like NMS should be calling us
946 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
947
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800948 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
949 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 }
951 }
952 };
953
954 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700955 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
956 * to show visible notifications as needed.
957 */
Felipe Lemef0823852016-06-08 13:43:08 -0700958 void updateNotificationsNL() {
959 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700960
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700961 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700962 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700963 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700964
965 // TODO: when switching to kernel notifications, compute next future
966 // cycle boundary to recompute notifications.
967
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700968 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800969 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700970 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
971 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 // ignore policies that aren't relevant to user
973 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700974 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700975
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 final long start = computeLastCycleBoundary(currentTime, policy);
977 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700978 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700979
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700980 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800981 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700982 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
983 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700984 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700985 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700986 }
987
Jeff Sharkey497e4432011-06-14 17:27:29 -0700988 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700989 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700990
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800991 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700992 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700993 }
994 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700995 }
996
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700997 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700998 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
999 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001000 if (!mActiveNotifs.contains(tag)) {
1001 cancelNotification(tag);
1002 }
1003 }
1004 }
1005
1006 /**
1007 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001008 * current device state, such as when
1009 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1010 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 */
1012 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001013 if (template.isMatchRuleMobile()) {
1014 final TelephonyManager tele = TelephonyManager.from(mContext);
1015 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001016
Jeff Sharkey32566012014-12-02 18:30:14 -08001017 // Mobile template is relevant when any active subscriber matches
1018 final int[] subIds = sub.getActiveSubscriptionIdList();
1019 for (int subId : subIds) {
1020 final String subscriberId = tele.getSubscriberId(subId);
1021 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001022 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001023 if (template.matches(probeIdent)) {
1024 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001025 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001026 }
1027 return false;
1028 } else {
1029 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001030 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001031 }
1032
1033 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 * Notify that given {@link NetworkTemplate} is over
1035 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1036 */
Felipe Lemef0823852016-06-08 13:43:08 -07001037 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 if (!mOverLimitNotified.contains(template)) {
1039 mContext.startActivity(buildNetworkOverLimitIntent(template));
1040 mOverLimitNotified.add(template);
1041 }
1042 }
1043
Felipe Lemef0823852016-06-08 13:43:08 -07001044 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 mOverLimitNotified.remove(template);
1046 }
1047
1048 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049 * Build unique tag that identifies an active {@link NetworkPolicy}
1050 * notification of a specific type, like {@link #TYPE_LIMIT}.
1051 */
1052 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001053 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001054 }
1055
1056 /**
1057 * Show notification for combined {@link NetworkPolicy} and specific type,
1058 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1059 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001060 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001061 final String tag = buildNotificationTag(policy, type);
1062 final Notification.Builder builder = new Notification.Builder(mContext);
1063 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001064 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001065 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001066 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001067
1068 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001069 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 switch (type) {
1071 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001072 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001073 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001075 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001076 builder.setTicker(title);
1077 builder.setContentTitle(title);
1078 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001079
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001080 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1081 builder.setDeleteIntent(PendingIntent.getBroadcast(
1082 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1083
1084 final Intent viewIntent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001085 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001086 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1087
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 break;
1089 }
1090 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001091 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001092
1093 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001094 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001095 switch (policy.template.getMatchRule()) {
1096 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001097 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001098 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001099 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001100 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001101 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001102 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001103 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001104 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001105 case MATCH_WIFI:
1106 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001107 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001108 break;
1109 default:
1110 title = null;
1111 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001112 }
1113
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001114 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001115 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 builder.setTicker(title);
1117 builder.setContentTitle(title);
1118 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001119
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001120 final Intent intent = buildNetworkOverLimitIntent(policy.template);
1121 builder.setContentIntent(PendingIntent.getActivity(
1122 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1123 break;
1124 }
1125 case TYPE_LIMIT_SNOOZED: {
1126 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001127 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 Formatter.formatFileSize(mContext, overBytes));
1129
1130 final CharSequence title;
1131 switch (policy.template.getMatchRule()) {
1132 case MATCH_MOBILE_3G_LOWER:
1133 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1134 break;
1135 case MATCH_MOBILE_4G:
1136 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1137 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001138 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001139 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1140 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001141 case MATCH_WIFI:
1142 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1143 break;
1144 default:
1145 title = null;
1146 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 }
1148
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001149 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001150 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001151 builder.setTicker(title);
1152 builder.setContentTitle(title);
1153 builder.setContentText(body);
1154
1155 final Intent intent = buildViewDataUsageIntent(policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001156 builder.setContentIntent(PendingIntent.getActivity(
1157 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001158 break;
1159 }
1160 }
1161
1162 // TODO: move to NotificationManager once we can mock it
1163 try {
1164 final String packageName = mContext.getPackageName();
1165 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001166 if(!TextUtils.isEmpty(body)) {
1167 builder.setStyle(new Notification.BigTextStyle()
1168 .bigText(body));
1169 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001170 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001171 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001172 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001173 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001174 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001175 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001176 }
1177 }
1178
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001179 private void cancelNotification(String tag) {
1180 // TODO: move to NotificationManager once we can mock it
1181 try {
1182 final String packageName = mContext.getPackageName();
1183 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001184 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001185 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001186 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001187 }
1188 }
1189
1190 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001191 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001192 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001193 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001194 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001195 @Override
1196 public void onReceive(Context context, Intent intent) {
1197 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1198 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001199
1200 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001201 synchronized (mNetworkPoliciesSecondLock) {
1202 ensureActiveMobilePolicyNL();
1203 normalizePoliciesNL();
1204 updateNetworkEnabledNL();
1205 updateNetworkRulesNL();
1206 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 }
1208 }
1209 };
1210
1211 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001212 * Proactively control network data connections when they exceed
1213 * {@link NetworkPolicy#limitBytes}.
1214 */
Felipe Lemef0823852016-06-08 13:43:08 -07001215 void updateNetworkEnabledNL() {
1216 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001217
1218 // TODO: reset any policy-disabled networks when any policy is removed
1219 // completely, which is currently rare case.
1220
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001221 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001222 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1223 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001224 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001225 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001226 setNetworkTemplateEnabled(policy.template, true);
1227 continue;
1228 }
1229
1230 final long start = computeLastCycleBoundary(currentTime, policy);
1231 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001232 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001233
1234 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001235 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1236 && policy.lastLimitSnooze < start;
1237 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001238
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001239 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 }
1241 }
1242
1243 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001244 * Proactively disable networks that match the given
1245 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001246 */
1247 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001248 // TODO: reach into ConnectivityManager to proactively disable bringing
1249 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001250
1251 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1252 // If mobile data usage hits the limit or if the user resumes the data, we need to
1253 // notify telephony.
1254 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1255 final TelephonyManager tm = TelephonyManager.from(mContext);
1256
1257 final int[] subIds = sm.getActiveSubscriptionIdList();
1258 for (int subId : subIds) {
1259 final String subscriberId = tm.getSubscriberId(subId);
1260 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1261 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1262 // Template is matched when subscriber id matches.
1263 if (template.matches(probeIdent)) {
1264 tm.setPolicyDataEnabled(enabled, subId);
1265 }
1266 }
1267 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001268 }
1269
1270 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 * Examine all connected {@link NetworkState}, looking for
1272 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1273 * remaining quota based on usage cycle and historical stats.
1274 */
Felipe Lemef0823852016-06-08 13:43:08 -07001275 void updateNetworkRulesNL() {
1276 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001277
1278 final NetworkState[] states;
1279 try {
1280 states = mConnManager.getAllNetworkState();
1281 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001282 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001283 return;
1284 }
1285
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001286 // First, generate identities of all connected networks so we can
1287 // quickly compare them against all defined policies below.
1288 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001289 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001290 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001291 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001292 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001293
1294 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001295 if (baseIface != null) {
1296 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001297 }
1298
1299 // Stacked interfaces are considered to have same identity as
1300 // their parent network.
1301 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1302 for (LinkProperties stackedLink : stackedLinks) {
1303 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001304 if (stackedIface != null) {
1305 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001306 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001307 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 }
1309 }
1310
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001311 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001312 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001313 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001314 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001315 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001317 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001318 for (int j = connIdents.size() - 1; j >= 0; j--) {
1319 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1320 if (policy.template.matches(ident.second)) {
1321 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 }
1323 }
1324
1325 if (ifaceList.size() > 0) {
1326 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001327 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001328 }
1329 }
1330
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001331 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001332 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001333
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334 // apply each policy that we found ifaces for; compute remaining data
1335 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001336 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001337 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1338 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1339 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001341 final long start;
1342 final long totalBytes;
1343 if (policy.hasCycle()) {
1344 start = computeLastCycleBoundary(currentTime, policy);
1345 totalBytes = getTotalBytes(policy.template, start, currentTime);
1346 } else {
1347 start = Long.MAX_VALUE;
1348 totalBytes = 0;
1349 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001350
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001351 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001352 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001353 }
1354
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001355 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001357 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001358 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001359 if (!hasLimit) {
1360 // metered network, but no policy limit; we still need to
1361 // restrict apps, so push really high quota.
1362 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001363 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001364 // snoozing past quota, but we still need to restrict apps,
1365 // so push really high quota.
1366 quotaBytes = Long.MAX_VALUE;
1367 } else {
1368 // remaining "quota" bytes are based on total usage in
1369 // current cycle. kernel doesn't like 0-byte rules, so we
1370 // set 1-byte quota and disable the radio later.
1371 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1372 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001373
1374 if (ifaces.length > 1) {
1375 // TODO: switch to shared quota once NMS supports
1376 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001377 }
1378
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001379 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001380 // long quotaBytes split up into two ints to fit in message
1381 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1382 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1383 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001384 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001385 }
1386 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001387
1388 // keep track of lowest warning or limit of active policies
1389 if (hasWarning && policy.warningBytes < lowestRule) {
1390 lowestRule = policy.warningBytes;
1391 }
1392 if (hasLimit && policy.limitBytes < lowestRule) {
1393 lowestRule = policy.limitBytes;
1394 }
1395 }
1396
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001397 for (int i = connIfaces.size()-1; i >= 0; i--) {
1398 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001399 // long quotaBytes split up into two ints to fit in message
1400 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1401 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1402 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001403 newMeteredIfaces.add(iface);
1404 }
1405
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001406 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001407
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001408 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001409 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1410 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001411 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001412 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1413 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001414 }
1415 }
1416 mMeteredIfaces = newMeteredIfaces;
1417
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001418 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001419 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001420 }
1421
1422 /**
1423 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1424 * have at least a default mobile policy defined.
1425 */
Felipe Lemef0823852016-06-08 13:43:08 -07001426 private void ensureActiveMobilePolicyNL() {
1427 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001428 if (mSuppressDefaultPolicy) return;
1429
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001430 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001431 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001432
Jeff Sharkey32566012014-12-02 18:30:14 -08001433 final int[] subIds = sub.getActiveSubscriptionIdList();
1434 for (int subId : subIds) {
1435 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001436 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001437 }
1438 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001439
Felipe Lemef0823852016-06-08 13:43:08 -07001440 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001441 // Poke around to see if we already have a policy
1442 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001443 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001444 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1445 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1446 if (template.matches(probeIdent)) {
1447 if (LOGD) {
1448 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1449 + NetworkIdentity.scrubSubscriberId(subscriberId));
1450 }
1451 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001452 }
1453 }
1454
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1456 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001457
Jeff Sharkey32566012014-12-02 18:30:14 -08001458 // Build default mobile policy, and assume usage cycle starts today
1459 final long warningBytes = mContext.getResources().getInteger(
1460 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001461
Jeff Sharkey32566012014-12-02 18:30:14 -08001462 final Time time = new Time();
1463 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001464
Jeff Sharkey32566012014-12-02 18:30:14 -08001465 final int cycleDay = time.monthDay;
1466 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001467
Jeff Sharkey32566012014-12-02 18:30:14 -08001468 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1469 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1470 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001471 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001472 }
1473
Felipe Lemef0823852016-06-08 13:43:08 -07001474 private void readPolicyAL() {
1475 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001476
1477 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001478 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001479 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001480
1481 FileInputStream fis = null;
1482 try {
1483 fis = mPolicyFile.openRead();
1484 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001485 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486
1487 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001488 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001489 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001490 while ((type = in.next()) != END_DOCUMENT) {
1491 final String tag = in.getName();
1492 if (type == START_TAG) {
1493 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001494 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001496 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1497 mRestrictBackground = readBooleanAttribute(
1498 in, ATTR_RESTRICT_BACKGROUND);
1499 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001500 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001501 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001502 if (mRestrictBackground != oldValue) {
1503 // Some early services may have read the default value,
1504 // so notify them that it's changed
1505 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1506 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1507 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001508
1509 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1510 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1511 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001512 final String networkId;
1513 if (version >= VERSION_ADDED_NETWORK_ID) {
1514 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1515 } else {
1516 networkId = null;
1517 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001518 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001519 final String cycleTimezone;
1520 if (version >= VERSION_ADDED_TIMEZONE) {
1521 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1522 } else {
1523 cycleTimezone = Time.TIMEZONE_UTC;
1524 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001525 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1526 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001527 final long lastLimitSnooze;
1528 if (version >= VERSION_SPLIT_SNOOZE) {
1529 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1530 } else if (version >= VERSION_ADDED_SNOOZE) {
1531 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001532 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001533 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001534 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001535 final boolean metered;
1536 if (version >= VERSION_ADDED_METERED) {
1537 metered = readBooleanAttribute(in, ATTR_METERED);
1538 } else {
1539 switch (networkTemplate) {
1540 case MATCH_MOBILE_3G_LOWER:
1541 case MATCH_MOBILE_4G:
1542 case MATCH_MOBILE_ALL:
1543 metered = true;
1544 break;
1545 default:
1546 metered = false;
1547 }
1548 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001549 final long lastWarningSnooze;
1550 if (version >= VERSION_SPLIT_SNOOZE) {
1551 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1552 } else {
1553 lastWarningSnooze = SNOOZE_NEVER;
1554 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001555 final boolean inferred;
1556 if (version >= VERSION_ADDED_INFERRED) {
1557 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1558 } else {
1559 inferred = false;
1560 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561
Jeff Sharkey32566012014-12-02 18:30:14 -08001562 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1563 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001564 if (template.isPersistable()) {
1565 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1566 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1567 lastLimitSnooze, metered, inferred));
1568 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001569
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001570 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001571 final int uid = readIntAttribute(in, ATTR_UID);
1572 final int policy = readIntAttribute(in, ATTR_POLICY);
1573
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001574 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001575 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001576 } else {
1577 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1578 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001579 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001580 final int appId = readIntAttribute(in, ATTR_APP_ID);
1581 final int policy = readIntAttribute(in, ATTR_POLICY);
1582
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001583 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001584 // app policy is deprecated so this is only used in pre system user split.
1585 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001586 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001587 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001588 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001589 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001590 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001591 } else if (TAG_WHITELIST.equals(tag)) {
1592 insideWhitelist = true;
1593 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1594 final int uid = readIntAttribute(in, ATTR_UID);
1595 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001596 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1597 final int uid = readIntAttribute(in, ATTR_UID);
1598 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001600 } else if (type == END_TAG) {
1601 if (TAG_WHITELIST.equals(tag)) {
1602 insideWhitelist = false;
1603 }
1604
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 }
1606 }
1607
1608 } catch (FileNotFoundException e) {
1609 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001610 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001612 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001614 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001615 } finally {
1616 IoUtils.closeQuietly(fis);
1617 }
1618 }
1619
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001620 /**
1621 * Upgrade legacy background data flags, notifying listeners of one last
1622 * change to always-true.
1623 */
Felipe Lemef0823852016-06-08 13:43:08 -07001624 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001625 mRestrictBackground = Settings.Secure.getInt(
1626 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1627
1628 // kick off one last broadcast if restricted
1629 if (mRestrictBackground) {
1630 final Intent broadcast = new Intent(
1631 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001632 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001633 }
1634 }
1635
Felipe Lemef0823852016-06-08 13:43:08 -07001636 void writePolicyAL() {
1637 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001638
1639 FileOutputStream fos = null;
1640 try {
1641 fos = mPolicyFile.startWrite();
1642
1643 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001644 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001645 out.startDocument(null, true);
1646
1647 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001648 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001649 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001650
1651 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001652 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1653 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001654 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001655 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001656
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001657 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001658 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1659 final String subscriberId = template.getSubscriberId();
1660 if (subscriberId != null) {
1661 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001663 final String networkId = template.getNetworkId();
1664 if (networkId != null) {
1665 out.attribute(null, ATTR_NETWORK_ID, networkId);
1666 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001668 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1670 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001671 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1672 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001673 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001674 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001675 out.endTag(null, TAG_NETWORK_POLICY);
1676 }
1677
1678 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001679 for (int i = 0; i < mUidPolicy.size(); i++) {
1680 final int uid = mUidPolicy.keyAt(i);
1681 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001682
Jeff Sharkey497e4432011-06-14 17:27:29 -07001683 // skip writing empty policies
1684 if (policy == POLICY_NONE) continue;
1685
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001686 out.startTag(null, TAG_UID_POLICY);
1687 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001688 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001689 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001690 }
1691
1692 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001693
1694 // write all whitelists
1695 out.startTag(null, TAG_WHITELIST);
1696
1697 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001698 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001699 for (int i = 0; i < size; i++) {
1700 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1701 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1702 writeIntAttribute(out, ATTR_UID, uid);
1703 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1704 }
1705
Felipe Lemea9505cc2016-02-26 10:28:41 -08001706 // revoked restrict background whitelist
1707 size = mRestrictBackgroundWhitelistRevokedUids.size();
1708 for (int i = 0; i < size; i++) {
1709 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1710 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1711 writeIntAttribute(out, ATTR_UID, uid);
1712 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1713 }
1714
Felipe Lemeb85a6372016-01-14 16:16:16 -08001715 out.endTag(null, TAG_WHITELIST);
1716
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001717 out.endDocument();
1718
1719 mPolicyFile.finishWrite(fos);
1720 } catch (IOException e) {
1721 if (fos != null) {
1722 mPolicyFile.failWrite(fos);
1723 }
1724 }
1725 }
1726
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001727 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001728 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001729 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001730
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001731 if (!UserHandle.isApp(uid)) {
1732 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001733 }
Felipe Lemef0823852016-06-08 13:43:08 -07001734 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001735 final long token = Binder.clearCallingIdentity();
1736 try {
1737 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1738 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001739 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001740 }
1741 } finally {
1742 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001743 }
1744 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001745 }
1746
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001747 @Override
1748 public void addUidPolicy(int uid, int policy) {
1749 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001750
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001751 if (!UserHandle.isApp(uid)) {
1752 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1753 }
1754
Felipe Lemef0823852016-06-08 13:43:08 -07001755 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001756 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1757 policy |= oldPolicy;
1758 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001759 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001760 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001761 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001762 }
1763
1764 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001765 public void removeUidPolicy(int uid, int policy) {
1766 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1767
1768 if (!UserHandle.isApp(uid)) {
1769 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1770 }
1771
Felipe Lemef0823852016-06-08 13:43:08 -07001772 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001773 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1774 policy = oldPolicy & ~policy;
1775 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001776 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001777 }
1778 }
1779 }
1780
Felipe Lemef0823852016-06-08 13:43:08 -07001781 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1782 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001783
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001784 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1785 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1786 isBlacklisted ? 1 : 0).sendToTarget();
1787
1788 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001789 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001790 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1791 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001792 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001793 .sendToTarget();
1794 }
1795 }
1796
Felipe Lemef0823852016-06-08 13:43:08 -07001797 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001798 mUidPolicy.put(uid, policy);
1799
1800 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001801 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001802 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001803 synchronized (mNetworkPoliciesSecondLock) {
1804 writePolicyAL();
1805 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001806 }
1807 }
1808
1809 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001810 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1812
Felipe Lemef0823852016-06-08 13:43:08 -07001813 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001814 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001815 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001816 }
1817
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001818 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001819 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001820 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1821
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001822 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001823 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001824 for (int i = 0; i < mUidPolicy.size(); i++) {
1825 final int uid = mUidPolicy.keyAt(i);
1826 final int uidPolicy = mUidPolicy.valueAt(i);
1827 if (uidPolicy == policy) {
1828 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001829 }
1830 }
1831 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001832 return uids;
1833 }
1834
1835 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001836 * Removes any persistable state associated with given {@link UserHandle}, persisting
1837 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001838 */
Felipe Lemef0823852016-06-08 13:43:08 -07001839 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001840
Felipe Lemef0823852016-06-08 13:43:08 -07001841 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001842 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001843
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001844 // Remove entries from restricted background UID whitelist
1845 int[] wlUids = new int[0];
1846 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1847 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1848 if (UserHandle.getUserId(uid) == userId) {
1849 wlUids = appendInt(wlUids, uid);
1850 }
1851 }
1852
1853 if (wlUids.length > 0) {
1854 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001855 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001856 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001857 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001858 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001859
1860 // Remove entries from revoked default restricted background UID whitelist
1861 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1862 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1863 if (UserHandle.getUserId(uid) == userId) {
1864 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001865 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001866 }
1867 }
1868
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001869 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001870 int[] uids = new int[0];
1871 for (int i = 0; i < mUidPolicy.size(); i++) {
1872 final int uid = mUidPolicy.keyAt(i);
1873 if (UserHandle.getUserId(uid) == userId) {
1874 uids = appendInt(uids, uid);
1875 }
1876 }
1877
1878 if (uids.length > 0) {
1879 for (int uid : uids) {
1880 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001881 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001882 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001883 }
Felipe Lemef0823852016-06-08 13:43:08 -07001884 synchronized (mNetworkPoliciesSecondLock) {
1885 updateRulesForGlobalChangeAL(true);
1886 if (writePolicy && changed) {
1887 writePolicyAL();
1888 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001889 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001890 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001891 }
1892
1893 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001894 public void setConnectivityListener(INetworkPolicyListener listener) {
1895 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1896 if (mConnectivityListener != null) {
1897 throw new IllegalStateException("Connectivity listener already registered");
1898 }
1899 mConnectivityListener = listener;
1900 }
1901
1902 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001903 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001904 // TODO: create permission for observing network policy
1905 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001906 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001907 }
1908
1909 @Override
1910 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001911 // TODO: create permission for observing network policy
1912 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001913 mListeners.unregister(listener);
1914 }
1915
Jeff Sharkey1b861272011-05-22 00:34:52 -07001916 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001917 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001918 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1919
Felipe Leme6a05eee2016-02-19 14:43:51 -08001920 final long token = Binder.clearCallingIdentity();
1921 try {
1922 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001923 synchronized (mUidRulesFirstLock) {
1924 synchronized (mNetworkPoliciesSecondLock) {
1925 normalizePoliciesNL(policies);
1926 updateNetworkEnabledNL();
1927 updateNetworkRulesNL();
1928 updateNotificationsNL();
1929 writePolicyAL();
1930 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001931 }
1932 } finally {
1933 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001934 }
1935 }
1936
Felipe Lemef0823852016-06-08 13:43:08 -07001937 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001938 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001939 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1940 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001941 }
1942
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001943 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001944 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001945 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001946 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001947 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1948 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1949 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001950 } catch (SecurityException e) {
1951 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001952
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001953 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1954 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1955 return new NetworkPolicy[0];
1956 }
Svet Ganov16a16892015-04-16 10:32:04 -07001957 }
1958
Felipe Lemef0823852016-06-08 13:43:08 -07001959 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001960 final int size = mNetworkPolicy.size();
1961 final NetworkPolicy[] policies = new NetworkPolicy[size];
1962 for (int i = 0; i < size; i++) {
1963 policies[i] = mNetworkPolicy.valueAt(i);
1964 }
1965 return policies;
1966 }
1967 }
1968
Felipe Lemef0823852016-06-08 13:43:08 -07001969 private void normalizePoliciesNL() {
1970 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001971 }
1972
Felipe Lemef0823852016-06-08 13:43:08 -07001973 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001974 final TelephonyManager tele = TelephonyManager.from(mContext);
1975 final String[] merged = tele.getMergedSubscriberIds();
1976
1977 mNetworkPolicy.clear();
1978 for (NetworkPolicy policy : policies) {
1979 // When two normalized templates conflict, prefer the most
1980 // restrictive policy
1981 policy.template = NetworkTemplate.normalize(policy.template, merged);
1982 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1983 if (existing == null || existing.compareTo(policy) > 0) {
1984 if (existing != null) {
1985 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1986 }
1987 mNetworkPolicy.put(policy.template, policy);
1988 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001989 }
1990 }
1991
1992 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001993 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001994 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001995
1996 final long token = Binder.clearCallingIdentity();
1997 try {
1998 performSnooze(template, TYPE_LIMIT);
1999 } finally {
2000 Binder.restoreCallingIdentity(token);
2001 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002002 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002003
Dianne Hackborn497175b2014-07-01 12:56:08 -07002004 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002005 maybeRefreshTrustedTime();
2006 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002007 synchronized (mUidRulesFirstLock) {
2008 synchronized (mNetworkPoliciesSecondLock) {
2009 // find and snooze local policy that matches
2010 final NetworkPolicy policy = mNetworkPolicy.get(template);
2011 if (policy == null) {
2012 throw new IllegalArgumentException("unable to find policy for " + template);
2013 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002014
Felipe Lemef0823852016-06-08 13:43:08 -07002015 switch (type) {
2016 case TYPE_WARNING:
2017 policy.lastWarningSnooze = currentTime;
2018 break;
2019 case TYPE_LIMIT:
2020 policy.lastLimitSnooze = currentTime;
2021 break;
2022 default:
2023 throw new IllegalArgumentException("unexpected type");
2024 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002025
Felipe Lemef0823852016-06-08 13:43:08 -07002026 normalizePoliciesNL();
2027 updateNetworkEnabledNL();
2028 updateNetworkRulesNL();
2029 updateNotificationsNL();
2030 writePolicyAL();
2031 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002032 }
2033 }
2034
2035 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002036 public void onTetheringChanged(String iface, boolean tethering) {
2037 // No need to enforce permission because setRestrictBackground() will do it.
2038 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002039 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002040 if (mRestrictBackground && tethering) {
2041 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2042 setRestrictBackground(false);
2043 }
2044 }
2045 }
2046
2047 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002048 public void setRestrictBackground(boolean restrictBackground) {
2049 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002050 final long token = Binder.clearCallingIdentity();
2051 try {
2052 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002053 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002054 if (restrictBackground == mRestrictBackground) {
2055 // Ideally, UI should never allow this scenario...
2056 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2057 return;
2058 }
Felipe Lemef0823852016-06-08 13:43:08 -07002059 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002060 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002061
Felipe Leme6a05eee2016-02-19 14:43:51 -08002062 } finally {
2063 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002064 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002065
2066 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2067 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002068 }
2069
Felipe Lemef0823852016-06-08 13:43:08 -07002070 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002071 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002072 final boolean oldRestrictBackground = mRestrictBackground;
2073 mRestrictBackground = restrictBackground;
2074 // Must whitelist foreground apps before turning data saver mode on.
2075 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2076 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002077 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002078 try {
2079 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2080 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2081 mRestrictBackground = oldRestrictBackground;
2082 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002083 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002084 return;
2085 }
2086 } catch (RemoteException e) {
2087 // ignored; service lives in system_server
2088 }
Felipe Lemef0823852016-06-08 13:43:08 -07002089 synchronized (mNetworkPoliciesSecondLock) {
2090 updateNotificationsNL();
2091 writePolicyAL();
2092 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002093 }
2094
Jeff Sharkey46645002011-07-27 21:11:21 -07002095 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002096 public void addRestrictBackgroundWhitelistedUid(int uid) {
2097 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002098 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002099 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002100 int changed;
2101 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002102 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002103 if (oldStatus) {
2104 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2105 return;
2106 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002107 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002108 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002109 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002110 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2111 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2112 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2113 + " from revoked restrict background whitelist");
2114 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2115 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002116 if (needFirewallRules) {
2117 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002118 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002119 }
2120 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002121 synchronized (mNetworkPoliciesSecondLock) {
2122 writePolicyAL();
2123 }
2124 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002125 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002126 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2127 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002128 }
2129
2130 @Override
2131 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2132 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002133 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002134 synchronized (mUidRulesFirstLock) {
2135 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002136 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002137 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2138 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002139 }
2140
Felipe Leme70c57c22016-03-29 10:45:13 -07002141 /**
2142 * Removes a uid from the restricted background whitelist, returning whether its current
2143 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2144 */
Felipe Lemef0823852016-06-08 13:43:08 -07002145 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002146 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002147 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002148 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002149 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2150 return false;
2151 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002152 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002153 if (oldStatus) {
2154 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2155 mRestrictBackgroundWhitelistUids.delete(uid);
2156 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002157 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2158 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2159 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2160 + " to revoked restrict background whitelist");
2161 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2162 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002163 if (needFirewallRules) {
2164 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002165 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002166 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002167 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002168 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002169 synchronized (mNetworkPoliciesSecondLock) {
2170 writePolicyAL();
2171 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002172 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002173 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2174 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002175 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002176 }
2177
2178 @Override
2179 public int[] getRestrictBackgroundWhitelistedUids() {
2180 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002181 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002182 final int size = mRestrictBackgroundWhitelistUids.size();
2183 final int[] whitelist = new int[size];
2184 for (int i = 0; i < size; i++) {
2185 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2186 }
2187 if (LOGV) {
2188 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2189 + mRestrictBackgroundWhitelistUids);
2190 }
2191 return whitelist;
2192 }
2193 }
2194
2195 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002196 public int getRestrictBackgroundByCaller() {
2197 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2198 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002199
Felipe Lemef0823852016-06-08 13:43:08 -07002200 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002201 // Must clear identity because getUidPolicy() is restricted to system.
2202 final long token = Binder.clearCallingIdentity();
2203 final int policy;
2204 try {
2205 policy = getUidPolicy(uid);
2206 } finally {
2207 Binder.restoreCallingIdentity(token);
2208 }
2209 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2210 // App is blacklisted.
2211 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2212 }
Felipe Leme1b103232016-01-22 09:44:57 -08002213 if (!mRestrictBackground) {
2214 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2215 }
2216 return mRestrictBackgroundWhitelistUids.get(uid)
2217 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2218 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2219 }
2220 }
2221
2222 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002223 public boolean getRestrictBackground() {
2224 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2225
Felipe Lemef0823852016-06-08 13:43:08 -07002226 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002227 return mRestrictBackground;
2228 }
2229 }
2230
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002231 @Override
2232 public void setDeviceIdleMode(boolean enabled) {
2233 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2234
Felipe Lemef0823852016-06-08 13:43:08 -07002235 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002236 if (mDeviceIdleMode != enabled) {
2237 mDeviceIdleMode = enabled;
2238 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002239 // Device idle change means we need to rebuild rules for all
2240 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002241 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002242 }
2243 if (enabled) {
2244 EventLogTags.writeDeviceIdleOnPhase("net");
2245 } else {
2246 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002247 }
2248 }
2249 }
2250 }
2251
Felipe Lemef0823852016-06-08 13:43:08 -07002252 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002253 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2254 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002255 if (policy.template.matches(ident)) {
2256 return policy;
2257 }
2258 }
2259 return null;
2260 }
2261
2262 @Override
2263 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2264 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2265
2266 // only returns usage summary, so we don't require caller to have
2267 // READ_NETWORK_USAGE_HISTORY.
2268 final long token = Binder.clearCallingIdentity();
2269 try {
2270 return getNetworkQuotaInfoUnchecked(state);
2271 } finally {
2272 Binder.restoreCallingIdentity(token);
2273 }
2274 }
2275
2276 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2277 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2278
2279 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002280 synchronized (mNetworkPoliciesSecondLock) {
2281 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002282 }
2283
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002284 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002285 // missing policy means we can't derive useful quota info
2286 return null;
2287 }
2288
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002289 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002290
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002291 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002292 final long start = computeLastCycleBoundary(currentTime, policy);
2293 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002294 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002295
2296 // report soft and hard limits under policy
2297 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2298 : NetworkQuotaInfo.NO_LIMIT;
2299 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2300 : NetworkQuotaInfo.NO_LIMIT;
2301
2302 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2303 }
2304
Jeff Sharkey46645002011-07-27 21:11:21 -07002305 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002306 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002307 if (state.networkInfo == null) {
2308 return false;
2309 }
2310
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002311 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2312
2313 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002314 synchronized (mNetworkPoliciesSecondLock) {
2315 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002316 }
2317
2318 if (policy != null) {
2319 return policy.metered;
2320 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002321 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002322 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002323 return true;
2324 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002325 return false;
2326 }
2327 }
2328
2329 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002330 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002331 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002332
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002333 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2334
Dianne Hackborn497175b2014-07-01 12:56:08 -07002335 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002336 for (String arg : args) {
2337 argSet.add(arg);
2338 }
2339
Felipe Lemef0823852016-06-08 13:43:08 -07002340 synchronized (mUidRulesFirstLock) {
2341 synchronized (mNetworkPoliciesSecondLock) {
2342 if (argSet.contains("--unsnooze")) {
2343 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2344 mNetworkPolicy.valueAt(i).clearSnooze();
2345 }
2346
2347 normalizePoliciesNL();
2348 updateNetworkEnabledNL();
2349 updateNetworkRulesNL();
2350 updateNotificationsNL();
2351 writePolicyAL();
2352
2353 fout.println("Cleared snooze timestamps");
2354 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002355 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002356
Felipe Lemef0823852016-06-08 13:43:08 -07002357 fout.print("System ready: "); fout.println(mSystemReady);
2358 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2359 fout.print("Restrict power: "); fout.println(mRestrictPower);
2360 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2361 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002362 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002363 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2364 fout.println(mNetworkPolicy.valueAt(i).toString());
2365 }
2366 fout.decreaseIndent();
2367
2368 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2369
2370 fout.println("Policy for UIDs:");
2371 fout.increaseIndent();
2372 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002373 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002374 final int uid = mUidPolicy.keyAt(i);
2375 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002376 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002377 fout.print(uid);
2378 fout.print(" policy=");
2379 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2380 fout.println();
2381 }
2382 fout.decreaseIndent();
2383
2384 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2385 if (size > 0) {
2386 fout.println("Power save whitelist (except idle) app ids:");
2387 fout.increaseIndent();
2388 for (int i = 0; i < size; i++) {
2389 fout.print("UID=");
2390 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2391 fout.print(": ");
2392 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2393 fout.println();
2394 }
2395 fout.decreaseIndent();
2396 }
2397
2398 size = mPowerSaveWhitelistAppIds.size();
2399 if (size > 0) {
2400 fout.println("Power save whitelist app ids:");
2401 fout.increaseIndent();
2402 for (int i = 0; i < size; i++) {
2403 fout.print("UID=");
2404 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2405 fout.print(": ");
2406 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2407 fout.println();
2408 }
2409 fout.decreaseIndent();
2410 }
2411
2412 size = mRestrictBackgroundWhitelistUids.size();
2413 if (size > 0) {
2414 fout.println("Restrict background whitelist uids:");
2415 fout.increaseIndent();
2416 for (int i = 0; i < size; i++) {
2417 fout.print("UID=");
2418 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2419 fout.println();
2420 }
2421 fout.decreaseIndent();
2422 }
2423
2424 size = mDefaultRestrictBackgroundWhitelistUids.size();
2425 if (size > 0) {
2426 fout.println("Default restrict background whitelist uids:");
2427 fout.increaseIndent();
2428 for (int i = 0; i < size; i++) {
2429 fout.print("UID=");
2430 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2431 fout.println();
2432 }
2433 fout.decreaseIndent();
2434 }
2435
2436 size = mRestrictBackgroundWhitelistRevokedUids.size();
2437 if (size > 0) {
2438 fout.println("Default restrict background whitelist uids revoked by users:");
2439 fout.increaseIndent();
2440 for (int i = 0; i < size; i++) {
2441 fout.print("UID=");
2442 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2443 fout.println();
2444 }
2445 fout.decreaseIndent();
2446 }
2447
2448 final SparseBooleanArray knownUids = new SparseBooleanArray();
2449 collectKeys(mUidState, knownUids);
2450 collectKeys(mUidRules, knownUids);
2451
2452 fout.println("Status for all known UIDs:");
2453 fout.increaseIndent();
2454 size = knownUids.size();
2455 for (int i = 0; i < size; i++) {
2456 final int uid = knownUids.keyAt(i);
2457 fout.print("UID=");
2458 fout.print(uid);
2459
2460 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2461 fout.print(" state=");
2462 fout.print(state);
2463 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2464 fout.print(" (fg)");
2465 } else {
2466 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2467 ? " (fg svc)" : " (bg)");
2468 }
2469
2470 final int uidRules = mUidRules.get(uid, RULE_NONE);
2471 fout.print(" rules=");
2472 fout.print(uidRulesToString(uidRules));
2473 fout.println();
2474 }
2475 fout.decreaseIndent();
2476
2477 fout.println("Status for just UIDs with rules:");
2478 fout.increaseIndent();
2479 size = mUidRules.size();
2480 for (int i = 0; i < size; i++) {
2481 final int uid = mUidRules.keyAt(i);
2482 fout.print("UID=");
2483 fout.print(uid);
2484 final int uidRules = mUidRules.get(uid, RULE_NONE);
2485 fout.print(" rules=");
2486 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002487 fout.println();
2488 }
2489 fout.decreaseIndent();
2490 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002491 }
2492 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002493
2494 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002495 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2496 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002497 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002498 this, in, out, err, args, resultReceiver);
2499 }
2500
2501 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002502 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002503 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2504
Felipe Lemef0823852016-06-08 13:43:08 -07002505 synchronized (mUidRulesFirstLock) {
2506 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002507 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002508 }
2509
Felipe Lemef0823852016-06-08 13:43:08 -07002510 private boolean isUidForegroundUL(int uid) {
2511 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002512 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2513 }
2514
Felipe Lemef0823852016-06-08 13:43:08 -07002515 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002516 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002517 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002518 }
2519
Felipe Lemef0823852016-06-08 13:43:08 -07002520 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002521 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2522 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2523 }
2524
Felipe Lemef0823852016-06-08 13:43:08 -07002525 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002526 // only really in foreground when screen is also on
Felipe Lemef28983d2016-03-25 12:18:23 -07002527 return mScreenOn && state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002528 }
2529
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002530 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002531 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002532 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2533 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002534 */
Felipe Lemef0823852016-06-08 13:43:08 -07002535 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002536 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2537 if (oldUidState != uidState) {
2538 // state changed, push updated rules
2539 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002540 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002541 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2542 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002543 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002544 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002545 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002546 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002547 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002548 }
2549 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002550 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002551 }
Felipe Lemef0823852016-06-08 13:43:08 -07002552 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002553 }
Felipe Lemef0823852016-06-08 13:43:08 -07002554 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002555 }
2556 }
2557
Felipe Lemef0823852016-06-08 13:43:08 -07002558 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002559 final int index = mUidState.indexOfKey(uid);
2560 if (index >= 0) {
2561 final int oldUidState = mUidState.valueAt(index);
2562 mUidState.removeAt(index);
2563 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002564 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002565 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002566 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002567 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002568 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002569 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002570 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002571 }
Felipe Lemef0823852016-06-08 13:43:08 -07002572 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002573 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002574 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002575 }
2576 }
2577
Felipe Lemef28983d2016-03-25 12:18:23 -07002578 // adjust stats accounting based on foreground status
2579 private void updateNetworkStats(int uid, boolean uidForeground) {
2580 try {
2581 mNetworkStats.setUidForeground(uid, uidForeground);
2582 } catch (RemoteException e) {
2583 // ignored; service lives in system_server
2584 }
2585 }
2586
Felipe Lemef0823852016-06-08 13:43:08 -07002587 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002588 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002589 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002590 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002591 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002592 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002593 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002594 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002595 }
2596 }
2597
Jeff Sharkeya4620792011-05-20 15:29:23 -07002598 private void updateScreenOn() {
Felipe Lemef0823852016-06-08 13:43:08 -07002599 synchronized (mUidRulesFirstLock) {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002600 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07002601 mScreenOn = mPowerManager.isInteractive();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002602 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002603 // ignored; service lives in system_server
Jeff Sharkeya4620792011-05-20 15:29:23 -07002604 }
Felipe Lemef0823852016-06-08 13:43:08 -07002605 updateRulesForScreenUL();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002606 }
2607 }
2608
2609 /**
2610 * Update rules that might be changed by {@link #mScreenOn} value.
2611 */
Felipe Lemef0823852016-06-08 13:43:08 -07002612 private void updateRulesForScreenUL() {
Jeff Sharkeya4620792011-05-20 15:29:23 -07002613 // only update rules for anyone with foreground activities
Dianne Hackborn497175b2014-07-01 12:56:08 -07002614 final int size = mUidState.size();
Jeff Sharkeya4620792011-05-20 15:29:23 -07002615 for (int i = 0; i < size; i++) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002616 if (mUidState.valueAt(i) <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002617 final int uid = mUidState.keyAt(i);
Felipe Lemef0823852016-06-08 13:43:08 -07002618 updateRestrictionRulesForUidUL(uid);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002619 }
2620 }
2621 }
2622
Felipe Leme011b98f2016-02-10 17:28:31 -08002623 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002624 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2625 }
2626
Felipe Lemef0823852016-06-08 13:43:08 -07002627 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002628 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2629 }
2630
Felipe Lemef0823852016-06-08 13:43:08 -07002631 void updateRulesForPowerSaveUL() {
2632 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002633 mUidFirewallPowerSaveRules);
2634 }
2635
Felipe Lemef0823852016-06-08 13:43:08 -07002636 void updateRuleForRestrictPowerUL(int uid) {
2637 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002638 }
2639
Felipe Lemef0823852016-06-08 13:43:08 -07002640 void updateRulesForDeviceIdleUL() {
2641 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002642 mUidFirewallDozableRules);
2643 }
2644
Felipe Lemef0823852016-06-08 13:43:08 -07002645 void updateRuleForDeviceIdleUL(int uid) {
2646 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002647 }
2648
Felipe Lemef28983d2016-03-25 12:18:23 -07002649 // NOTE: since both fw_dozable and fw_powersave uses the same map
2650 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002651 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002652 SparseIntArray rules) {
2653 if (enabled) {
2654 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002655 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002656 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002657 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002658 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002659 for (int ui = users.size() - 1; ui >= 0; ui--) {
2660 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002661 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002662 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2663 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2664 int uid = UserHandle.getUid(user.id, appId);
2665 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2666 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002667 }
2668 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2669 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2670 int uid = UserHandle.getUid(user.id, appId);
2671 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2672 }
2673 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002674 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002675 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002676 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2677 }
2678 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002679 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002680 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002681
Felipe Lemef0823852016-06-08 13:43:08 -07002682 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002683 }
2684
Felipe Lemef0823852016-06-08 13:43:08 -07002685 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002686 final int appId = UserHandle.getAppId(uid);
2687 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2688 }
2689
Felipe Lemef28983d2016-03-25 12:18:23 -07002690 // NOTE: since both fw_dozable and fw_powersave uses the same map
2691 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002692 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002693 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002694 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002695 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2696 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002697 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002698 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002699 }
2700 }
2701 }
2702
Felipe Lemef0823852016-06-08 13:43:08 -07002703 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002704 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2705 uidRules.clear();
2706
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002707 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002708 final List<UserInfo> users = mUserManager.getUsers();
2709 for (int ui = users.size() - 1; ui >= 0; ui--) {
2710 UserInfo user = users.get(ui);
2711 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2712 for (int uid : idleUids) {
2713 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002714 // quick check: if this uid doesn't have INTERNET permission, it
2715 // doesn't have network access anyway, so it is a waste to mess
2716 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002717 if (hasInternetPermissions(uid)) {
2718 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002719 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002720 }
2721 }
2722 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002723
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002724 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2725 }
2726
Felipe Lemef0823852016-06-08 13:43:08 -07002727 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002728 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002729
2730 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002731 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002732 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002733 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2734 } else {
2735 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2736 }
2737 }
2738
Felipe Lemef0823852016-06-08 13:43:08 -07002739 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002740 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002741 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002742 }
2743
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002744 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002745 * Update rules that might be changed by {@link #mRestrictBackground},
2746 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002747 */
Felipe Lemef0823852016-06-08 13:43:08 -07002748 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002749 long start;
2750 if (LOGD) start = System.currentTimeMillis();
2751
Felipe Lemef0823852016-06-08 13:43:08 -07002752 updateRulesForRestrictPowerUL();
2753 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002754
2755 // If the set of restricted networks may have changed, re-evaluate those.
2756 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002757 normalizePoliciesNL();
2758 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002759 }
2760 if (LOGD) {
2761 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002762 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002763 + delta + "ms");
2764 }
2765 }
2766
Felipe Lemef0823852016-06-08 13:43:08 -07002767 private void updateRulesForRestrictPowerUL() {
2768 updateRulesForDeviceIdleUL();
2769 updateRulesForAppIdleUL();
2770 updateRulesForPowerSaveUL();
2771 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002772 }
2773
Felipe Lemef0823852016-06-08 13:43:08 -07002774 private void updateRulesForRestrictBackgroundUL() {
2775 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002776 }
2777
2778 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2779 private static final int TYPE_RESTRICT_POWER = 2;
2780 @Retention(RetentionPolicy.SOURCE)
2781 @IntDef(flag = false, value = {
2782 TYPE_RESTRICT_BACKGROUND,
2783 TYPE_RESTRICT_POWER,
2784 })
2785 public @interface RestrictType {
2786 }
2787
2788 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002789 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002790 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002791
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002792 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002793 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002794 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002795 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2796 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2797 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002798
Felipe Leme03e689d2016-03-02 16:17:38 -08002799 final int usersSize = users.size();
2800 final int appsSize = apps.size();
2801 for (int i = 0; i < usersSize; i++) {
2802 final UserInfo user = users.get(i);
2803 for (int j = 0; j < appsSize; j++) {
2804 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002805 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002806 switch (type) {
2807 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002808 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002809 break;
2810 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002811 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002812 break;
2813 default:
2814 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2815 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002816 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002817 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002818 }
2819
Felipe Lemef0823852016-06-08 13:43:08 -07002820 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002821 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002822 for (int i = 0; i < users.size(); i++) {
2823 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002824 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002825 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002826 int uid = UserHandle.getUid(user.id, appId);
Felipe Lemef0823852016-06-08 13:43:08 -07002827 updateRulesForRestrictPowerUL();
Felipe Leme781ba142016-05-09 16:24:48 -07002828 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002829 updateRuleForAppIdleUL(uid);
2830 updateRuleForDeviceIdleUL(uid);
2831 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002832 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002833 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002834 }
2835 }
2836 }
2837
Felipe Leme70c57c22016-03-29 10:45:13 -07002838 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2839 // methods below could be merged into a isUidValidForRules() method.
2840 private boolean isUidValidForBlacklistRules(int uid) {
2841 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002842 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002843 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002844 return true;
2845 }
2846
2847 return false;
2848 }
2849
Felipe Leme70c57c22016-03-29 10:45:13 -07002850 private boolean isUidValidForWhitelistRules(int uid) {
2851 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2852 }
2853
Amith Yamasani15e472352015-04-24 19:06:07 -07002854 private boolean isUidIdle(int uid) {
2855 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2856 final int userId = UserHandle.getUserId(uid);
2857
songjinshi0655edd2016-05-18 19:55:32 +08002858 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002859 for (String packageName : packages) {
2860 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2861 return false;
2862 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002863 }
2864 }
2865 return true;
2866 }
2867
2868 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002869 * Checks if an uid has INTERNET permissions.
2870 * <p>
2871 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002872 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002873 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002874 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002875 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002876 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002877 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002878 }
2879 } catch (RemoteException e) {
2880 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002881 return true;
2882 }
2883
2884 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002885 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002886 *
Felipe Leme781ba142016-05-09 16:24:48 -07002887 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002888 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002889 * <li>Doze mode
2890 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002891 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002892 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002893 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002894 *
2895 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002896 */
Felipe Lemef0823852016-06-08 13:43:08 -07002897 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002898 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002899 updateRuleForDeviceIdleUL(uid);
2900 updateRuleForAppIdleUL(uid);
2901 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002902
2903 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002904 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002905
2906 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002907 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002908 }
2909
Felipe Leme70c57c22016-03-29 10:45:13 -07002910 /**
2911 * Applies network rules to bandwidth controllers based on process state and user-defined
2912 * restrictions (blacklist / whitelist).
2913 *
2914 * <p>
2915 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2916 * networks:
2917 * <ul>
2918 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2919 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2920 * also blacklisted.
2921 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2922 * no UIDs other those whitelisted will have access.
2923 * <ul>
2924 *
2925 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2926 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2927 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2928 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002929 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002930 * {@link INetworkManagementService}, but this method should also be called in events (like
2931 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2932 * following rules should also be applied:
2933 *
2934 * <ul>
2935 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2936 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2937 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2938 * {@code bw_penalty_box}.
2939 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2940 * </ul>
2941 *
2942 * <p>For optimization, the rules are only applied on user apps that have internet access
2943 * permission, since there is no need to change the {@code iptables} rule if the app does not
2944 * have permission to use the internet.
2945 *
2946 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002947 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002948 */
Felipe Lemef0823852016-06-08 13:43:08 -07002949 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2950 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002951 }
2952
2953 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002954 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002955 * app is removed - it ignores the UID validity check.
2956 */
Felipe Lemef0823852016-06-08 13:43:08 -07002957 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002958 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2959 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2960 return;
2961 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002962
Dianne Hackborn497175b2014-07-01 12:56:08 -07002963 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002964 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002965 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002966
Felipe Leme781ba142016-05-09 16:24:48 -07002967 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2968 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2969 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2970 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002971
Felipe Leme70c57c22016-03-29 10:45:13 -07002972 // First step: define the new rule based on user restrictions and foreground state.
2973 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002974 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2975 newRule = RULE_TEMPORARY_ALLOW_METERED;
2976 } else if (isWhitelisted) {
2977 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002978 }
2979 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002980 if (isBlacklisted) {
2981 newRule = RULE_REJECT_METERED;
2982 } else if (mRestrictBackground && isWhitelisted) {
2983 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002984 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002985 }
Felipe Leme781ba142016-05-09 16:24:48 -07002986 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002987
Felipe Lemef28983d2016-03-25 12:18:23 -07002988 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002989 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002990 + ": isForeground=" +isForeground
2991 + ", isBlacklisted=" + isBlacklisted
2992 + ", isWhitelisted=" + isWhitelisted
2993 + ", oldRule=" + uidRulesToString(oldRule)
2994 + ", newRule=" + uidRulesToString(newRule)
2995 + ", newUidRules=" + uidRulesToString(newUidRules)
2996 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002997 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002998
Felipe Leme46c4fc32016-05-04 09:21:43 -07002999 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003000 mUidRules.delete(uid);
3001 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003002 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003003 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003004
Felipe Lemed31a97f2016-05-06 14:53:50 -07003005 boolean changed = false;
3006
Felipe Leme70c57c22016-03-29 10:45:13 -07003007 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003008 if (newRule != oldRule) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003009 changed = true;
3010
Felipe Leme781ba142016-05-09 16:24:48 -07003011 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003012 // Temporarily whitelist foreground app, removing from blacklist if necessary
3013 // (since bw_penalty_box prevails over bw_happy_box).
3014
3015 setMeteredNetworkWhitelist(uid, true);
3016 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3017 // but ideally it should be just:
3018 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003019 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003020 setMeteredNetworkBlacklist(uid, false);
3021 }
Felipe Leme781ba142016-05-09 16:24:48 -07003022 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003023 // Remove temporary whitelist from app that is not on foreground anymore.
3024
3025 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3026 // but ideally they should be just:
3027 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3028 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003029 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003030 setMeteredNetworkWhitelist(uid, false);
3031 }
Felipe Leme781ba142016-05-09 16:24:48 -07003032 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003033 setMeteredNetworkBlacklist(uid, true);
3034 }
Felipe Leme781ba142016-05-09 16:24:48 -07003035 } else if ((newRule & RULE_REJECT_METERED) != 0
3036 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003037 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003038 setMeteredNetworkBlacklist(uid, isBlacklisted);
3039 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003040 // Since blacklist prevails over whitelist, we need to handle the special case
3041 // where app is whitelisted and blacklisted at the same time (although such
3042 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003043 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003044 }
Felipe Leme781ba142016-05-09 16:24:48 -07003045 } else if ((newRule & RULE_ALLOW_METERED) != 0
3046 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003047 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003048 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003049 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003050 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003051 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3052 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003053 + ", whitelisted=" + isWhitelisted
3054 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003055 + ", newRule=" + uidRulesToString(newUidRules)
3056 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003057 }
Felipe Leme781ba142016-05-09 16:24:48 -07003058
3059 // Dispatch changed rule to existing listeners.
3060 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3061 }
3062 }
3063
3064 /**
3065 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3066 * listeners in case of change.
3067 * <p>
3068 * There are 3 power-related rules that affects whether an app has background access on
3069 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3070 * restriction, it's added to the equivalent firewall chain:
3071 * <ul>
3072 * <li>App is idle: {@code fw_standby} firewall chain.
3073 * <li>Device is idle: {@code fw_dozable} firewall chain.
3074 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3075 * </ul>
3076 * <p>
3077 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3078 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3079 * <p>
3080 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3081 */
Felipe Lemef0823852016-06-08 13:43:08 -07003082 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003083 if (!isUidValidForBlacklistRules(uid)) {
3084 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3085 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003086 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003087
Felipe Leme781ba142016-05-09 16:24:48 -07003088 final boolean isIdle = isUidIdle(uid);
3089 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
3090 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
3091 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003092 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003093
Felipe Lemef0823852016-06-08 13:43:08 -07003094 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003095 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3096 int newRule = RULE_NONE;
3097
3098 // First step: define the new rule based on user restrictions and foreground state.
3099
3100 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3101 // by considering the foreground and non-foreground states.
3102 if (isForeground) {
3103 if (restrictMode) {
3104 newRule = RULE_ALLOW_ALL;
3105 }
3106 } else if (restrictMode) {
3107 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3108 }
3109
3110 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3111
3112 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003113 Log.v(TAG, "updateRulesForNonMeteredNetworksUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003114 + ", isIdle: " + isIdle
3115 + ", mRestrictPower: " + mRestrictPower
3116 + ", mDeviceIdleMode: " + mDeviceIdleMode
3117 + ", isForeground=" + isForeground
3118 + ", isWhitelisted=" + isWhitelisted
3119 + ", oldRule=" + uidRulesToString(oldRule)
3120 + ", newRule=" + uidRulesToString(newRule)
3121 + ", newUidRules=" + uidRulesToString(newUidRules)
3122 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3123 }
3124
3125 if (newUidRules == RULE_NONE) {
3126 mUidRules.delete(uid);
3127 } else {
3128 mUidRules.put(uid, newUidRules);
3129 }
3130
3131 // Second step: notify listeners if state changed.
3132 if (newRule != oldRule) {
3133 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003134 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003135 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003136 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3137 } else {
3138 // All scenarios should have been covered above
3139 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3140 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003141 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003142 + ", newRule=" + uidRulesToString(newUidRules)
3143 + ", oldRule=" + uidRulesToString(oldUidRules));
3144 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003145 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003146 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003147 }
3148
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003149 private class AppIdleStateChangeListener
3150 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3151
3152 @Override
3153 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3154 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003155 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3156 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003157 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003158 synchronized (mUidRulesFirstLock) {
3159 updateRuleForAppIdleUL(uid);
3160 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003161 }
3162 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003163 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003164 }
3165
3166 @Override
3167 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003168 synchronized (mUidRulesFirstLock) {
3169 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003170 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003171 }
3172 }
3173
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003174 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3175 if (listener != null) {
3176 try {
3177 listener.onUidRulesChanged(uid, uidRules);
3178 } catch (RemoteException ignored) {
3179 }
3180 }
3181 }
3182
3183 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3184 String[] meteredIfaces) {
3185 if (listener != null) {
3186 try {
3187 listener.onMeteredIfacesChanged(meteredIfaces);
3188 } catch (RemoteException ignored) {
3189 }
3190 }
3191 }
3192
3193 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3194 boolean restrictBackground) {
3195 if (listener != null) {
3196 try {
3197 listener.onRestrictBackgroundChanged(restrictBackground);
3198 } catch (RemoteException ignored) {
3199 }
3200 }
3201 }
3202
3203 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3204 int uid, boolean whitelisted) {
3205 if (listener != null) {
3206 try {
3207 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3208 } catch (RemoteException ignored) {
3209 }
3210 }
3211 }
3212
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003213 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3214 int uid, boolean blacklisted) {
3215 if (listener != null) {
3216 try {
3217 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3218 } catch (RemoteException ignored) {
3219 }
3220 }
3221 }
3222
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003223 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003224 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003225 public boolean handleMessage(Message msg) {
3226 switch (msg.what) {
3227 case MSG_RULES_CHANGED: {
3228 final int uid = msg.arg1;
3229 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003230 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003231 final int length = mListeners.beginBroadcast();
3232 for (int i = 0; i < length; i++) {
3233 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003234 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003235 }
3236 mListeners.finishBroadcast();
3237 return true;
3238 }
3239 case MSG_METERED_IFACES_CHANGED: {
3240 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003241 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003242 final int length = mListeners.beginBroadcast();
3243 for (int i = 0; i < length; i++) {
3244 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003245 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003246 }
3247 mListeners.finishBroadcast();
3248 return true;
3249 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003250 case MSG_LIMIT_REACHED: {
3251 final String iface = (String) msg.obj;
3252
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003253 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003254 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003255 if (mMeteredIfaces.contains(iface)) {
3256 try {
3257 // force stats update to make sure we have
3258 // numbers that caused alert to trigger.
3259 mNetworkStats.forceUpdate();
3260 } catch (RemoteException e) {
3261 // ignored; service lives in system_server
3262 }
3263
Felipe Lemef0823852016-06-08 13:43:08 -07003264 updateNetworkEnabledNL();
3265 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003266 }
3267 }
3268 return true;
3269 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003270 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3271 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003272 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003273 final int length = mListeners.beginBroadcast();
3274 for (int i = 0; i < length; i++) {
3275 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003276 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003277 }
3278 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003279 final Intent intent =
3280 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3281 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3282 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3283 return true;
3284 }
3285 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003286 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3287 // - when an app is whitelisted
3288 // - when an app is blacklisted
3289 //
3290 // Whether the internal listeners (INetworkPolicyListener implementations) or
3291 // app broadcast receivers are notified depend on the following rules:
3292 //
3293 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3294 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3295 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003296 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003297 final boolean changed = msg.arg2 == 1;
3298 final Boolean whitelisted = (Boolean) msg.obj;
3299
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003300 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003301 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003302 final boolean whitelistedBool = whitelisted.booleanValue();
3303 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3304 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003305 final int length = mListeners.beginBroadcast();
3306 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003307 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003308 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3309 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003310 }
3311 mListeners.finishBroadcast();
3312 }
Felipe Leme9778f762016-01-27 14:46:39 -08003313 final PackageManager pm = mContext.getPackageManager();
3314 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003315 if (changed && packages != null) {
3316 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003317 final int userId = UserHandle.getUserId(uid);
3318 for (String packageName : packages) {
3319 final Intent intent = new Intent(
3320 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3321 intent.setPackage(packageName);
3322 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3323 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3324 }
Felipe Leme9778f762016-01-27 14:46:39 -08003325 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003326 return true;
3327 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003328 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3329 final int uid = msg.arg1;
3330 final boolean blacklisted = msg.arg2 == 1;
3331
3332 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3333 blacklisted);
3334 final int length = mListeners.beginBroadcast();
3335 for (int i = 0; i < length; i++) {
3336 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3337 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3338 blacklisted);
3339 }
3340 mListeners.finishBroadcast();
3341 return true;
3342 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003343 case MSG_ADVISE_PERSIST_THRESHOLD: {
3344 final long lowestRule = (Long) msg.obj;
3345 try {
3346 // make sure stats are recorded frequently enough; we aim
3347 // for 2MB threshold for 2GB/month rules.
3348 final long persistThreshold = lowestRule / 1000;
3349 mNetworkStats.advisePersistThreshold(persistThreshold);
3350 } catch (RemoteException e) {
3351 // ignored; service lives in system_server
3352 }
3353 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003354 }
Jeff Sharkey0abe5562012-06-19 13:32:22 -07003355 case MSG_SCREEN_ON_CHANGED: {
3356 updateScreenOn();
3357 return true;
3358 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003359 case MSG_UPDATE_INTERFACE_QUOTA: {
3360 removeInterfaceQuota((String) msg.obj);
3361 // int params need to be stitched back into a long
3362 setInterfaceQuota((String) msg.obj,
3363 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3364 return true;
3365 }
3366 case MSG_REMOVE_INTERFACE_QUOTA: {
3367 removeInterfaceQuota((String) msg.obj);
3368 return true;
3369 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003370 default: {
3371 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003372 }
3373 }
3374 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003375 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003376
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003377 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003378 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003379 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003380 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003381 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003382 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003383 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003384 }
3385 }
3386
3387 private void removeInterfaceQuota(String iface) {
3388 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003389 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003390 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003391 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003392 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003393 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003394 }
3395 }
3396
Felipe Leme70c57c22016-03-29 10:45:13 -07003397 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3398 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003399 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003400 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003401 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003402 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3403 } catch (RemoteException e) {
3404 // ignored; service lives in system_server
3405 }
3406 }
3407
3408 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3409 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3410 try {
3411 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3412 } catch (IllegalStateException e) {
3413 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003414 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003415 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003416 }
3417 }
3418
Amith Yamasani15e472352015-04-24 19:06:07 -07003419 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003420 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3421 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3422 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003423 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003424 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003425 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003426 int size = uidRules.size();
3427 int[] uids = new int[size];
3428 int[] rules = new int[size];
3429 for(int index = size - 1; index >= 0; --index) {
3430 uids[index] = uidRules.keyAt(index);
3431 rules[index] = uidRules.valueAt(index);
3432 }
3433 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003434 } catch (IllegalStateException e) {
3435 Log.wtf(TAG, "problem setting firewall uid rules", e);
3436 } catch (RemoteException e) {
3437 // ignored; service lives in system_server
3438 }
3439 }
3440
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003441 /**
3442 * Add or remove a uid to the firewall blacklist for all network ifaces.
3443 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003444 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003445 if (chain == FIREWALL_CHAIN_DOZABLE) {
3446 mUidFirewallDozableRules.put(uid, rule);
3447 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3448 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003449 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3450 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003451 }
3452
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003453 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003454 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003455 } catch (IllegalStateException e) {
3456 Log.wtf(TAG, "problem setting firewall uid rules", e);
3457 } catch (RemoteException e) {
3458 // ignored; service lives in system_server
3459 }
3460 }
3461
3462 /**
3463 * Add or remove a uid to the firewall blacklist for all network ifaces.
3464 */
Felipe Lemef0823852016-06-08 13:43:08 -07003465 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003466 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3467 mFirewallChainStates.get(chain) == enable) {
3468 // All is the same, nothing to do.
3469 return;
3470 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003471 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003472 try {
3473 mNetworkManager.setFirewallChainEnabled(chain, enable);
3474 } catch (IllegalStateException e) {
3475 Log.wtf(TAG, "problem enable firewall chain", e);
3476 } catch (RemoteException e) {
3477 // ignored; service lives in system_server
3478 }
3479 }
3480
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003481 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3482 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003483 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003484 } catch (RuntimeException e) {
3485 Slog.w(TAG, "problem reading network stats: " + e);
3486 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003487 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003488 // ignored; service lives in system_server
3489 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003490 }
3491 }
3492
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003493 private boolean isBandwidthControlEnabled() {
3494 final long token = Binder.clearCallingIdentity();
3495 try {
3496 return mNetworkManager.isBandwidthControlEnabled();
3497 } catch (RemoteException e) {
3498 // ignored; service lives in system_server
3499 return false;
3500 } finally {
3501 Binder.restoreCallingIdentity(token);
3502 }
3503 }
3504
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003505 /**
3506 * Try refreshing {@link #mTime} when stale.
3507 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003508 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003509 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003510 mTime.forceRefresh();
3511 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003512 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003513
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003514 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003515 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3516 }
3517
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003518 private static Intent buildAllowBackgroundDataIntent() {
3519 return new Intent(ACTION_ALLOW_BACKGROUND);
3520 }
3521
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003522 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3523 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3524 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3525 return intent;
3526 }
3527
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003528 private static Intent buildNetworkOverLimitIntent(NetworkTemplate template) {
3529 final Intent intent = new Intent();
3530 intent.setComponent(new ComponentName(
3531 "com.android.systemui", "com.android.systemui.net.NetworkOverLimitActivity"));
3532 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3533 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3534 return intent;
3535 }
3536
3537 private static Intent buildViewDataUsageIntent(NetworkTemplate template) {
3538 final Intent intent = new Intent();
3539 intent.setComponent(new ComponentName(
3540 "com.android.settings", "com.android.settings.Settings$DataUsageSummaryActivity"));
3541 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3542 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3543 return intent;
3544 }
3545
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003546 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003547 public void addIdleHandler(IdleHandler handler) {
3548 mHandler.getLooper().getQueue().addIdleHandler(handler);
3549 }
3550
Jeff Sharkey1b861272011-05-22 00:34:52 -07003551 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3552 final int size = source.size();
3553 for (int i = 0; i < size; i++) {
3554 target.put(source.keyAt(i), true);
3555 }
3556 }
3557
Stuart Scottf1fb3972015-04-02 18:00:02 -07003558 @Override
3559 public void factoryReset(String subscriber) {
3560 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3561
Stuart Scotte3e314d2015-04-20 14:07:45 -07003562 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3563 return;
3564 }
3565
Stuart Scottf1fb3972015-04-02 18:00:02 -07003566 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003567 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003568 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3569 for (NetworkPolicy policy : policies) {
3570 if (policy.template.equals(template)) {
3571 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3572 policy.inferred = false;
3573 policy.clearSnooze();
3574 }
3575 }
3576 setNetworkPolicies(policies);
3577
3578 // Turn restrict background data off
3579 setRestrictBackground(false);
3580
Stuart Scotte3e314d2015-04-20 14:07:45 -07003581 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3582 // Remove app's "restrict background data" flag
3583 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3584 setUidPolicy(uid, POLICY_NONE);
3585 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003586 }
3587 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003588
3589 private class MyPackageMonitor extends PackageMonitor {
3590
3591 @Override
3592 public void onPackageRemoved(String packageName, int uid) {
3593 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003594 synchronized (mUidRulesFirstLock) {
3595 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3596 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003597 }
3598 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003599 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003600
3601 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3602
3603 @Override
3604 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003605 synchronized (mUidRulesFirstLock) {
3606 boolean changed = removeUserStateUL(userId, false);
3607 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003608 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003609 synchronized (mNetworkPoliciesSecondLock) {
3610 writePolicyAL();
3611 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003612 }
3613 }
3614 }
3615 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003616}