blob: 6381aa7470220780d3a48f84c3a8bab8bb7bba30 [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;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
56import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070060import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070069import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
70import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
71import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
72import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
73import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
74import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
75import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070076import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
83import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
84import static com.android.internal.util.XmlUtils.writeIntAttribute;
85import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070086import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070087import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060088
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080090import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070092
Dianne Hackborn88e98df2015-03-23 13:29:14 -070093import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070094import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070095import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070096import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070097import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070098import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070099import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700101import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700102import android.app.Notification;
103import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700104import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700106import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700107import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700108import android.content.Intent;
109import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700111import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700112import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700113import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700114import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700115import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700118import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700120import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700121import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700123import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700124import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700126import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700127import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700128import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700129import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700130import android.net.wifi.WifiConfiguration;
131import android.net.wifi.WifiInfo;
132import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700133import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700134import android.os.Environment;
135import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700136import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700137import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700138import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700139import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700140import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700141import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700142import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700144import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600145import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146import android.os.ServiceManager;
Felipe Leme873a83a2016-09-07 11:34:10 -0700147import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700148import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700149import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700150import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800151import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700152import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400153import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700154import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700155import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700156import android.util.ArrayMap;
157import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700158import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700159import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700160import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700161import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700162import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700163import android.util.SparseBooleanArray;
164import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.util.TrustedTime;
166import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700167
Jeff Sharkey497e4432011-06-14 17:27:29 -0700168import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700169import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800170import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800171import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700173import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700174import com.android.server.DeviceIdleController;
175import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700176import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800177import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600178
179import libcore.io.IoUtils;
180
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700182
183import org.xmlpull.v1.XmlPullParser;
184import org.xmlpull.v1.XmlPullParserException;
185import org.xmlpull.v1.XmlSerializer;
186
187import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700188import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189import java.io.FileInputStream;
190import java.io.FileNotFoundException;
191import java.io.FileOutputStream;
192import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700193import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700194import java.lang.annotation.Retention;
195import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100196import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import java.util.ArrayList;
198import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700199import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700201/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700202 * Service that maintains low-level network policy rules, using
203 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204 * <p>
205 * Derives active rules by combining a given policy with other system status,
206 * and delivers to listeners, such as {@link ConnectivityManager}, for
207 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700208 *
209 * <p>
210 * This class uses 2-3 locks to synchronize state:
211 * <ul>
212 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
213 * rules).
214 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
215 * as network policies).
216 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
217 * must be held.
218 * </ul>
219 *
220 * <p>
221 * As such, methods that require synchronization have the following prefixes:
222 * <ul>
223 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
224 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
225 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
226 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
227 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700228 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700229public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800230 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700231 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700232 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700233
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700234 private static final int VERSION_INIT = 1;
235 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700236 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800237 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800238 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800239 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700240 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700241 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700242 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700243 private static final int VERSION_SWITCH_UID = 10;
244 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700245
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800246 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700247 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700249 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800250 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700251 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700252
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253 private static final String TAG_POLICY_LIST = "policy-list";
254 private static final String TAG_NETWORK_POLICY = "network-policy";
255 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700256 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800257 private static final String TAG_WHITELIST = "whitelist";
258 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800259 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700260
261 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700262 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
264 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700265 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800267 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268 private static final String ATTR_WARNING_BYTES = "warningBytes";
269 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700270 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800271 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
272 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800273 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700274 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700275 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700276 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700277 private static final String ATTR_POLICY = "policy";
278
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800279 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800280 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800281 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800282 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700283
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700284 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
285
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700286 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700287 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800288 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800289 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700290 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700291 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
292 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700293 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700294 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700295 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700296
Jeff Sharkey75279902011-05-24 18:39:45 -0700297 private final Context mContext;
298 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700299 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
Felipe Lemef0823852016-06-08 13:43:08 -0700316 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
317 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
318 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700319
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700320 private final boolean mSuppressDefaultPolicy;
321
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700322 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800323 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700324 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800325 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700326
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700327 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700328 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700329 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700330 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700331
Felipe Lemef0823852016-06-08 13:43:08 -0700332 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700333 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700334 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700335 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800337 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700338
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700339 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700340 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700341 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
342
Jeff Sharkey32566012014-12-02 18:30:14 -0800343 /**
344 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700345 * in power save mode, except device idle (doze) still applies.
346 * TODO: An int array might be sufficient
347 */
Felipe Lemef0823852016-06-08 13:43:08 -0700348 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700349 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
350
351 /**
352 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800353 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700354 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800355 */
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700357 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700358
Felipe Lemef0823852016-06-08 13:43:08 -0700359 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700360 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
361
Felipe Lemeb85a6372016-01-14 16:16:16 -0800362 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800363 * UIDs that have been initially white-listed by system to avoid restricted background.
364 */
Felipe Lemef0823852016-06-08 13:43:08 -0700365 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800366 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
367 new SparseBooleanArray();
368
369 /**
370 * UIDs that have been initially white-listed by system to avoid restricted background,
371 * but later revoked by user.
372 */
Felipe Lemef0823852016-06-08 13:43:08 -0700373 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800374 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
375 new SparseBooleanArray();
376
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700377 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700378 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800379 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700380 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700383
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700384 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700386 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700387
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700388 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800390 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700391
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600392 /** Higher priority listener before general event dispatch */
393 private INetworkPolicyListener mConnectivityListener;
394
Jeff Sharkey32566012014-12-02 18:30:14 -0800395 private final RemoteCallbackList<INetworkPolicyListener>
396 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700397
Dianne Hackborn497175b2014-07-01 12:56:08 -0700398 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399
Felipe Lemef0823852016-06-08 13:43:08 -0700400 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700401 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700402
Svet Ganov16a16892015-04-16 10:32:04 -0700403 private final AppOpsManager mAppOps;
404
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800405 private final IPackageManager mIPm;
406
Felipe Lemeb85a6372016-01-14 16:16:16 -0800407
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700408 // TODO: keep whitelist of system-critical services that should never have
409 // rules enforced, such as system, phone, and radio UIDs.
410
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700411 // TODO: migrate notifications to SystemUI
412
Jeff Sharkey75279902011-05-24 18:39:45 -0700413 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700414 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
415 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700416 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
417 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700418 }
419
420 private static File getSystemDir() {
421 return new File(Environment.getDataDirectory(), "system");
422 }
423
424 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700425 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700426 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700427 mContext = checkNotNull(context, "missing context");
428 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700429 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700430 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700431 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700432 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700433 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700434 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700435 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436
Amith Yamasani450a16b2013-09-18 16:28:50 -0700437 HandlerThread thread = new HandlerThread(TAG);
438 thread.start();
439 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700440
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700441 mSuppressDefaultPolicy = suppressDefaultPolicy;
442
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700444
445 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800446
Felipe Lemed17fda42016-04-29 11:12:45 -0700447 // Expose private service for system components to use.
448 LocalServices.addService(NetworkPolicyManagerInternal.class,
449 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700450 }
451
452 public void bindConnectivityManager(IConnectivityManager connManager) {
453 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700454 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700455
Jeff Sharkey497e4432011-06-14 17:27:29 -0700456 public void bindNotificationManager(INotificationManager notifManager) {
457 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
458 }
459
Felipe Lemef0823852016-06-08 13:43:08 -0700460 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700461 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700462 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
463 mPowerSaveWhitelistExceptIdleAppIds.clear();
464 if (whitelist != null) {
465 for (int uid : whitelist) {
466 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
467 }
468 }
469 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700470 mPowerSaveWhitelistAppIds.clear();
471 if (whitelist != null) {
472 for (int uid : whitelist) {
473 mPowerSaveWhitelistAppIds.put(uid, true);
474 }
475 }
476 } catch (RemoteException e) {
477 }
478 }
479
Felipe Lemea9505cc2016-02-26 10:28:41 -0800480 /**
481 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
482 * revoke the whitelist.
483 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700484 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800485 */
Felipe Lemef0823852016-06-08 13:43:08 -0700486 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800487 final List<UserInfo> users = mUserManager.getUsers();
488 final int numberUsers = users.size();
489
Felipe Lemea110eec2016-04-29 09:58:06 -0700490 boolean changed = false;
491 for (int i = 0; i < numberUsers; i++) {
492 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700493 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700494 }
495 return changed;
496 }
497
Felipe Lemef0823852016-06-08 13:43:08 -0700498 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700499 final SystemConfig sysConfig = SystemConfig.getInstance();
500 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800501 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
502 boolean changed = false;
503 for (int i = 0; i < allowDataUsage.size(); i++) {
504 final String pkg = allowDataUsage.valueAt(i);
505 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700506 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
507 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800508 final ApplicationInfo app;
509 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700510 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800511 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700512 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
513 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800514 continue;
515 }
516 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700517 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
518 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800519 continue;
520 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700521 final int uid = UserHandle.getUid(userId, app.uid);
522 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
523 if (LOGD)
524 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
525 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800526 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700527 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700528 if (LOGD)
529 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
530 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700531 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700532 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800533 }
534 }
535 return changed;
536 }
537
Felipe Lemef0823852016-06-08 13:43:08 -0700538 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700539 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700540 // Clear the states of the current whitelist
541 final int N = mPowerSaveTempWhitelistAppIds.size();
542 for (int i = 0; i < N; i++) {
543 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
544 }
545 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700546 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700547 if (whitelist != null) {
548 for (int uid : whitelist) {
549 mPowerSaveTempWhitelistAppIds.put(uid, true);
550 }
551 }
552 } catch (RemoteException e) {
553 }
554 }
555
Amith Yamasani06f08062015-06-12 13:23:33 -0700556 /**
557 * Remove unnecessary entries in the temp whitelist
558 */
Felipe Lemef0823852016-06-08 13:43:08 -0700559 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700560 final int N = mPowerSaveTempWhitelistAppIds.size();
561 for (int i = N - 1; i >= 0; i--) {
562 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
563 mPowerSaveTempWhitelistAppIds.removeAt(i);
564 }
565 }
566 }
567
Jeff Sharkeya4620792011-05-20 15:29:23 -0700568 public void systemReady() {
Felipe Leme873a83a2016-09-07 11:34:10 -0700569 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
570 try {
571 if (!isBandwidthControlEnabled()) {
572 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
573 return;
574 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700575
Felipe Leme873a83a2016-09-07 11:34:10 -0700576 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700577
Felipe Leme873a83a2016-09-07 11:34:10 -0700578 synchronized (mUidRulesFirstLock) {
579 synchronized (mNetworkPoliciesSecondLock) {
580 updatePowerSaveWhitelistUL();
581 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
582 mPowerManagerInternal.registerLowPowerModeObserver(
583 new PowerManagerInternal.LowPowerModeListener() {
584 @Override
585 public void onLowPowerModeChanged(boolean enabled) {
586 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
587 synchronized (mUidRulesFirstLock) {
588 if (mRestrictPower != enabled) {
589 mRestrictPower = enabled;
590 updateRulesForRestrictPowerUL();
591 }
Felipe Lemef0823852016-06-08 13:43:08 -0700592 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700593 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700594 });
595 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
596
597 mSystemReady = true;
598
599 // read policy from disk
600 readPolicyAL();
601
602 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
603 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700604 }
Felipe Lemef0823852016-06-08 13:43:08 -0700605
Felipe Leme873a83a2016-09-07 11:34:10 -0700606 setRestrictBackgroundUL(mRestrictBackground);
607 updateRulesForGlobalChangeAL(false);
608 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700609 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800610 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700611
612 try {
613 mActivityManager.registerUidObserver(mUidObserver,
614 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
615 mNetworkManager.registerObserver(mAlertObserver);
616 } catch (RemoteException e) {
617 // ignored; both services live in system_server
618 }
619
620 // listen for changes to power save whitelist
621 final IntentFilter whitelistFilter = new IntentFilter(
622 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
623 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
624
625 DeviceIdleController.LocalService deviceIdleService
626 = LocalServices.getService(DeviceIdleController.LocalService.class);
627 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
628
629 // watch for network interfaces to be claimed
630 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
631 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
632
633 // listen for package changes to update policy
634 final IntentFilter packageFilter = new IntentFilter();
635 packageFilter.addAction(ACTION_PACKAGE_ADDED);
636 packageFilter.addDataScheme("package");
637 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
638
639 // listen for UID changes to update policy
640 mContext.registerReceiver(
641 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
642
643 // listen for user changes to update policy
644 final IntentFilter userFilter = new IntentFilter();
645 userFilter.addAction(ACTION_USER_ADDED);
646 userFilter.addAction(ACTION_USER_REMOVED);
647 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
648
649 // listen for stats update events
650 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
651 mContext.registerReceiver(
652 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
653
654 // listen for restrict background changes from notifications
655 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
656 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
657
658 // listen for snooze warning from notifications
659 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
660 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
661 MANAGE_NETWORK_POLICY, mHandler);
662
663 // listen for configured wifi networks to be removed
664 final IntentFilter wifiConfigFilter =
665 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
666 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
667
668 // listen for wifi state changes to catch metered hint
669 final IntentFilter wifiStateFilter = new IntentFilter(
670 WifiManager.NETWORK_STATE_CHANGED_ACTION);
671 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
672
673 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
674 } finally {
675 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700676 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700677 }
678
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700679 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700680 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700681 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
682 try {
683 synchronized (mUidRulesFirstLock) {
684 updateUidStateUL(uid, procState);
685 }
686 } finally {
687 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700688 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700689 }
690
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700691 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700692 synchronized (mUidRulesFirstLock) {
693 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700694 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700695 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700696
697 @Override public void onUidActive(int uid) throws RemoteException {
698 }
699
700 @Override public void onUidIdle(int uid) throws RemoteException {
701 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700702 };
703
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700704 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700705 @Override
706 public void onReceive(Context context, Intent intent) {
707 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700708 synchronized (mUidRulesFirstLock) {
709 updatePowerSaveWhitelistUL();
710 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700711 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700712 }
713 }
714 };
715
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700716 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
717 @Override
718 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700719 synchronized (mUidRulesFirstLock) {
720 updatePowerSaveTempWhitelistUL();
721 updateRulesForTempWhitelistChangeUL();
722 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700723 }
724 }
725 };
726
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700727 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700728 @Override
729 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700730 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700731
732 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700733 final int uid = intent.getIntExtra(EXTRA_UID, -1);
734 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700735
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700736 if (ACTION_PACKAGE_ADDED.equals(action)) {
737 // update rules for UID, since it might be subject to
738 // global background data policy
739 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700740 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700741 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700742 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700743 }
744 }
745 };
746
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700747 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700748 @Override
749 public void onReceive(Context context, Intent intent) {
750 // on background handler thread, and UID_REMOVED is protected
751
752 final int uid = intent.getIntExtra(EXTRA_UID, -1);
753 if (uid == -1) return;
754
755 // remove any policy and update rules to clean up
756 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700757 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700758 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700759 synchronized (mNetworkPoliciesSecondLock) {
760 writePolicyAL();
761 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700762 }
763 }
764 };
765
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700766 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700767 @Override
768 public void onReceive(Context context, Intent intent) {
769 // on background handler thread, and USER_ADDED and USER_REMOVED
770 // broadcasts are protected
771
772 final String action = intent.getAction();
773 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
774 if (userId == -1) return;
775
Amith Yamasani15e472352015-04-24 19:06:07 -0700776 switch (action) {
777 case ACTION_USER_REMOVED:
778 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700779 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800780 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700781 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700782 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700783 if (action == ACTION_USER_ADDED) {
784 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700785 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700786 }
787 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700788 synchronized (mNetworkPoliciesSecondLock) {
789 updateRulesForGlobalChangeAL(true);
790 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700791 }
792 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700793 }
794 }
795 };
796
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700797 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700798 * Receiver that watches for {@link INetworkStatsService} updates, which we
799 * use to check against {@link NetworkPolicy#warningBytes}.
800 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700801 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700802 @Override
803 public void onReceive(Context context, Intent intent) {
804 // on background handler thread, and verified
805 // READ_NETWORK_USAGE_HISTORY permission above.
806
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800807 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700808 synchronized (mNetworkPoliciesSecondLock) {
809 updateNetworkEnabledNL();
810 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700811 }
812 }
813 };
814
815 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700816 * Receiver that watches for {@link Notification} control of
817 * {@link #mRestrictBackground}.
818 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700819 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700820 @Override
821 public void onReceive(Context context, Intent intent) {
822 // on background handler thread, and verified MANAGE_NETWORK_POLICY
823 // permission above.
824
825 setRestrictBackground(false);
826 }
827 };
828
829 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800830 * Receiver that watches for {@link Notification} control of
831 * {@link NetworkPolicy#lastWarningSnooze}.
832 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700833 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800834 @Override
835 public void onReceive(Context context, Intent intent) {
836 // on background handler thread, and verified MANAGE_NETWORK_POLICY
837 // permission above.
838
839 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
840 performSnooze(template, TYPE_WARNING);
841 }
842 };
843
844 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700845 * Receiver that watches for {@link WifiConfiguration} to be changed.
846 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700847 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700848 @Override
849 public void onReceive(Context context, Intent intent) {
850 // on background handler thread, and verified CONNECTIVITY_INTERNAL
851 // permission above.
852
853 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
854 if (reason == CHANGE_REASON_REMOVED) {
855 final WifiConfiguration config = intent.getParcelableExtra(
856 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700857 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800858 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700859 synchronized (mUidRulesFirstLock) {
860 synchronized (mNetworkPoliciesSecondLock) {
861 if (mNetworkPolicy.containsKey(template)) {
862 mNetworkPolicy.remove(template);
863 writePolicyAL();
864 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700865 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700866 }
867 }
868 }
869 }
870 };
871
872 /**
873 * Receiver that watches {@link WifiInfo} state changes to infer metered
874 * state. Ignores hints when policy is user-defined.
875 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700876 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700877 @Override
878 public void onReceive(Context context, Intent intent) {
879 // on background handler thread, and verified CONNECTIVITY_INTERNAL
880 // permission above.
881
882 // ignore when not connected
883 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
884 if (!netInfo.isConnected()) return;
885
886 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
887 final boolean meteredHint = info.getMeteredHint();
888
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800889 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700890 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700891 NetworkPolicy policy = mNetworkPolicy.get(template);
892 if (policy == null && meteredHint) {
893 // policy doesn't exist, and AP is hinting that it's
894 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800895 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700896 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700897
898 } else if (policy != null && policy.inferred) {
899 // policy exists, and was inferred: update its current
900 // metered state.
901 policy.metered = meteredHint;
902
903 // since this is inferred for each wifi session, just update
904 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700905 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700906 }
907 }
908 }
909 };
910
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800911 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
912 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
913 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
914 metered, true);
915 }
916
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700917 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700918 * Observer that watches for {@link INetworkManagementService} alerts.
919 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700920 final private INetworkManagementEventObserver mAlertObserver
921 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700922 @Override
923 public void limitReached(String limitName, String iface) {
924 // only someone like NMS should be calling us
925 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
926
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800927 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
928 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700929 }
930 }
931 };
932
933 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
935 * to show visible notifications as needed.
936 */
Felipe Lemef0823852016-06-08 13:43:08 -0700937 void updateNotificationsNL() {
938 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700940 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700941 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700942 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700943
944 // TODO: when switching to kernel notifications, compute next future
945 // cycle boundary to recompute notifications.
946
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700947 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800948 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700949 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
950 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700951 // ignore policies that aren't relevant to user
952 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700953 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700954
Jeff Sharkey497e4432011-06-14 17:27:29 -0700955 final long start = computeLastCycleBoundary(currentTime, policy);
956 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700957 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700958
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700959 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800960 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700961 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
962 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700963 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700964 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700965 }
966
Jeff Sharkey497e4432011-06-14 17:27:29 -0700967 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700968 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700969
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800970 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700971 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700972 }
973 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700974 }
975
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700976 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700977 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
978 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700979 if (!mActiveNotifs.contains(tag)) {
980 cancelNotification(tag);
981 }
982 }
983 }
984
985 /**
986 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700987 * current device state, such as when
988 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
989 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700990 */
991 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800992 if (template.isMatchRuleMobile()) {
993 final TelephonyManager tele = TelephonyManager.from(mContext);
994 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700995
Jeff Sharkey32566012014-12-02 18:30:14 -0800996 // Mobile template is relevant when any active subscriber matches
997 final int[] subIds = sub.getActiveSubscriptionIdList();
998 for (int subId : subIds) {
999 final String subscriberId = tele.getSubscriberId(subId);
1000 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001001 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001002 if (template.matches(probeIdent)) {
1003 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001004 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001005 }
1006 return false;
1007 } else {
1008 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001009 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001010 }
1011
1012 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 * Notify that given {@link NetworkTemplate} is over
1014 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1015 */
Felipe Lemef0823852016-06-08 13:43:08 -07001016 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001017 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001018 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 mOverLimitNotified.add(template);
1020 }
1021 }
1022
Felipe Lemef0823852016-06-08 13:43:08 -07001023 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001024 mOverLimitNotified.remove(template);
1025 }
1026
1027 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 * Build unique tag that identifies an active {@link NetworkPolicy}
1029 * notification of a specific type, like {@link #TYPE_LIMIT}.
1030 */
1031 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001032 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001033 }
1034
1035 /**
1036 * Show notification for combined {@link NetworkPolicy} and specific type,
1037 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1038 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001039 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001040 final String tag = buildNotificationTag(policy, type);
1041 final Notification.Builder builder = new Notification.Builder(mContext);
1042 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001043 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001044 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001045 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046
1047 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001048 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001049 switch (type) {
1050 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001051 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001052 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001053
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001054 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055 builder.setTicker(title);
1056 builder.setContentTitle(title);
1057 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001058 builder.setDefaults(Notification.DEFAULT_ALL);
1059 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001060
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001061 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1062 builder.setDeleteIntent(PendingIntent.getBroadcast(
1063 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1064
Wei Liu546cb772016-07-21 16:19:01 -07001065 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001066 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001067 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1068
Jeff Sharkey497e4432011-06-14 17:27:29 -07001069 break;
1070 }
1071 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001072 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073
1074 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001075 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001076 switch (policy.template.getMatchRule()) {
1077 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001078 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001079 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001080 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001086 case MATCH_WIFI:
1087 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001088 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001089 break;
1090 default:
1091 title = null;
1092 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001093 }
1094
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001095 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001096 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001097 builder.setTicker(title);
1098 builder.setContentTitle(title);
1099 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001100
Wei Liu546cb772016-07-21 16:19:01 -07001101 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 builder.setContentIntent(PendingIntent.getActivity(
1103 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1104 break;
1105 }
1106 case TYPE_LIMIT_SNOOZED: {
1107 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001108 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001109 Formatter.formatFileSize(mContext, overBytes));
1110
1111 final CharSequence title;
1112 switch (policy.template.getMatchRule()) {
1113 case MATCH_MOBILE_3G_LOWER:
1114 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1115 break;
1116 case MATCH_MOBILE_4G:
1117 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1118 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001120 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1121 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 case MATCH_WIFI:
1123 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1124 break;
1125 default:
1126 title = null;
1127 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 }
1129
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001130 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001131 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001132 builder.setTicker(title);
1133 builder.setContentTitle(title);
1134 builder.setContentText(body);
1135
Wei Liu546cb772016-07-21 16:19:01 -07001136 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001137 builder.setContentIntent(PendingIntent.getActivity(
1138 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001139 break;
1140 }
1141 }
1142
1143 // TODO: move to NotificationManager once we can mock it
1144 try {
1145 final String packageName = mContext.getPackageName();
1146 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001147 if(!TextUtils.isEmpty(body)) {
1148 builder.setStyle(new Notification.BigTextStyle()
1149 .bigText(body));
1150 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001151 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001152 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001153 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001154 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001155 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001156 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001157 }
1158 }
1159
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001160 private void cancelNotification(String tag) {
1161 // TODO: move to NotificationManager once we can mock it
1162 try {
1163 final String packageName = mContext.getPackageName();
1164 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001165 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001166 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001167 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 }
1169 }
1170
1171 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001172 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001173 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001174 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001175 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001176 @Override
1177 public void onReceive(Context context, Intent intent) {
1178 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1179 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001180
1181 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001182 synchronized (mNetworkPoliciesSecondLock) {
1183 ensureActiveMobilePolicyNL();
1184 normalizePoliciesNL();
1185 updateNetworkEnabledNL();
1186 updateNetworkRulesNL();
1187 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 }
1189 }
1190 };
1191
1192 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001193 * Proactively control network data connections when they exceed
1194 * {@link NetworkPolicy#limitBytes}.
1195 */
Felipe Lemef0823852016-06-08 13:43:08 -07001196 void updateNetworkEnabledNL() {
1197 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198
1199 // TODO: reset any policy-disabled networks when any policy is removed
1200 // completely, which is currently rare case.
1201
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001202 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001203 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1204 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001205 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001206 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001207 setNetworkTemplateEnabled(policy.template, true);
1208 continue;
1209 }
1210
1211 final long start = computeLastCycleBoundary(currentTime, policy);
1212 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001213 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001214
1215 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001216 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1217 && policy.lastLimitSnooze < start;
1218 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001219
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001220 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001221 }
1222 }
1223
1224 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001225 * Proactively disable networks that match the given
1226 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227 */
1228 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001229 // TODO: reach into ConnectivityManager to proactively disable bringing
1230 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001231
1232 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1233 // If mobile data usage hits the limit or if the user resumes the data, we need to
1234 // notify telephony.
1235 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1236 final TelephonyManager tm = TelephonyManager.from(mContext);
1237
1238 final int[] subIds = sm.getActiveSubscriptionIdList();
1239 for (int subId : subIds) {
1240 final String subscriberId = tm.getSubscriberId(subId);
1241 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1242 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1243 // Template is matched when subscriber id matches.
1244 if (template.matches(probeIdent)) {
1245 tm.setPolicyDataEnabled(enabled, subId);
1246 }
1247 }
1248 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001249 }
1250
1251 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001252 * Examine all connected {@link NetworkState}, looking for
1253 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1254 * remaining quota based on usage cycle and historical stats.
1255 */
Felipe Lemef0823852016-06-08 13:43:08 -07001256 void updateNetworkRulesNL() {
1257 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001258
1259 final NetworkState[] states;
1260 try {
1261 states = mConnManager.getAllNetworkState();
1262 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001263 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 return;
1265 }
1266
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001267 // First, generate identities of all connected networks so we can
1268 // quickly compare them against all defined policies below.
1269 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001270 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001272 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001273 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001274
1275 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001276 if (baseIface != null) {
1277 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001278 }
1279
1280 // Stacked interfaces are considered to have same identity as
1281 // their parent network.
1282 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1283 for (LinkProperties stackedLink : stackedLinks) {
1284 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001285 if (stackedIface != null) {
1286 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001287 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001288 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 }
1290 }
1291
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001292 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001293 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001295 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001296 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001298 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001299 for (int j = connIdents.size() - 1; j >= 0; j--) {
1300 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1301 if (policy.template.matches(ident.second)) {
1302 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 }
1304 }
1305
1306 if (ifaceList.size() > 0) {
1307 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001308 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001309 }
1310 }
1311
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001312 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001313 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001314
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001315 // apply each policy that we found ifaces for; compute remaining data
1316 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001317 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001318 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1319 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1320 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001322 final long start;
1323 final long totalBytes;
1324 if (policy.hasCycle()) {
1325 start = computeLastCycleBoundary(currentTime, policy);
1326 totalBytes = getTotalBytes(policy.template, start, currentTime);
1327 } else {
1328 start = Long.MAX_VALUE;
1329 totalBytes = 0;
1330 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001331
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001333 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334 }
1335
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001336 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001337 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001338 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001339 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001340 if (!hasLimit) {
1341 // metered network, but no policy limit; we still need to
1342 // restrict apps, so push really high quota.
1343 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001344 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001345 // snoozing past quota, but we still need to restrict apps,
1346 // so push really high quota.
1347 quotaBytes = Long.MAX_VALUE;
1348 } else {
1349 // remaining "quota" bytes are based on total usage in
1350 // current cycle. kernel doesn't like 0-byte rules, so we
1351 // set 1-byte quota and disable the radio later.
1352 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1353 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001354
1355 if (ifaces.length > 1) {
1356 // TODO: switch to shared quota once NMS supports
1357 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001358 }
1359
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001360 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001361 // long quotaBytes split up into two ints to fit in message
1362 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1363 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1364 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001365 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001366 }
1367 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001368
1369 // keep track of lowest warning or limit of active policies
1370 if (hasWarning && policy.warningBytes < lowestRule) {
1371 lowestRule = policy.warningBytes;
1372 }
1373 if (hasLimit && policy.limitBytes < lowestRule) {
1374 lowestRule = policy.limitBytes;
1375 }
1376 }
1377
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001378 for (int i = connIfaces.size()-1; i >= 0; i--) {
1379 String iface = connIfaces.valueAt(i);
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) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1383 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001384 newMeteredIfaces.add(iface);
1385 }
1386
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001387 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001389 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001390 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1391 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001392 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001393 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1394 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001395 }
1396 }
1397 mMeteredIfaces = newMeteredIfaces;
1398
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001400 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001401 }
1402
1403 /**
1404 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1405 * have at least a default mobile policy defined.
1406 */
Felipe Lemef0823852016-06-08 13:43:08 -07001407 private void ensureActiveMobilePolicyNL() {
1408 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001409 if (mSuppressDefaultPolicy) return;
1410
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001411 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001412 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001413
Jeff Sharkey32566012014-12-02 18:30:14 -08001414 final int[] subIds = sub.getActiveSubscriptionIdList();
1415 for (int subId : subIds) {
1416 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001417 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001418 }
1419 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001420
Felipe Lemef0823852016-06-08 13:43:08 -07001421 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001422 // Poke around to see if we already have a policy
1423 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001424 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001425 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1426 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1427 if (template.matches(probeIdent)) {
1428 if (LOGD) {
1429 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1430 + NetworkIdentity.scrubSubscriberId(subscriberId));
1431 }
1432 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001433 }
1434 }
1435
Jeff Sharkey32566012014-12-02 18:30:14 -08001436 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1437 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001438
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001440 final int dataWarningConfig = mContext.getResources().getInteger(
1441 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1442 final long warningBytes;
1443 if (dataWarningConfig == WARNING_DISABLED) {
1444 warningBytes = WARNING_DISABLED;
1445 } else {
1446 warningBytes = dataWarningConfig * MB_IN_BYTES;
1447 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001448
Jeff Sharkey32566012014-12-02 18:30:14 -08001449 final Time time = new Time();
1450 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001451
Jeff Sharkey32566012014-12-02 18:30:14 -08001452 final int cycleDay = time.monthDay;
1453 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001454
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1456 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1457 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001458 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459 }
1460
Felipe Lemef0823852016-06-08 13:43:08 -07001461 private void readPolicyAL() {
1462 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463
1464 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001465 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001466 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467
1468 FileInputStream fis = null;
1469 try {
1470 fis = mPolicyFile.openRead();
1471 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001472 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473
Felipe Leme46b451f2016-08-19 08:46:17 -07001474 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1475 // to skip UIDs that were explicitly blacklisted.
1476 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1477
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001478 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001479 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001480 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001481 while ((type = in.next()) != END_DOCUMENT) {
1482 final String tag = in.getName();
1483 if (type == START_TAG) {
1484 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001485 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001487 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1488 mRestrictBackground = readBooleanAttribute(
1489 in, ATTR_RESTRICT_BACKGROUND);
1490 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001491 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001492 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001493 if (mRestrictBackground != oldValue) {
1494 // Some early services may have read the default value,
1495 // so notify them that it's changed
1496 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1497 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1498 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499
1500 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1501 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1502 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001503 final String networkId;
1504 if (version >= VERSION_ADDED_NETWORK_ID) {
1505 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1506 } else {
1507 networkId = null;
1508 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001509 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001510 final String cycleTimezone;
1511 if (version >= VERSION_ADDED_TIMEZONE) {
1512 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1513 } else {
1514 cycleTimezone = Time.TIMEZONE_UTC;
1515 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1517 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001518 final long lastLimitSnooze;
1519 if (version >= VERSION_SPLIT_SNOOZE) {
1520 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1521 } else if (version >= VERSION_ADDED_SNOOZE) {
1522 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001523 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001524 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001525 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001526 final boolean metered;
1527 if (version >= VERSION_ADDED_METERED) {
1528 metered = readBooleanAttribute(in, ATTR_METERED);
1529 } else {
1530 switch (networkTemplate) {
1531 case MATCH_MOBILE_3G_LOWER:
1532 case MATCH_MOBILE_4G:
1533 case MATCH_MOBILE_ALL:
1534 metered = true;
1535 break;
1536 default:
1537 metered = false;
1538 }
1539 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001540 final long lastWarningSnooze;
1541 if (version >= VERSION_SPLIT_SNOOZE) {
1542 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1543 } else {
1544 lastWarningSnooze = SNOOZE_NEVER;
1545 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001546 final boolean inferred;
1547 if (version >= VERSION_ADDED_INFERRED) {
1548 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1549 } else {
1550 inferred = false;
1551 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001552
Jeff Sharkey32566012014-12-02 18:30:14 -08001553 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1554 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001555 if (template.isPersistable()) {
1556 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1557 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1558 lastLimitSnooze, metered, inferred));
1559 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001562 final int uid = readIntAttribute(in, ATTR_UID);
1563 final int policy = readIntAttribute(in, ATTR_POLICY);
1564
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001565 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001566 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001567 } else {
1568 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1569 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001570 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001571 final int appId = readIntAttribute(in, ATTR_APP_ID);
1572 final int policy = readIntAttribute(in, ATTR_POLICY);
1573
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001574 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001575 // app policy is deprecated so this is only used in pre system user split.
1576 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001577 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001578 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001579 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001580 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001581 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001582 } else if (TAG_WHITELIST.equals(tag)) {
1583 insideWhitelist = true;
1584 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1585 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001586 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001587 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1588 final int uid = readIntAttribute(in, ATTR_UID);
1589 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001590 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001591 } else if (type == END_TAG) {
1592 if (TAG_WHITELIST.equals(tag)) {
1593 insideWhitelist = false;
1594 }
1595
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001596 }
1597 }
1598
Felipe Leme46b451f2016-08-19 08:46:17 -07001599 final int size = whitelistedRestrictBackground.size();
1600 for (int i = 0; i < size; i++) {
1601 final int uid = whitelistedRestrictBackground.keyAt(i);
1602 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1603 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1604 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1605 + " because its policy is " + uidPoliciesToString(policy));
1606 continue;
1607 }
1608 if (UserHandle.isApp(uid)) {
1609 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1610 if (LOGV)
1611 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1612 setUidPolicyUncheckedUL(uid, newPolicy, false);
1613 } else {
1614 Slog.w(TAG, "unable to update policy on UID " + uid);
1615 }
1616 }
1617
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001618 } catch (FileNotFoundException e) {
1619 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001620 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001621 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001622 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001623 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001624 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 } finally {
1626 IoUtils.closeQuietly(fis);
1627 }
1628 }
1629
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001630 /**
1631 * Upgrade legacy background data flags, notifying listeners of one last
1632 * change to always-true.
1633 */
Felipe Lemef0823852016-06-08 13:43:08 -07001634 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001635 mRestrictBackground = Settings.Secure.getInt(
1636 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1637
1638 // kick off one last broadcast if restricted
1639 if (mRestrictBackground) {
1640 final Intent broadcast = new Intent(
1641 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001642 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001643 }
1644 }
1645
Felipe Lemef0823852016-06-08 13:43:08 -07001646 void writePolicyAL() {
1647 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648
1649 FileOutputStream fos = null;
1650 try {
1651 fos = mPolicyFile.startWrite();
1652
1653 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001654 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655 out.startDocument(null, true);
1656
1657 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001658 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001659 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001660
1661 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001662 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1663 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001664 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001665 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001666
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001667 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001668 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1669 final String subscriberId = template.getSubscriberId();
1670 if (subscriberId != null) {
1671 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001672 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001673 final String networkId = template.getNetworkId();
1674 if (networkId != null) {
1675 out.attribute(null, ATTR_NETWORK_ID, networkId);
1676 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001678 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001679 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1680 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001681 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1682 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001683 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001684 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001685 out.endTag(null, TAG_NETWORK_POLICY);
1686 }
1687
1688 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001689 for (int i = 0; i < mUidPolicy.size(); i++) {
1690 final int uid = mUidPolicy.keyAt(i);
1691 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001692
Jeff Sharkey497e4432011-06-14 17:27:29 -07001693 // skip writing empty policies
1694 if (policy == POLICY_NONE) continue;
1695
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001696 out.startTag(null, TAG_UID_POLICY);
1697 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001698 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001699 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001700 }
1701
1702 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001703
1704 // write all whitelists
1705 out.startTag(null, TAG_WHITELIST);
1706
Felipe Lemea9505cc2016-02-26 10:28:41 -08001707 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001708 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001709 for (int i = 0; i < size; i++) {
1710 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1711 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1712 writeIntAttribute(out, ATTR_UID, uid);
1713 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1714 }
1715
Felipe Lemeb85a6372016-01-14 16:16:16 -08001716 out.endTag(null, TAG_WHITELIST);
1717
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001718 out.endDocument();
1719
1720 mPolicyFile.finishWrite(fos);
1721 } catch (IOException e) {
1722 if (fos != null) {
1723 mPolicyFile.failWrite(fos);
1724 }
1725 }
1726 }
1727
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001728 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001729 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001730 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001731
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001732 if (!UserHandle.isApp(uid)) {
1733 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001734 }
Felipe Lemef0823852016-06-08 13:43:08 -07001735 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001736 final long token = Binder.clearCallingIdentity();
1737 try {
1738 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1739 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001740 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001741 }
1742 } finally {
1743 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001744 }
1745 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001746 }
1747
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001748 @Override
1749 public void addUidPolicy(int uid, int policy) {
1750 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001751
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001752 if (!UserHandle.isApp(uid)) {
1753 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1754 }
1755
Felipe Lemef0823852016-06-08 13:43:08 -07001756 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001757 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1758 policy |= oldPolicy;
1759 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001760 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001761 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001762 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001763 }
1764
1765 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001766 public void removeUidPolicy(int uid, int policy) {
1767 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1768
1769 if (!UserHandle.isApp(uid)) {
1770 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1771 }
1772
Felipe Lemef0823852016-06-08 13:43:08 -07001773 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001774 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1775 policy = oldPolicy & ~policy;
1776 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001777 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001778 }
1779 }
1780 }
1781
Felipe Lemef0823852016-06-08 13:43:08 -07001782 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1783 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001784
Felipe Leme57e3d312016-08-23 14:42:52 -07001785 final boolean notifyApp;
1786 if (!isUidValidForWhitelistRules(uid)) {
1787 notifyApp = false;
1788 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001789 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1790 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1791 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1792 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001793 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1794 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001795 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1796 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1797 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1798 if (LOGD)
1799 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1800 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1801 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001802 notifyApp = wasBlocked != isBlocked;
1803 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001804 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1805 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001806 }
1807
Felipe Lemef0823852016-06-08 13:43:08 -07001808 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001809 if (policy == POLICY_NONE) {
1810 mUidPolicy.delete(uid);
1811 } else {
1812 mUidPolicy.put(uid, policy);
1813 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001814
1815 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001816 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001817 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001818 synchronized (mNetworkPoliciesSecondLock) {
1819 writePolicyAL();
1820 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001821 }
1822 }
1823
1824 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001825 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001826 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1827
Felipe Lemef0823852016-06-08 13:43:08 -07001828 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001829 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001830 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001831 }
1832
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001833 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001834 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001835 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1836
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001837 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001838 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001839 for (int i = 0; i < mUidPolicy.size(); i++) {
1840 final int uid = mUidPolicy.keyAt(i);
1841 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001842 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1843 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001844 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001845 }
1846 }
1847 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001848 return uids;
1849 }
1850
1851 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001852 * Removes any persistable state associated with given {@link UserHandle}, persisting
1853 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001854 */
Felipe Lemef0823852016-06-08 13:43:08 -07001855 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001856
Felipe Lemef0823852016-06-08 13:43:08 -07001857 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001858 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001859
Felipe Lemea110eec2016-04-29 09:58:06 -07001860 // 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 Leme873a83a2016-09-07 11:34:10 -07002077 updateRulesForRestrictBackgroundUL();
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
Felipe Lemeb85a6372016-01-14 16:16:16 -08002095 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002096 public int getRestrictBackgroundByCaller() {
2097 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2098 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002099
Felipe Lemef0823852016-06-08 13:43:08 -07002100 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002101 // Must clear identity because getUidPolicy() is restricted to system.
2102 final long token = Binder.clearCallingIdentity();
2103 final int policy;
2104 try {
2105 policy = getUidPolicy(uid);
2106 } finally {
2107 Binder.restoreCallingIdentity(token);
2108 }
2109 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2110 // App is blacklisted.
2111 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2112 }
Felipe Leme1b103232016-01-22 09:44:57 -08002113 if (!mRestrictBackground) {
2114 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2115 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002116 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002117 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2118 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2119 }
2120 }
2121
2122 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002123 public boolean getRestrictBackground() {
2124 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2125
Felipe Lemef0823852016-06-08 13:43:08 -07002126 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002127 return mRestrictBackground;
2128 }
2129 }
2130
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002131 @Override
2132 public void setDeviceIdleMode(boolean enabled) {
2133 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002134 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2135 try {
2136 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002137 if (mDeviceIdleMode == enabled) {
2138 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002139 }
Felipe Lemeea014392016-09-06 13:59:54 -07002140 mDeviceIdleMode = enabled;
2141 if (mSystemReady) {
2142 // Device idle change means we need to rebuild rules for all
2143 // known apps, so do a global refresh.
2144 updateRulesForRestrictPowerUL();
2145 }
2146 }
2147 if (enabled) {
2148 EventLogTags.writeDeviceIdleOnPhase("net");
2149 } else {
2150 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002151 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002152 } finally {
2153 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002154 }
2155 }
2156
Felipe Lemef0823852016-06-08 13:43:08 -07002157 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002158 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2159 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002160 if (policy.template.matches(ident)) {
2161 return policy;
2162 }
2163 }
2164 return null;
2165 }
2166
2167 @Override
2168 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2169 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2170
2171 // only returns usage summary, so we don't require caller to have
2172 // READ_NETWORK_USAGE_HISTORY.
2173 final long token = Binder.clearCallingIdentity();
2174 try {
2175 return getNetworkQuotaInfoUnchecked(state);
2176 } finally {
2177 Binder.restoreCallingIdentity(token);
2178 }
2179 }
2180
2181 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2182 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2183
2184 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002185 synchronized (mNetworkPoliciesSecondLock) {
2186 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002187 }
2188
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002189 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002190 // missing policy means we can't derive useful quota info
2191 return null;
2192 }
2193
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002194 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002195
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002196 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002197 final long start = computeLastCycleBoundary(currentTime, policy);
2198 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002199 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002200
2201 // report soft and hard limits under policy
2202 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2203 : NetworkQuotaInfo.NO_LIMIT;
2204 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2205 : NetworkQuotaInfo.NO_LIMIT;
2206
2207 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2208 }
2209
Jeff Sharkey46645002011-07-27 21:11:21 -07002210 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002211 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002212 if (state.networkInfo == null) {
2213 return false;
2214 }
2215
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002216 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2217
2218 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002219 synchronized (mNetworkPoliciesSecondLock) {
2220 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002221 }
2222
2223 if (policy != null) {
2224 return policy.metered;
2225 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002226 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002227 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002228 return true;
2229 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002230 return false;
2231 }
2232 }
2233
2234 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002235 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002236 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002237
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002238 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2239
Dianne Hackborn497175b2014-07-01 12:56:08 -07002240 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002241 for (String arg : args) {
2242 argSet.add(arg);
2243 }
2244
Felipe Lemef0823852016-06-08 13:43:08 -07002245 synchronized (mUidRulesFirstLock) {
2246 synchronized (mNetworkPoliciesSecondLock) {
2247 if (argSet.contains("--unsnooze")) {
2248 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2249 mNetworkPolicy.valueAt(i).clearSnooze();
2250 }
2251
2252 normalizePoliciesNL();
2253 updateNetworkEnabledNL();
2254 updateNetworkRulesNL();
2255 updateNotificationsNL();
2256 writePolicyAL();
2257
2258 fout.println("Cleared snooze timestamps");
2259 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002260 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002261
Felipe Lemef0823852016-06-08 13:43:08 -07002262 fout.print("System ready: "); fout.println(mSystemReady);
2263 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2264 fout.print("Restrict power: "); fout.println(mRestrictPower);
2265 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2266 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002267 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002268 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2269 fout.println(mNetworkPolicy.valueAt(i).toString());
2270 }
2271 fout.decreaseIndent();
2272
2273 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2274
2275 fout.println("Policy for UIDs:");
2276 fout.increaseIndent();
2277 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002278 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002279 final int uid = mUidPolicy.keyAt(i);
2280 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002281 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002282 fout.print(uid);
2283 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002284 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002285 fout.println();
2286 }
2287 fout.decreaseIndent();
2288
2289 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2290 if (size > 0) {
2291 fout.println("Power save whitelist (except idle) app ids:");
2292 fout.increaseIndent();
2293 for (int i = 0; i < size; i++) {
2294 fout.print("UID=");
2295 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2296 fout.print(": ");
2297 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2298 fout.println();
2299 }
2300 fout.decreaseIndent();
2301 }
2302
2303 size = mPowerSaveWhitelistAppIds.size();
2304 if (size > 0) {
2305 fout.println("Power save whitelist app ids:");
2306 fout.increaseIndent();
2307 for (int i = 0; i < size; i++) {
2308 fout.print("UID=");
2309 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2310 fout.print(": ");
2311 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2312 fout.println();
2313 }
2314 fout.decreaseIndent();
2315 }
2316
Felipe Lemef0823852016-06-08 13:43:08 -07002317 size = mDefaultRestrictBackgroundWhitelistUids.size();
2318 if (size > 0) {
2319 fout.println("Default restrict background whitelist uids:");
2320 fout.increaseIndent();
2321 for (int i = 0; i < size; i++) {
2322 fout.print("UID=");
2323 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2324 fout.println();
2325 }
2326 fout.decreaseIndent();
2327 }
2328
2329 size = mRestrictBackgroundWhitelistRevokedUids.size();
2330 if (size > 0) {
2331 fout.println("Default restrict background whitelist uids revoked by users:");
2332 fout.increaseIndent();
2333 for (int i = 0; i < size; i++) {
2334 fout.print("UID=");
2335 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2336 fout.println();
2337 }
2338 fout.decreaseIndent();
2339 }
2340
2341 final SparseBooleanArray knownUids = new SparseBooleanArray();
2342 collectKeys(mUidState, knownUids);
2343 collectKeys(mUidRules, knownUids);
2344
2345 fout.println("Status for all known UIDs:");
2346 fout.increaseIndent();
2347 size = knownUids.size();
2348 for (int i = 0; i < size; i++) {
2349 final int uid = knownUids.keyAt(i);
2350 fout.print("UID=");
2351 fout.print(uid);
2352
2353 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2354 fout.print(" state=");
2355 fout.print(state);
2356 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2357 fout.print(" (fg)");
2358 } else {
2359 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2360 ? " (fg svc)" : " (bg)");
2361 }
2362
2363 final int uidRules = mUidRules.get(uid, RULE_NONE);
2364 fout.print(" rules=");
2365 fout.print(uidRulesToString(uidRules));
2366 fout.println();
2367 }
2368 fout.decreaseIndent();
2369
2370 fout.println("Status for just UIDs with rules:");
2371 fout.increaseIndent();
2372 size = mUidRules.size();
2373 for (int i = 0; i < size; i++) {
2374 final int uid = mUidRules.keyAt(i);
2375 fout.print("UID=");
2376 fout.print(uid);
2377 final int uidRules = mUidRules.get(uid, RULE_NONE);
2378 fout.print(" rules=");
2379 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002380 fout.println();
2381 }
2382 fout.decreaseIndent();
2383 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002384 }
2385 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002386
2387 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002388 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2389 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002390 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002391 this, in, out, err, args, resultReceiver);
2392 }
2393
2394 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002395 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002396 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2397
Felipe Lemef0823852016-06-08 13:43:08 -07002398 synchronized (mUidRulesFirstLock) {
2399 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002400 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002401 }
2402
Felipe Lemef0823852016-06-08 13:43:08 -07002403 private boolean isUidForegroundUL(int uid) {
2404 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002405 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2406 }
2407
Felipe Lemef0823852016-06-08 13:43:08 -07002408 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002409 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002410 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002411 }
2412
Felipe Lemef0823852016-06-08 13:43:08 -07002413 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002414 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2415 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2416 }
2417
Felipe Lemef0823852016-06-08 13:43:08 -07002418 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002419 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002420 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002421 }
2422
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002423 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002424 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002425 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2426 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002427 */
Felipe Lemef0823852016-06-08 13:43:08 -07002428 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002429 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2430 try {
2431 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2432 if (oldUidState != uidState) {
2433 // state changed, push updated rules
2434 mUidState.put(uid, uidState);
2435 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2436 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2437 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2438 if (isUidIdle(uid)) {
2439 updateRuleForAppIdleUL(uid);
2440 }
2441 if (mDeviceIdleMode) {
2442 updateRuleForDeviceIdleUL(uid);
2443 }
2444 if (mRestrictPower) {
2445 updateRuleForRestrictPowerUL(uid);
2446 }
2447 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002448 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002449 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002450 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002451 } finally {
2452 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002453 }
2454 }
2455
Felipe Lemef0823852016-06-08 13:43:08 -07002456 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002457 final int index = mUidState.indexOfKey(uid);
2458 if (index >= 0) {
2459 final int oldUidState = mUidState.valueAt(index);
2460 mUidState.removeAt(index);
2461 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002462 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002463 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002464 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002465 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002466 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002467 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002468 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002469 }
Felipe Lemef0823852016-06-08 13:43:08 -07002470 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002471 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002472 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002473 }
2474 }
2475
Felipe Lemef28983d2016-03-25 12:18:23 -07002476 // adjust stats accounting based on foreground status
2477 private void updateNetworkStats(int uid, boolean uidForeground) {
2478 try {
2479 mNetworkStats.setUidForeground(uid, uidForeground);
2480 } catch (RemoteException e) {
2481 // ignored; service lives in system_server
2482 }
2483 }
2484
Felipe Lemef0823852016-06-08 13:43:08 -07002485 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002486 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002487 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002488 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002489 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002490 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002491 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002492 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002493 }
2494 }
2495
Felipe Leme011b98f2016-02-10 17:28:31 -08002496 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002497 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2498 }
2499
Felipe Lemef0823852016-06-08 13:43:08 -07002500 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002501 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2502 }
2503
Felipe Lemef0823852016-06-08 13:43:08 -07002504 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002505 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2506 try {
2507 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2508 mUidFirewallPowerSaveRules);
2509 } finally {
2510 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2511 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002512 }
2513
Felipe Lemef0823852016-06-08 13:43:08 -07002514 void updateRuleForRestrictPowerUL(int uid) {
2515 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002516 }
2517
Felipe Lemef0823852016-06-08 13:43:08 -07002518 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002519 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2520 try {
2521 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2522 mUidFirewallDozableRules);
2523 } finally {
2524 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2525 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002526 }
2527
Felipe Lemef0823852016-06-08 13:43:08 -07002528 void updateRuleForDeviceIdleUL(int uid) {
2529 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002530 }
2531
Felipe Lemef28983d2016-03-25 12:18:23 -07002532 // NOTE: since both fw_dozable and fw_powersave uses the same map
2533 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002534 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002535 SparseIntArray rules) {
2536 if (enabled) {
2537 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002538 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002539 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002540 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002541 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002542 for (int ui = users.size() - 1; ui >= 0; ui--) {
2543 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002544 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002545 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2546 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2547 int uid = UserHandle.getUid(user.id, appId);
2548 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2549 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002550 }
2551 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2552 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2553 int uid = UserHandle.getUid(user.id, appId);
2554 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2555 }
2556 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002557 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002558 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002559 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2560 }
2561 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002562 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2563 } else {
2564 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002565 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002566 }
2567
Felipe Lemef0823852016-06-08 13:43:08 -07002568 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002569 final int appId = UserHandle.getAppId(uid);
2570 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2571 }
2572
Felipe Lemef28983d2016-03-25 12:18:23 -07002573 // NOTE: since both fw_dozable and fw_powersave uses the same map
2574 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002575 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002576 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002577 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002578 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2579 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002580 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002581 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002582 }
2583 }
2584 }
2585
Felipe Lemef0823852016-06-08 13:43:08 -07002586 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002587 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2588 try {
2589 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2590 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002591
Felipe Leme873a83a2016-09-07 11:34:10 -07002592 // Fully update the app idle firewall chain.
2593 final List<UserInfo> users = mUserManager.getUsers();
2594 for (int ui = users.size() - 1; ui >= 0; ui--) {
2595 UserInfo user = users.get(ui);
2596 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2597 for (int uid : idleUids) {
2598 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2599 // quick check: if this uid doesn't have INTERNET permission, it
2600 // doesn't have network access anyway, so it is a waste to mess
2601 // with it here.
2602 if (hasInternetPermissions(uid)) {
2603 uidRules.put(uid, FIREWALL_RULE_DENY);
2604 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002605 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002606 }
2607 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002608
Felipe Lemebc853dd2016-09-08 13:26:55 -07002609 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002610 } finally {
2611 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2612 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002613 }
2614
Felipe Lemef0823852016-06-08 13:43:08 -07002615 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002616 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002617
2618 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002619 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002620 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002621 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2622 } else {
2623 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2624 }
2625 }
2626
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002627 /**
2628 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2629 * changed.
2630 */
Felipe Lemef0823852016-06-08 13:43:08 -07002631 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002632 boolean paroled = mUsageStats.isAppIdleParoleOn();
2633 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002634 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002635
2636 int ruleCount = mUidFirewallStandbyRules.size();
2637 for (int i = 0; i < ruleCount; i++) {
2638 int uid = mUidFirewallStandbyRules.keyAt(i);
2639 int oldRules = mUidRules.get(uid);
2640 if (enableChain) {
2641 // Chain wasn't enabled before and the other power-related
2642 // chains are whitelists, so we can clear the
2643 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2644 // the effective rules result in blocking network access.
2645 oldRules &= MASK_METERED_NETWORKS;
2646 } else {
2647 // Skip if it had no restrictions to begin with
2648 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2649 }
2650 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
2651 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002652 }
2653
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002654 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002655 * Update rules that might be changed by {@link #mRestrictBackground},
2656 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002657 */
Felipe Lemef0823852016-06-08 13:43:08 -07002658 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002659 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2660 try {
Felipe Leme09700462016-09-08 09:33:48 -07002661 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002662 updateRulesForRestrictPowerUL();
2663 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002664
Felipe Leme873a83a2016-09-07 11:34:10 -07002665 // If the set of restricted networks may have changed, re-evaluate those.
2666 if (restrictedNetworksChanged) {
2667 normalizePoliciesNL();
2668 updateNetworkRulesNL();
2669 }
2670 } finally {
2671 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002672 }
2673 }
2674
Felipe Leme09700462016-09-08 09:33:48 -07002675 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002676 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002677 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2678 try {
2679 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002680 updateRulesForPowerSaveUL();
2681 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2682 } finally {
2683 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2684 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002685 }
2686
Felipe Lemef0823852016-06-08 13:43:08 -07002687 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002688 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2689 try {
2690 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2691 } finally {
2692 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2693 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002694 }
2695
2696 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2697 private static final int TYPE_RESTRICT_POWER = 2;
2698 @Retention(RetentionPolicy.SOURCE)
2699 @IntDef(flag = false, value = {
2700 TYPE_RESTRICT_BACKGROUND,
2701 TYPE_RESTRICT_POWER,
2702 })
2703 public @interface RestrictType {
2704 }
2705
2706 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002707 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002708 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2709 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2710 }
2711 try {
2712 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002713
Felipe Leme873a83a2016-09-07 11:34:10 -07002714 // update rules for all installed applications
2715 final List<UserInfo> users = mUserManager.getUsers();
2716 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2717 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2718 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2719 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002720
Felipe Leme873a83a2016-09-07 11:34:10 -07002721 final int usersSize = users.size();
2722 final int appsSize = apps.size();
2723 for (int i = 0; i < usersSize; i++) {
2724 final UserInfo user = users.get(i);
2725 for (int j = 0; j < appsSize; j++) {
2726 final ApplicationInfo app = apps.get(j);
2727 final int uid = UserHandle.getUid(user.id, app.uid);
2728 switch (type) {
2729 case TYPE_RESTRICT_BACKGROUND:
2730 updateRulesForDataUsageRestrictionsUL(uid);
2731 break;
2732 case TYPE_RESTRICT_POWER:
2733 updateRulesForPowerRestrictionsUL(uid);
2734 break;
2735 default:
2736 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2737 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002738 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002739 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002740 } finally {
2741 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2742 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2743 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002744 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002745 }
2746
Felipe Lemef0823852016-06-08 13:43:08 -07002747 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002748 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002749 for (int i = 0; i < users.size(); i++) {
2750 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002751 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002752 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002753 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002754 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002755 updateRuleForAppIdleUL(uid);
2756 updateRuleForDeviceIdleUL(uid);
2757 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002758 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002759 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002760 }
2761 }
2762 }
2763
Felipe Leme70c57c22016-03-29 10:45:13 -07002764 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2765 // methods below could be merged into a isUidValidForRules() method.
2766 private boolean isUidValidForBlacklistRules(int uid) {
2767 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002768 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002769 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002770 return true;
2771 }
2772
2773 return false;
2774 }
2775
Felipe Leme70c57c22016-03-29 10:45:13 -07002776 private boolean isUidValidForWhitelistRules(int uid) {
2777 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2778 }
2779
Amith Yamasani15e472352015-04-24 19:06:07 -07002780 private boolean isUidIdle(int uid) {
2781 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2782 final int userId = UserHandle.getUserId(uid);
2783
songjinshi0655edd2016-05-18 19:55:32 +08002784 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002785 for (String packageName : packages) {
2786 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2787 return false;
2788 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002789 }
2790 }
2791 return true;
2792 }
2793
2794 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002795 * Checks if an uid has INTERNET permissions.
2796 * <p>
2797 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002798 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002799 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002800 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002801 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002802 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002803 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002804 }
2805 } catch (RemoteException e) {
2806 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002807 return true;
2808 }
2809
2810 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002811 * Clears all state - internal and external - associated with an UID.
2812 */
2813 private void onUidDeletedUL(int uid) {
2814 // First cleanup in-memory state synchronously...
2815 mUidRules.delete(uid);
2816 mUidPolicy.delete(uid);
2817 mUidFirewallStandbyRules.delete(uid);
2818 mUidFirewallDozableRules.delete(uid);
2819 mUidFirewallPowerSaveRules.delete(uid);
2820 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2821 mPowerSaveWhitelistAppIds.delete(uid);
2822 mPowerSaveTempWhitelistAppIds.delete(uid);
2823
2824 // ...then update iptables asynchronously.
2825 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2826 }
2827
2828 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002829 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002830 *
Felipe Leme781ba142016-05-09 16:24:48 -07002831 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002832 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002833 * <li>Doze mode
2834 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002835 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002836 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002837 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002838 *
2839 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002840 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002841 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002842 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002843 updateRuleForDeviceIdleUL(uid);
2844 updateRuleForAppIdleUL(uid);
2845 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002846
2847 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002848 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002849
2850 // Update firewall and internal rules for Data Saver Mode.
Felipe Leme03e95e22016-09-09 09:25:31 -07002851 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002852 }
2853
Felipe Leme70c57c22016-03-29 10:45:13 -07002854 /**
2855 * Applies network rules to bandwidth controllers based on process state and user-defined
2856 * restrictions (blacklist / whitelist).
2857 *
2858 * <p>
2859 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2860 * networks:
2861 * <ul>
2862 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2863 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2864 * also blacklisted.
2865 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2866 * no UIDs other those whitelisted will have access.
2867 * <ul>
2868 *
2869 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2870 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2871 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2872 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002873 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002874 * {@link INetworkManagementService}, but this method should also be called in events (like
2875 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2876 * following rules should also be applied:
2877 *
2878 * <ul>
2879 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2880 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2881 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2882 * {@code bw_penalty_box}.
2883 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2884 * </ul>
2885 *
2886 * <p>For optimization, the rules are only applied on user apps that have internet access
2887 * permission, since there is no need to change the {@code iptables} rule if the app does not
2888 * have permission to use the internet.
2889 *
2890 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002891 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002892 */
Felipe Lemef0823852016-06-08 13:43:08 -07002893 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07002894 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002895 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2896 return;
2897 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002898
Dianne Hackborn497175b2014-07-01 12:56:08 -07002899 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002900 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002901 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002902
Felipe Leme781ba142016-05-09 16:24:48 -07002903 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002904 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002905 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2906 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002907
Felipe Leme70c57c22016-03-29 10:45:13 -07002908 // First step: define the new rule based on user restrictions and foreground state.
2909 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002910 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2911 newRule = RULE_TEMPORARY_ALLOW_METERED;
2912 } else if (isWhitelisted) {
2913 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002914 }
2915 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002916 if (isBlacklisted) {
2917 newRule = RULE_REJECT_METERED;
2918 } else if (mRestrictBackground && isWhitelisted) {
2919 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002920 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002921 }
Felipe Leme781ba142016-05-09 16:24:48 -07002922 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002923
Felipe Lemef28983d2016-03-25 12:18:23 -07002924 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002925 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002926 + ": isForeground=" +isForeground
2927 + ", isBlacklisted=" + isBlacklisted
2928 + ", isWhitelisted=" + isWhitelisted
2929 + ", oldRule=" + uidRulesToString(oldRule)
2930 + ", newRule=" + uidRulesToString(newRule)
2931 + ", newUidRules=" + uidRulesToString(newUidRules)
2932 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002933 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002934
Felipe Leme46c4fc32016-05-04 09:21:43 -07002935 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002936 mUidRules.delete(uid);
2937 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002938 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002939 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002940
Felipe Leme70c57c22016-03-29 10:45:13 -07002941 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002942 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002943 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002944 // Temporarily whitelist foreground app, removing from blacklist if necessary
2945 // (since bw_penalty_box prevails over bw_happy_box).
2946
2947 setMeteredNetworkWhitelist(uid, true);
2948 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2949 // but ideally it should be just:
2950 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002951 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002952 setMeteredNetworkBlacklist(uid, false);
2953 }
Felipe Leme781ba142016-05-09 16:24:48 -07002954 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002955 // Remove temporary whitelist from app that is not on foreground anymore.
2956
2957 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2958 // but ideally they should be just:
2959 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2960 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002961 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002962 setMeteredNetworkWhitelist(uid, false);
2963 }
Felipe Leme781ba142016-05-09 16:24:48 -07002964 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002965 setMeteredNetworkBlacklist(uid, true);
2966 }
Felipe Leme781ba142016-05-09 16:24:48 -07002967 } else if ((newRule & RULE_REJECT_METERED) != 0
2968 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002969 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002970 setMeteredNetworkBlacklist(uid, isBlacklisted);
2971 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002972 // Since blacklist prevails over whitelist, we need to handle the special case
2973 // where app is whitelisted and blacklisted at the same time (although such
2974 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07002975 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002976 }
Felipe Leme781ba142016-05-09 16:24:48 -07002977 } else if ((newRule & RULE_ALLOW_METERED) != 0
2978 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002979 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07002980 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002981 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002982 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002983 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2984 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07002985 + ", whitelisted=" + isWhitelisted
2986 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07002987 + ", newRule=" + uidRulesToString(newUidRules)
2988 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07002989 }
Felipe Leme781ba142016-05-09 16:24:48 -07002990
2991 // Dispatch changed rule to existing listeners.
2992 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
2993 }
2994 }
2995
2996 /**
2997 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
2998 * listeners in case of change.
2999 * <p>
3000 * There are 3 power-related rules that affects whether an app has background access on
3001 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3002 * restriction, it's added to the equivalent firewall chain:
3003 * <ul>
3004 * <li>App is idle: {@code fw_standby} firewall chain.
3005 * <li>Device is idle: {@code fw_dozable} firewall chain.
3006 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3007 * </ul>
3008 * <p>
3009 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3010 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3011 * <p>
3012 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3013 */
Felipe Lemef0823852016-06-08 13:43:08 -07003014 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003015 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3016
3017 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
3018
3019 if (newUidRules == RULE_NONE) {
3020 mUidRules.delete(uid);
3021 } else {
3022 mUidRules.put(uid, newUidRules);
3023 }
3024 }
3025
3026 /**
3027 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3028 *
3029 * @param uid the uid of the app to update rules for
3030 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3031 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3032 *
3033 * @return the new computed rules for the uid
3034 */
3035 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003036 if (!isUidValidForBlacklistRules(uid)) {
3037 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003038 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003039 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003040
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003041 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003042 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003043 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003044
Felipe Lemef0823852016-06-08 13:43:08 -07003045 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003046 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3047 int newRule = RULE_NONE;
3048
3049 // First step: define the new rule based on user restrictions and foreground state.
3050
3051 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3052 // by considering the foreground and non-foreground states.
3053 if (isForeground) {
3054 if (restrictMode) {
3055 newRule = RULE_ALLOW_ALL;
3056 }
3057 } else if (restrictMode) {
3058 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3059 }
3060
3061 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3062
3063 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003064 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003065 + ", isIdle: " + isIdle
3066 + ", mRestrictPower: " + mRestrictPower
3067 + ", mDeviceIdleMode: " + mDeviceIdleMode
3068 + ", isForeground=" + isForeground
3069 + ", isWhitelisted=" + isWhitelisted
3070 + ", oldRule=" + uidRulesToString(oldRule)
3071 + ", newRule=" + uidRulesToString(newRule)
3072 + ", newUidRules=" + uidRulesToString(newUidRules)
3073 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3074 }
3075
Felipe Leme781ba142016-05-09 16:24:48 -07003076 // Second step: notify listeners if state changed.
3077 if (newRule != oldRule) {
3078 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003079 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003080 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003081 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3082 } else {
3083 // All scenarios should have been covered above
3084 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3085 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003086 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003087 + ", newRule=" + uidRulesToString(newUidRules)
3088 + ", oldRule=" + uidRulesToString(oldUidRules));
3089 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003090 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003091 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003092
3093 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003094 }
3095
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003096 private class AppIdleStateChangeListener
3097 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3098
3099 @Override
3100 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3101 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003102 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3103 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003104 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003105 synchronized (mUidRulesFirstLock) {
3106 updateRuleForAppIdleUL(uid);
3107 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003108 }
3109 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003110 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003111 }
3112
3113 @Override
3114 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003115 synchronized (mUidRulesFirstLock) {
3116 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003117 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003118 }
3119 }
3120
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003121 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3122 if (listener != null) {
3123 try {
3124 listener.onUidRulesChanged(uid, uidRules);
3125 } catch (RemoteException ignored) {
3126 }
3127 }
3128 }
3129
3130 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3131 String[] meteredIfaces) {
3132 if (listener != null) {
3133 try {
3134 listener.onMeteredIfacesChanged(meteredIfaces);
3135 } catch (RemoteException ignored) {
3136 }
3137 }
3138 }
3139
3140 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3141 boolean restrictBackground) {
3142 if (listener != null) {
3143 try {
3144 listener.onRestrictBackgroundChanged(restrictBackground);
3145 } catch (RemoteException ignored) {
3146 }
3147 }
3148 }
3149
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003150 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3151 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003152 if (listener != null) {
3153 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003154 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003155 } catch (RemoteException ignored) {
3156 }
3157 }
3158 }
3159
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003160 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003161 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003162 public boolean handleMessage(Message msg) {
3163 switch (msg.what) {
3164 case MSG_RULES_CHANGED: {
3165 final int uid = msg.arg1;
3166 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003167 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003168 final int length = mListeners.beginBroadcast();
3169 for (int i = 0; i < length; i++) {
3170 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003171 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003172 }
3173 mListeners.finishBroadcast();
3174 return true;
3175 }
3176 case MSG_METERED_IFACES_CHANGED: {
3177 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003178 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003179 final int length = mListeners.beginBroadcast();
3180 for (int i = 0; i < length; i++) {
3181 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003182 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003183 }
3184 mListeners.finishBroadcast();
3185 return true;
3186 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003187 case MSG_LIMIT_REACHED: {
3188 final String iface = (String) msg.obj;
3189
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003190 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003191 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003192 if (mMeteredIfaces.contains(iface)) {
3193 try {
3194 // force stats update to make sure we have
3195 // numbers that caused alert to trigger.
3196 mNetworkStats.forceUpdate();
3197 } catch (RemoteException e) {
3198 // ignored; service lives in system_server
3199 }
3200
Felipe Lemef0823852016-06-08 13:43:08 -07003201 updateNetworkEnabledNL();
3202 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003203 }
3204 }
3205 return true;
3206 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003207 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3208 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003209 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003210 final int length = mListeners.beginBroadcast();
3211 for (int i = 0; i < length; i++) {
3212 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003213 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003214 }
3215 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003216 final Intent intent =
3217 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3218 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3219 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3220 return true;
3221 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003222 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003223 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003224 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003225 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003226 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003227 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003228 final int length = mListeners.beginBroadcast();
3229 for (int i = 0; i < length; i++) {
3230 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003231 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003232 }
3233 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003234 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3235 if (notifyApp.booleanValue()) {
3236 broadcastRestrictBackgroundChanged(uid, notifyApp);
3237 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003238 return true;
3239 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003240 case MSG_ADVISE_PERSIST_THRESHOLD: {
3241 final long lowestRule = (Long) msg.obj;
3242 try {
3243 // make sure stats are recorded frequently enough; we aim
3244 // for 2MB threshold for 2GB/month rules.
3245 final long persistThreshold = lowestRule / 1000;
3246 mNetworkStats.advisePersistThreshold(persistThreshold);
3247 } catch (RemoteException e) {
3248 // ignored; service lives in system_server
3249 }
3250 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003251 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003252 case MSG_UPDATE_INTERFACE_QUOTA: {
3253 removeInterfaceQuota((String) msg.obj);
3254 // int params need to be stitched back into a long
3255 setInterfaceQuota((String) msg.obj,
3256 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3257 return true;
3258 }
3259 case MSG_REMOVE_INTERFACE_QUOTA: {
3260 removeInterfaceQuota((String) msg.obj);
3261 return true;
3262 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003263 case MSG_SET_FIREWALL_RULES: {
3264 final int chain = msg.arg1;
3265 final int toggle = msg.arg2;
3266 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3267 if (uidRules != null) {
3268 setUidFirewallRules(chain, uidRules);
3269 }
3270 if (toggle != CHAIN_TOGGLE_NONE) {
3271 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3272 }
3273 return true;
3274 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003275 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3276 resetUidFirewallRules(msg.arg1);
3277 return true;
3278 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003279 default: {
3280 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003281 }
3282 }
3283 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003284
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003285 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003286
Felipe Leme57e3d312016-08-23 14:42:52 -07003287 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3288 final PackageManager pm = mContext.getPackageManager();
3289 final String[] packages = pm.getPackagesForUid(uid);
3290 if (packages != null) {
3291 final int userId = UserHandle.getUserId(uid);
3292 for (String packageName : packages) {
3293 final Intent intent =
3294 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3295 intent.setPackage(packageName);
3296 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3297 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3298 }
3299 }
3300 }
3301
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003302 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003303 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003304 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003305 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003306 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003307 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003308 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003309 }
3310 }
3311
3312 private void removeInterfaceQuota(String iface) {
3313 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003314 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003315 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003316 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003317 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003318 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003319 }
3320 }
3321
Felipe Leme70c57c22016-03-29 10:45:13 -07003322 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3323 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003324 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003325 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003326 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003327 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3328 } catch (RemoteException e) {
3329 // ignored; service lives in system_server
3330 }
3331 }
3332
3333 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3334 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3335 try {
3336 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3337 } catch (IllegalStateException e) {
3338 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003339 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003340 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003341 }
3342 }
3343
Felipe Lemebc853dd2016-09-08 13:26:55 -07003344 private static final int CHAIN_TOGGLE_NONE = 0;
3345 private static final int CHAIN_TOGGLE_ENABLE = 1;
3346 private static final int CHAIN_TOGGLE_DISABLE = 2;
3347 @Retention(RetentionPolicy.SOURCE)
3348 @IntDef(flag = false, value = {
3349 CHAIN_TOGGLE_NONE,
3350 CHAIN_TOGGLE_ENABLE,
3351 CHAIN_TOGGLE_DISABLE
3352 })
3353 public @interface ChainToggleType {
3354 }
3355
3356 /**
3357 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3358 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3359 *
3360 * @param chain firewall chain.
3361 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3362 * @param toggle whether the chain should be enabled, disabled, or not changed.
3363 */
3364 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3365 @ChainToggleType int toggle) {
3366 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3367 }
3368
Amith Yamasani15e472352015-04-24 19:06:07 -07003369 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003370 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3371 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3372 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003373 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003374 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003375 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003376 int size = uidRules.size();
3377 int[] uids = new int[size];
3378 int[] rules = new int[size];
3379 for(int index = size - 1; index >= 0; --index) {
3380 uids[index] = uidRules.keyAt(index);
3381 rules[index] = uidRules.valueAt(index);
3382 }
3383 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003384 } catch (IllegalStateException e) {
3385 Log.wtf(TAG, "problem setting firewall uid rules", e);
3386 } catch (RemoteException e) {
3387 // ignored; service lives in system_server
3388 }
3389 }
3390
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003391 /**
3392 * Add or remove a uid to the firewall blacklist for all network ifaces.
3393 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003394 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003395 if (chain == FIREWALL_CHAIN_DOZABLE) {
3396 mUidFirewallDozableRules.put(uid, rule);
3397 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3398 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003399 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3400 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003401 }
3402
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003403 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003404 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003405 } catch (IllegalStateException e) {
3406 Log.wtf(TAG, "problem setting firewall uid rules", e);
3407 } catch (RemoteException e) {
3408 // ignored; service lives in system_server
3409 }
3410 }
3411
3412 /**
3413 * Add or remove a uid to the firewall blacklist for all network ifaces.
3414 */
Felipe Lemef0823852016-06-08 13:43:08 -07003415 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003416 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3417 mFirewallChainStates.get(chain) == enable) {
3418 // All is the same, nothing to do.
3419 return;
3420 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003421 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003422 try {
3423 mNetworkManager.setFirewallChainEnabled(chain, enable);
3424 } catch (IllegalStateException e) {
3425 Log.wtf(TAG, "problem enable firewall chain", e);
3426 } catch (RemoteException e) {
3427 // ignored; service lives in system_server
3428 }
3429 }
3430
Felipe Leme03e95e22016-09-09 09:25:31 -07003431 /**
3432 * Resets all firewall rules associated with an UID.
3433 */
3434 private void resetUidFirewallRules(int uid) {
3435 try {
3436 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3437 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3438 mNetworkManager
3439 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3440 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3441 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3442 } catch (IllegalStateException e) {
3443 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3444 } catch (RemoteException e) {
3445 // ignored; service lives in system_server
3446 }
3447 }
3448
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003449 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3450 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003451 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003452 } catch (RuntimeException e) {
3453 Slog.w(TAG, "problem reading network stats: " + e);
3454 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003455 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003456 // ignored; service lives in system_server
3457 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003458 }
3459 }
3460
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003461 private boolean isBandwidthControlEnabled() {
3462 final long token = Binder.clearCallingIdentity();
3463 try {
3464 return mNetworkManager.isBandwidthControlEnabled();
3465 } catch (RemoteException e) {
3466 // ignored; service lives in system_server
3467 return false;
3468 } finally {
3469 Binder.restoreCallingIdentity(token);
3470 }
3471 }
3472
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003473 /**
3474 * Try refreshing {@link #mTime} when stale.
3475 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003476 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003477 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003478 mTime.forceRefresh();
3479 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003480 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003481
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003482 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003483 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3484 }
3485
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003486 private static Intent buildAllowBackgroundDataIntent() {
3487 return new Intent(ACTION_ALLOW_BACKGROUND);
3488 }
3489
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003490 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3491 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3492 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3493 return intent;
3494 }
3495
Wei Liu546cb772016-07-21 16:19:01 -07003496 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003497 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003498 intent.setComponent(ComponentName.unflattenFromString(
3499 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003500 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3501 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3502 return intent;
3503 }
3504
Wei Liu546cb772016-07-21 16:19:01 -07003505 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003506 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003507 intent.setComponent(ComponentName.unflattenFromString(
3508 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003509 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3510 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3511 return intent;
3512 }
3513
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003514 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003515 public void addIdleHandler(IdleHandler handler) {
3516 mHandler.getLooper().getQueue().addIdleHandler(handler);
3517 }
3518
Jeff Sharkey1b861272011-05-22 00:34:52 -07003519 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3520 final int size = source.size();
3521 for (int i = 0; i < size; i++) {
3522 target.put(source.keyAt(i), true);
3523 }
3524 }
3525
Stuart Scottf1fb3972015-04-02 18:00:02 -07003526 @Override
3527 public void factoryReset(String subscriber) {
3528 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3529
Stuart Scotte3e314d2015-04-20 14:07:45 -07003530 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3531 return;
3532 }
3533
Stuart Scottf1fb3972015-04-02 18:00:02 -07003534 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003535 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003536 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3537 for (NetworkPolicy policy : policies) {
3538 if (policy.template.equals(template)) {
3539 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3540 policy.inferred = false;
3541 policy.clearSnooze();
3542 }
3543 }
3544 setNetworkPolicies(policies);
3545
3546 // Turn restrict background data off
3547 setRestrictBackground(false);
3548
Stuart Scotte3e314d2015-04-20 14:07:45 -07003549 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3550 // Remove app's "restrict background data" flag
3551 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3552 setUidPolicy(uid, POLICY_NONE);
3553 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003554 }
3555 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003556
Felipe Lemed17fda42016-04-29 11:12:45 -07003557 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3558
3559 @Override
3560 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003561 synchronized (mUidRulesFirstLock) {
3562 boolean changed = removeUserStateUL(userId, false);
3563 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003564 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003565 synchronized (mNetworkPoliciesSecondLock) {
3566 writePolicyAL();
3567 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003568 }
3569 }
3570 }
3571 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003572}