blob: 085de43f43e8072abdd5783a4d3a77dd9d01e77d [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
54import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
55import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070058import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070059import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Leme46c4fc32016-05-04 09:21:43 -070060import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070061import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
62import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
64import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070065import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080066import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070067import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
68import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
69import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
70import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
71import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
72import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
73import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080075
Jeff Sharkey854b2b12012-04-13 16:03:40 -070076import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070077import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070078import static com.android.internal.util.XmlUtils.readBooleanAttribute;
79import static com.android.internal.util.XmlUtils.readIntAttribute;
80import static com.android.internal.util.XmlUtils.readLongAttribute;
81import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
82import static com.android.internal.util.XmlUtils.writeIntAttribute;
83import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700121import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
128import android.net.wifi.WifiInfo;
129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700136import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700137import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700140import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700141import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600142import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143import android.os.ServiceManager;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700144import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700145import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700146import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800147import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700148import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400149import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700150import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700151import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700152import android.util.ArrayMap;
153import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700154import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700155import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700156import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700157import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700158import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700159import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700160import android.util.SparseBooleanArray;
161import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700162import android.util.TrustedTime;
163import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700164
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700166import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800167import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800168import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800169import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700171import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700172import com.android.server.DeviceIdleController;
173import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700174import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800175import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600176
177import libcore.io.IoUtils;
178
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700179import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180
181import org.xmlpull.v1.XmlPullParser;
182import org.xmlpull.v1.XmlPullParserException;
183import org.xmlpull.v1.XmlSerializer;
184
185import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700186import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187import java.io.FileInputStream;
188import java.io.FileNotFoundException;
189import java.io.FileOutputStream;
190import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700191import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700192import java.lang.annotation.Retention;
193import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100194import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195import java.util.ArrayList;
196import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700197import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700199/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700200 * Service that maintains low-level network policy rules, using
201 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700202 * <p>
203 * Derives active rules by combining a given policy with other system status,
204 * and delivers to listeners, such as {@link ConnectivityManager}, for
205 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700206 *
207 * <p>
208 * This class uses 2-3 locks to synchronize state:
209 * <ul>
210 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
211 * rules).
212 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
213 * as network policies).
214 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
215 * must be held.
216 * </ul>
217 *
218 * <p>
219 * As such, methods that require synchronization have the following prefixes:
220 * <ul>
221 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
222 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
223 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
224 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
225 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700226 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700227public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800228 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700229 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700230 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700231
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700232 private static final int VERSION_INIT = 1;
233 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700234 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800235 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800236 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800237 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700238 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700239 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700240 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700241 private static final int VERSION_SWITCH_UID = 10;
242 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700243
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800244 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700245 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800246 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700247 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800248 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700249 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700250
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251 private static final String TAG_POLICY_LIST = "policy-list";
252 private static final String TAG_NETWORK_POLICY = "network-policy";
253 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700254 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800255 private static final String TAG_WHITELIST = "whitelist";
256 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800257 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700258
259 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700260 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
262 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700263 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700264 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800265 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private static final String ATTR_WARNING_BYTES = "warningBytes";
267 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700268 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800269 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
270 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800271 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700272 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700273 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700274 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700275 private static final String ATTR_POLICY = "policy";
276
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800278 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800279 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800280 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700281
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
283
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700284 private static final int MSG_RULES_CHANGED = 1;
285 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800286 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800287 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700288 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Felipe Leme9778f762016-01-27 14:46:39 -0800289 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700290 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
291 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700292 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700293
Jeff Sharkey75279902011-05-24 18:39:45 -0700294 private final Context mContext;
295 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700296 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700298 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700299 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700300 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700301
302 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700303 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700304 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700305 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700306
Felipe Lemef0823852016-06-08 13:43:08 -0700307 // See main javadoc for instructions on how to use these locks.
308 final Object mUidRulesFirstLock = new Object();
309 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700310
Felipe Lemef0823852016-06-08 13:43:08 -0700311 @GuardedBy("allLocks") volatile boolean mSystemReady;
312
Felipe Lemef0823852016-06-08 13:43:08 -0700313 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
314 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
315 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700316
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700317 private final boolean mSuppressDefaultPolicy;
318
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700319 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800320 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700321 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800322 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700323
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700324 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700325 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700326 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700327 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700328
Felipe Lemef0823852016-06-08 13:43:08 -0700329 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700330 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700331 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700332 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700333 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800334 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700335
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700336 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700337 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700338 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
339
Jeff Sharkey32566012014-12-02 18:30:14 -0800340 /**
341 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700342 * in power save mode, except device idle (doze) still applies.
343 * TODO: An int array might be sufficient
344 */
Felipe Lemef0823852016-06-08 13:43:08 -0700345 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700346 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
347
348 /**
349 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800350 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700351 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 */
Felipe Lemef0823852016-06-08 13:43:08 -0700353 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700354 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700355
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700357 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
358
Felipe Lemeb85a6372016-01-14 16:16:16 -0800359 /**
360 * UIDs that have been white-listed to avoid restricted background.
361 */
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800363 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
364
Felipe Lemea9505cc2016-02-26 10:28:41 -0800365 /**
366 * UIDs that have been initially white-listed by system to avoid restricted background.
367 */
Felipe Lemef0823852016-06-08 13:43:08 -0700368 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800369 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
370 new SparseBooleanArray();
371
372 /**
373 * UIDs that have been initially white-listed by system to avoid restricted background,
374 * but later revoked by user.
375 */
Felipe Lemef0823852016-06-08 13:43:08 -0700376 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800377 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
378 new SparseBooleanArray();
379
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700380 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700383 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800385 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700386
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700387 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700389 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700390
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700391 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800393 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700394
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600395 /** Higher priority listener before general event dispatch */
396 private INetworkPolicyListener mConnectivityListener;
397
Jeff Sharkey32566012014-12-02 18:30:14 -0800398 private final RemoteCallbackList<INetworkPolicyListener>
399 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700400
Dianne Hackborn497175b2014-07-01 12:56:08 -0700401 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
Felipe Lemef0823852016-06-08 13:43:08 -0700403 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700405
Svet Ganov16a16892015-04-16 10:32:04 -0700406 private final AppOpsManager mAppOps;
407
Felipe Lemeb85a6372016-01-14 16:16:16 -0800408 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800409 private final IPackageManager mIPm;
410
Felipe Lemeb85a6372016-01-14 16:16:16 -0800411
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700412 // TODO: keep whitelist of system-critical services that should never have
413 // rules enforced, such as system, phone, and radio UIDs.
414
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700415 // TODO: migrate notifications to SystemUI
416
Jeff Sharkey75279902011-05-24 18:39:45 -0700417 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700418 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
419 this(context, activityManager, networkStats, networkManagement,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700420 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700421 }
422
423 private static File getSystemDir() {
424 return new File(Environment.getDataDirectory(), "system");
425 }
426
427 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700428 INetworkStatsService networkStats, INetworkManagementService networkManagement,
429 TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700430 mContext = checkNotNull(context, "missing context");
431 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700432 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700433 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700434 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700435 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700437 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800438 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439
Amith Yamasani450a16b2013-09-18 16:28:50 -0700440 HandlerThread thread = new HandlerThread(TAG);
441 thread.start();
442 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700444 mSuppressDefaultPolicy = suppressDefaultPolicy;
445
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700446 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700447
448 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800449
450 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700451
452 // Expose private service for system components to use.
453 LocalServices.addService(NetworkPolicyManagerInternal.class,
454 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700455 }
456
457 public void bindConnectivityManager(IConnectivityManager connManager) {
458 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700459 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700460
Jeff Sharkey497e4432011-06-14 17:27:29 -0700461 public void bindNotificationManager(INotificationManager notifManager) {
462 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
463 }
464
Felipe Lemef0823852016-06-08 13:43:08 -0700465 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700466 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700467 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
468 mPowerSaveWhitelistExceptIdleAppIds.clear();
469 if (whitelist != null) {
470 for (int uid : whitelist) {
471 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
472 }
473 }
474 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700475 mPowerSaveWhitelistAppIds.clear();
476 if (whitelist != null) {
477 for (int uid : whitelist) {
478 mPowerSaveWhitelistAppIds.put(uid, true);
479 }
480 }
481 } catch (RemoteException e) {
482 }
483 }
484
Felipe Lemea9505cc2016-02-26 10:28:41 -0800485 /**
486 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
487 * revoke the whitelist.
488 *
489 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
490 */
Felipe Lemef0823852016-06-08 13:43:08 -0700491 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800492 final List<UserInfo> users = mUserManager.getUsers();
493 final int numberUsers = users.size();
494
Felipe Lemea110eec2016-04-29 09:58:06 -0700495 boolean changed = false;
496 for (int i = 0; i < numberUsers; i++) {
497 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700498 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700499 }
500 return changed;
501 }
502
Felipe Lemef0823852016-06-08 13:43:08 -0700503 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700504 final SystemConfig sysConfig = SystemConfig.getInstance();
505 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800506 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
507 boolean changed = false;
508 for (int i = 0; i < allowDataUsage.size(); i++) {
509 final String pkg = allowDataUsage.valueAt(i);
510 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700511 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
512 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800513 final ApplicationInfo app;
514 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700515 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800516 } catch (PackageManager.NameNotFoundException e) {
517 // Should not happen
518 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
519 continue;
520 }
521 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700522 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800523 continue;
524 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700525 final int uid = UserHandle.getUid(userId, app.uid);
526 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
527 if (LOGD)
528 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
529 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800530 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700531 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
532 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
533 + userId + ") to restrict background whitelist");
534 mRestrictBackgroundWhitelistUids.append(uid, true);
535 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 }
537 }
538 return changed;
539 }
540
Felipe Lemef0823852016-06-08 13:43:08 -0700541 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700542 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700543 // Clear the states of the current whitelist
544 final int N = mPowerSaveTempWhitelistAppIds.size();
545 for (int i = 0; i < N; i++) {
546 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
547 }
548 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700549 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700550 if (whitelist != null) {
551 for (int uid : whitelist) {
552 mPowerSaveTempWhitelistAppIds.put(uid, true);
553 }
554 }
555 } catch (RemoteException e) {
556 }
557 }
558
Amith Yamasani06f08062015-06-12 13:23:33 -0700559 /**
560 * Remove unnecessary entries in the temp whitelist
561 */
Felipe Lemef0823852016-06-08 13:43:08 -0700562 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700563 final int N = mPowerSaveTempWhitelistAppIds.size();
564 for (int i = N - 1; i >= 0; i--) {
565 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
566 mPowerSaveTempWhitelistAppIds.removeAt(i);
567 }
568 }
569 }
570
Jeff Sharkeya4620792011-05-20 15:29:23 -0700571 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700572 if (!isBandwidthControlEnabled()) {
573 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
574 return;
575 }
576
Amith Yamasani15e472352015-04-24 19:06:07 -0700577 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
578
Felipe Lemeb85a6372016-01-14 16:16:16 -0800579 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
580
Felipe Lemef0823852016-06-08 13:43:08 -0700581 synchronized (mUidRulesFirstLock) {
582 synchronized (mNetworkPoliciesSecondLock) {
583 updatePowerSaveWhitelistUL();
584 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
585 mPowerManagerInternal.registerLowPowerModeObserver(
586 new PowerManagerInternal.LowPowerModeListener() {
587 @Override
588 public void onLowPowerModeChanged(boolean enabled) {
589 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
590 synchronized (mUidRulesFirstLock) {
591 if (mRestrictPower != enabled) {
592 mRestrictPower = enabled;
593 updateRulesForRestrictPowerUL();
594 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700595 }
596 }
Felipe Lemef0823852016-06-08 13:43:08 -0700597 });
598 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
599
600 mSystemReady = true;
601
602 // read policy from disk
603 readPolicyAL();
604
605 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
606 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700607 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700608
Felipe Lemef0823852016-06-08 13:43:08 -0700609 setRestrictBackgroundUL(mRestrictBackground);
610 updateRulesForGlobalChangeAL(false);
611 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800612 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700613 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700614
Jeff Sharkeya4620792011-05-20 15:29:23 -0700615 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700616 mActivityManager.registerUidObserver(mUidObserver,
617 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700618 mNetworkManager.registerObserver(mAlertObserver);
619 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700620 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700621 }
622
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700623 // listen for changes to power save whitelist
624 final IntentFilter whitelistFilter = new IntentFilter(
625 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
626 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
627
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700628 DeviceIdleController.LocalService deviceIdleService
629 = LocalServices.getService(DeviceIdleController.LocalService.class);
630 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
631
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700632 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900633 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700634 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
635
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700636 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700637 final IntentFilter packageFilter = new IntentFilter();
638 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700639 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700640 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700641
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700642 // listen for UID changes to update policy
643 mContext.registerReceiver(
644 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
645
646 // listen for user changes to update policy
647 final IntentFilter userFilter = new IntentFilter();
648 userFilter.addAction(ACTION_USER_ADDED);
649 userFilter.addAction(ACTION_USER_REMOVED);
650 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
651
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700652 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700653 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
654 mContext.registerReceiver(
655 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
656
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700657 // listen for restrict background changes from notifications
658 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
659 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
660
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800661 // listen for snooze warning from notifications
662 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
663 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
664 MANAGE_NETWORK_POLICY, mHandler);
665
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700666 // listen for configured wifi networks to be removed
667 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700668 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700669
670 // listen for wifi state changes to catch metered hint
671 final IntentFilter wifiStateFilter = new IntentFilter(
672 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700673 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700674
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700675 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -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 Lemef0823852016-06-08 13:43:08 -0700681 synchronized (mUidRulesFirstLock) {
682 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700683 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700684 }
685
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700686 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700687 synchronized (mUidRulesFirstLock) {
688 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700689 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700690 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700691
692 @Override public void onUidActive(int uid) throws RemoteException {
693 }
694
695 @Override public void onUidIdle(int uid) throws RemoteException {
696 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700697 };
698
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700699 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700700 @Override
701 public void onReceive(Context context, Intent intent) {
702 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700703 synchronized (mUidRulesFirstLock) {
704 updatePowerSaveWhitelistUL();
705 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700706 }
707 }
708 };
709
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700710 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
711 @Override
712 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700713 synchronized (mUidRulesFirstLock) {
714 updatePowerSaveTempWhitelistUL();
715 updateRulesForTempWhitelistChangeUL();
716 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700717 }
718 }
719 };
720
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700721 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700722 @Override
723 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700724 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700725
726 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700727 final int uid = intent.getIntExtra(EXTRA_UID, -1);
728 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700729
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700730 if (ACTION_PACKAGE_ADDED.equals(action)) {
731 // update rules for UID, since it might be subject to
732 // global background data policy
733 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700734 synchronized (mUidRulesFirstLock) {
735 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700736 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700737 }
738 }
739 };
740
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700741 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700742 @Override
743 public void onReceive(Context context, Intent intent) {
744 // on background handler thread, and UID_REMOVED is protected
745
746 final int uid = intent.getIntExtra(EXTRA_UID, -1);
747 if (uid == -1) return;
748
749 // remove any policy and update rules to clean up
750 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700751 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700752 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700753 updateRestrictionRulesForUidUL(uid);
754 synchronized (mNetworkPoliciesSecondLock) {
755 writePolicyAL();
756 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700757 }
758 }
759 };
760
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700761 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700762 @Override
763 public void onReceive(Context context, Intent intent) {
764 // on background handler thread, and USER_ADDED and USER_REMOVED
765 // broadcasts are protected
766
767 final String action = intent.getAction();
768 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
769 if (userId == -1) return;
770
Amith Yamasani15e472352015-04-24 19:06:07 -0700771 switch (action) {
772 case ACTION_USER_REMOVED:
773 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700774 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800775 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700776 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700777 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700778 if (action == ACTION_USER_ADDED) {
779 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700780 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700781 }
782 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700783 synchronized (mNetworkPoliciesSecondLock) {
784 updateRulesForGlobalChangeAL(true);
785 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700786 }
787 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700788 }
789 }
790 };
791
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700792 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700793 * Receiver that watches for {@link INetworkStatsService} updates, which we
794 * use to check against {@link NetworkPolicy#warningBytes}.
795 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700796 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700797 @Override
798 public void onReceive(Context context, Intent intent) {
799 // on background handler thread, and verified
800 // READ_NETWORK_USAGE_HISTORY permission above.
801
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800802 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700803 synchronized (mNetworkPoliciesSecondLock) {
804 updateNetworkEnabledNL();
805 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700806 }
807 }
808 };
809
810 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700811 * Receiver that watches for {@link Notification} control of
812 * {@link #mRestrictBackground}.
813 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700814 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700815 @Override
816 public void onReceive(Context context, Intent intent) {
817 // on background handler thread, and verified MANAGE_NETWORK_POLICY
818 // permission above.
819
820 setRestrictBackground(false);
821 }
822 };
823
824 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800825 * Receiver that watches for {@link Notification} control of
826 * {@link NetworkPolicy#lastWarningSnooze}.
827 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700828 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800829 @Override
830 public void onReceive(Context context, Intent intent) {
831 // on background handler thread, and verified MANAGE_NETWORK_POLICY
832 // permission above.
833
834 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
835 performSnooze(template, TYPE_WARNING);
836 }
837 };
838
839 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700840 * Receiver that watches for {@link WifiConfiguration} to be changed.
841 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700842 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700843 @Override
844 public void onReceive(Context context, Intent intent) {
845 // on background handler thread, and verified CONNECTIVITY_INTERNAL
846 // permission above.
847
848 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
849 if (reason == CHANGE_REASON_REMOVED) {
850 final WifiConfiguration config = intent.getParcelableExtra(
851 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700852 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800853 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700854 synchronized (mUidRulesFirstLock) {
855 synchronized (mNetworkPoliciesSecondLock) {
856 if (mNetworkPolicy.containsKey(template)) {
857 mNetworkPolicy.remove(template);
858 writePolicyAL();
859 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700860 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700861 }
862 }
863 }
864 }
865 };
866
867 /**
868 * Receiver that watches {@link WifiInfo} state changes to infer metered
869 * state. Ignores hints when policy is user-defined.
870 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700871 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700872 @Override
873 public void onReceive(Context context, Intent intent) {
874 // on background handler thread, and verified CONNECTIVITY_INTERNAL
875 // permission above.
876
877 // ignore when not connected
878 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
879 if (!netInfo.isConnected()) return;
880
881 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
882 final boolean meteredHint = info.getMeteredHint();
883
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800884 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700885 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700886 NetworkPolicy policy = mNetworkPolicy.get(template);
887 if (policy == null && meteredHint) {
888 // policy doesn't exist, and AP is hinting that it's
889 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800890 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700891 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700892
893 } else if (policy != null && policy.inferred) {
894 // policy exists, and was inferred: update its current
895 // metered state.
896 policy.metered = meteredHint;
897
898 // since this is inferred for each wifi session, just update
899 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700900 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700901 }
902 }
903 }
904 };
905
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800906 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
907 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
908 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
909 metered, true);
910 }
911
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700912 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700913 * Observer that watches for {@link INetworkManagementService} alerts.
914 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700915 final private INetworkManagementEventObserver mAlertObserver
916 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700917 @Override
918 public void limitReached(String limitName, String iface) {
919 // only someone like NMS should be calling us
920 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
921
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800922 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
923 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700924 }
925 }
926 };
927
928 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700929 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
930 * to show visible notifications as needed.
931 */
Felipe Lemef0823852016-06-08 13:43:08 -0700932 void updateNotificationsNL() {
933 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700934
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700935 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700936 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700937 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938
939 // TODO: when switching to kernel notifications, compute next future
940 // cycle boundary to recompute notifications.
941
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700942 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800943 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700944 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
945 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700946 // ignore policies that aren't relevant to user
947 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700948 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700949
Jeff Sharkey497e4432011-06-14 17:27:29 -0700950 final long start = computeLastCycleBoundary(currentTime, policy);
951 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700952 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700953
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700954 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800955 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700956 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
957 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700958 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700959 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700960 }
961
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700963 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700964
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800965 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700966 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700967 }
968 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700969 }
970
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700971 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700972 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
973 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700974 if (!mActiveNotifs.contains(tag)) {
975 cancelNotification(tag);
976 }
977 }
978 }
979
980 /**
981 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700982 * current device state, such as when
983 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
984 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 */
986 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800987 if (template.isMatchRuleMobile()) {
988 final TelephonyManager tele = TelephonyManager.from(mContext);
989 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700990
Jeff Sharkey32566012014-12-02 18:30:14 -0800991 // Mobile template is relevant when any active subscriber matches
992 final int[] subIds = sub.getActiveSubscriptionIdList();
993 for (int subId : subIds) {
994 final String subscriberId = tele.getSubscriberId(subId);
995 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700996 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800997 if (template.matches(probeIdent)) {
998 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700999 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001000 }
1001 return false;
1002 } else {
1003 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001004 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001005 }
1006
1007 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001008 * Notify that given {@link NetworkTemplate} is over
1009 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1010 */
Felipe Lemef0823852016-06-08 13:43:08 -07001011 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001012 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001013 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001014 mOverLimitNotified.add(template);
1015 }
1016 }
1017
Felipe Lemef0823852016-06-08 13:43:08 -07001018 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 mOverLimitNotified.remove(template);
1020 }
1021
1022 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 * Build unique tag that identifies an active {@link NetworkPolicy}
1024 * notification of a specific type, like {@link #TYPE_LIMIT}.
1025 */
1026 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001027 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001028 }
1029
1030 /**
1031 * Show notification for combined {@link NetworkPolicy} and specific type,
1032 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1033 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001035 final String tag = buildNotificationTag(policy, type);
1036 final Notification.Builder builder = new Notification.Builder(mContext);
1037 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001038 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001039 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001040 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001041
1042 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001043 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001044 switch (type) {
1045 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001047 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001049 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001050 builder.setTicker(title);
1051 builder.setContentTitle(title);
1052 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001053
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001054 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1055 builder.setDeleteIntent(PendingIntent.getBroadcast(
1056 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1057
Wei Liu546cb772016-07-21 16:19:01 -07001058 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001059 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001060 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1061
Jeff Sharkey497e4432011-06-14 17:27:29 -07001062 break;
1063 }
1064 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001065 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066
1067 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001068 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001069 switch (policy.template.getMatchRule()) {
1070 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001073 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001079 case MATCH_WIFI:
1080 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001081 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 break;
1083 default:
1084 title = null;
1085 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 }
1087
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001088 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001089 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001090 builder.setTicker(title);
1091 builder.setContentTitle(title);
1092 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001093
Wei Liu546cb772016-07-21 16:19:01 -07001094 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 builder.setContentIntent(PendingIntent.getActivity(
1096 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1097 break;
1098 }
1099 case TYPE_LIMIT_SNOOZED: {
1100 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001101 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 Formatter.formatFileSize(mContext, overBytes));
1103
1104 final CharSequence title;
1105 switch (policy.template.getMatchRule()) {
1106 case MATCH_MOBILE_3G_LOWER:
1107 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1108 break;
1109 case MATCH_MOBILE_4G:
1110 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1111 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001112 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001113 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1114 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 case MATCH_WIFI:
1116 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1117 break;
1118 default:
1119 title = null;
1120 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001121 }
1122
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001123 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001124 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 builder.setTicker(title);
1126 builder.setContentTitle(title);
1127 builder.setContentText(body);
1128
Wei Liu546cb772016-07-21 16:19:01 -07001129 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001130 builder.setContentIntent(PendingIntent.getActivity(
1131 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 break;
1133 }
1134 }
1135
1136 // TODO: move to NotificationManager once we can mock it
1137 try {
1138 final String packageName = mContext.getPackageName();
1139 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001140 if(!TextUtils.isEmpty(body)) {
1141 builder.setStyle(new Notification.BigTextStyle()
1142 .bigText(body));
1143 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001144 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001145 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001146 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001149 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150 }
1151 }
1152
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001153 private void cancelNotification(String tag) {
1154 // TODO: move to NotificationManager once we can mock it
1155 try {
1156 final String packageName = mContext.getPackageName();
1157 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001158 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001159 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001160 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001161 }
1162 }
1163
1164 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001165 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001166 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001168 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001169 @Override
1170 public void onReceive(Context context, Intent intent) {
1171 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1172 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001173
1174 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001175 synchronized (mNetworkPoliciesSecondLock) {
1176 ensureActiveMobilePolicyNL();
1177 normalizePoliciesNL();
1178 updateNetworkEnabledNL();
1179 updateNetworkRulesNL();
1180 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 }
1182 }
1183 };
1184
1185 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 * Proactively control network data connections when they exceed
1187 * {@link NetworkPolicy#limitBytes}.
1188 */
Felipe Lemef0823852016-06-08 13:43:08 -07001189 void updateNetworkEnabledNL() {
1190 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001191
1192 // TODO: reset any policy-disabled networks when any policy is removed
1193 // completely, which is currently rare case.
1194
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001195 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001196 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1197 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001199 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001200 setNetworkTemplateEnabled(policy.template, true);
1201 continue;
1202 }
1203
1204 final long start = computeLastCycleBoundary(currentTime, policy);
1205 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001206 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001207
1208 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001209 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1210 && policy.lastLimitSnooze < start;
1211 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001212
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001213 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001214 }
1215 }
1216
1217 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 * Proactively disable networks that match the given
1219 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001220 */
1221 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001222 // TODO: reach into ConnectivityManager to proactively disable bringing
1223 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001224
1225 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1226 // If mobile data usage hits the limit or if the user resumes the data, we need to
1227 // notify telephony.
1228 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1229 final TelephonyManager tm = TelephonyManager.from(mContext);
1230
1231 final int[] subIds = sm.getActiveSubscriptionIdList();
1232 for (int subId : subIds) {
1233 final String subscriberId = tm.getSubscriberId(subId);
1234 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1235 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1236 // Template is matched when subscriber id matches.
1237 if (template.matches(probeIdent)) {
1238 tm.setPolicyDataEnabled(enabled, subId);
1239 }
1240 }
1241 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001242 }
1243
1244 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001245 * Examine all connected {@link NetworkState}, looking for
1246 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1247 * remaining quota based on usage cycle and historical stats.
1248 */
Felipe Lemef0823852016-06-08 13:43:08 -07001249 void updateNetworkRulesNL() {
1250 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251
1252 final NetworkState[] states;
1253 try {
1254 states = mConnManager.getAllNetworkState();
1255 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001256 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 return;
1258 }
1259
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001260 // First, generate identities of all connected networks so we can
1261 // quickly compare them against all defined policies below.
1262 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001263 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001265 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001266 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001267
1268 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001269 if (baseIface != null) {
1270 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001271 }
1272
1273 // Stacked interfaces are considered to have same identity as
1274 // their parent network.
1275 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1276 for (LinkProperties stackedLink : stackedLinks) {
1277 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001278 if (stackedIface != null) {
1279 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001280 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001281 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001282 }
1283 }
1284
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001285 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001286 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001287 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001288 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001289 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001290
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001292 for (int j = connIdents.size() - 1; j >= 0; j--) {
1293 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1294 if (policy.template.matches(ident.second)) {
1295 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001296 }
1297 }
1298
1299 if (ifaceList.size() > 0) {
1300 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001301 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 }
1303 }
1304
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001305 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001306 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001307
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 // apply each policy that we found ifaces for; compute remaining data
1309 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001310 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001311 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1312 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1313 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001315 final long start;
1316 final long totalBytes;
1317 if (policy.hasCycle()) {
1318 start = computeLastCycleBoundary(currentTime, policy);
1319 totalBytes = getTotalBytes(policy.template, start, currentTime);
1320 } else {
1321 start = Long.MAX_VALUE;
1322 totalBytes = 0;
1323 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001326 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 }
1328
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001329 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001330 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001331 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001332 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001333 if (!hasLimit) {
1334 // metered network, but no policy limit; we still need to
1335 // restrict apps, so push really high quota.
1336 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001337 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001338 // snoozing past quota, but we still need to restrict apps,
1339 // so push really high quota.
1340 quotaBytes = Long.MAX_VALUE;
1341 } else {
1342 // remaining "quota" bytes are based on total usage in
1343 // current cycle. kernel doesn't like 0-byte rules, so we
1344 // set 1-byte quota and disable the radio later.
1345 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1346 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001347
1348 if (ifaces.length > 1) {
1349 // TODO: switch to shared quota once NMS supports
1350 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001351 }
1352
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001353 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001354 // long quotaBytes split up into two ints to fit in message
1355 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1356 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1357 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001358 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001359 }
1360 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001361
1362 // keep track of lowest warning or limit of active policies
1363 if (hasWarning && policy.warningBytes < lowestRule) {
1364 lowestRule = policy.warningBytes;
1365 }
1366 if (hasLimit && policy.limitBytes < lowestRule) {
1367 lowestRule = policy.limitBytes;
1368 }
1369 }
1370
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001371 for (int i = connIfaces.size()-1; i >= 0; i--) {
1372 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001373 // long quotaBytes split up into two ints to fit in message
1374 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1375 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1376 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001377 newMeteredIfaces.add(iface);
1378 }
1379
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001380 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001382 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001383 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1384 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001385 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001386 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1387 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001388 }
1389 }
1390 mMeteredIfaces = newMeteredIfaces;
1391
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001392 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001393 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001394 }
1395
1396 /**
1397 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1398 * have at least a default mobile policy defined.
1399 */
Felipe Lemef0823852016-06-08 13:43:08 -07001400 private void ensureActiveMobilePolicyNL() {
1401 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001402 if (mSuppressDefaultPolicy) return;
1403
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001404 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001405 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001406
Jeff Sharkey32566012014-12-02 18:30:14 -08001407 final int[] subIds = sub.getActiveSubscriptionIdList();
1408 for (int subId : subIds) {
1409 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001410 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001411 }
1412 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001413
Felipe Lemef0823852016-06-08 13:43:08 -07001414 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001415 // Poke around to see if we already have a policy
1416 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001417 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001418 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1419 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1420 if (template.matches(probeIdent)) {
1421 if (LOGD) {
1422 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1423 + NetworkIdentity.scrubSubscriberId(subscriberId));
1424 }
1425 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001426 }
1427 }
1428
Jeff Sharkey32566012014-12-02 18:30:14 -08001429 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1430 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001431
Jeff Sharkey32566012014-12-02 18:30:14 -08001432 // Build default mobile policy, and assume usage cycle starts today
1433 final long warningBytes = mContext.getResources().getInteger(
1434 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001435
Jeff Sharkey32566012014-12-02 18:30:14 -08001436 final Time time = new Time();
1437 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001438
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 final int cycleDay = time.monthDay;
1440 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001441
Jeff Sharkey32566012014-12-02 18:30:14 -08001442 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1443 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1444 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001445 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446 }
1447
Felipe Lemef0823852016-06-08 13:43:08 -07001448 private void readPolicyAL() {
1449 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450
1451 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001452 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001453 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454
1455 FileInputStream fis = null;
1456 try {
1457 fis = mPolicyFile.openRead();
1458 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001459 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001460
1461 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001462 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001463 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001464 while ((type = in.next()) != END_DOCUMENT) {
1465 final String tag = in.getName();
1466 if (type == START_TAG) {
1467 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001468 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001469 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001470 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1471 mRestrictBackground = readBooleanAttribute(
1472 in, ATTR_RESTRICT_BACKGROUND);
1473 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001474 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001475 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001476 if (mRestrictBackground != oldValue) {
1477 // Some early services may have read the default value,
1478 // so notify them that it's changed
1479 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1480 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1481 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482
1483 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1484 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1485 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001486 final String networkId;
1487 if (version >= VERSION_ADDED_NETWORK_ID) {
1488 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1489 } else {
1490 networkId = null;
1491 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001492 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001493 final String cycleTimezone;
1494 if (version >= VERSION_ADDED_TIMEZONE) {
1495 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1496 } else {
1497 cycleTimezone = Time.TIMEZONE_UTC;
1498 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1500 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001501 final long lastLimitSnooze;
1502 if (version >= VERSION_SPLIT_SNOOZE) {
1503 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1504 } else if (version >= VERSION_ADDED_SNOOZE) {
1505 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001506 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001507 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001508 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001509 final boolean metered;
1510 if (version >= VERSION_ADDED_METERED) {
1511 metered = readBooleanAttribute(in, ATTR_METERED);
1512 } else {
1513 switch (networkTemplate) {
1514 case MATCH_MOBILE_3G_LOWER:
1515 case MATCH_MOBILE_4G:
1516 case MATCH_MOBILE_ALL:
1517 metered = true;
1518 break;
1519 default:
1520 metered = false;
1521 }
1522 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001523 final long lastWarningSnooze;
1524 if (version >= VERSION_SPLIT_SNOOZE) {
1525 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1526 } else {
1527 lastWarningSnooze = SNOOZE_NEVER;
1528 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001529 final boolean inferred;
1530 if (version >= VERSION_ADDED_INFERRED) {
1531 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1532 } else {
1533 inferred = false;
1534 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001535
Jeff Sharkey32566012014-12-02 18:30:14 -08001536 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1537 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001538 if (template.isPersistable()) {
1539 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1540 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1541 lastLimitSnooze, metered, inferred));
1542 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001543
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001544 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545 final int uid = readIntAttribute(in, ATTR_UID);
1546 final int policy = readIntAttribute(in, ATTR_POLICY);
1547
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001548 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001549 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001550 } else {
1551 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1552 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001553 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001554 final int appId = readIntAttribute(in, ATTR_APP_ID);
1555 final int policy = readIntAttribute(in, ATTR_POLICY);
1556
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001557 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001558 // app policy is deprecated so this is only used in pre system user split.
1559 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001560 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001561 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001562 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001563 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001564 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001565 } else if (TAG_WHITELIST.equals(tag)) {
1566 insideWhitelist = true;
1567 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1568 final int uid = readIntAttribute(in, ATTR_UID);
1569 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001570 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1571 final int uid = readIntAttribute(in, ATTR_UID);
1572 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001574 } else if (type == END_TAG) {
1575 if (TAG_WHITELIST.equals(tag)) {
1576 insideWhitelist = false;
1577 }
1578
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579 }
1580 }
1581
1582 } catch (FileNotFoundException e) {
1583 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001584 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001586 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001588 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589 } finally {
1590 IoUtils.closeQuietly(fis);
1591 }
1592 }
1593
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001594 /**
1595 * Upgrade legacy background data flags, notifying listeners of one last
1596 * change to always-true.
1597 */
Felipe Lemef0823852016-06-08 13:43:08 -07001598 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001599 mRestrictBackground = Settings.Secure.getInt(
1600 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1601
1602 // kick off one last broadcast if restricted
1603 if (mRestrictBackground) {
1604 final Intent broadcast = new Intent(
1605 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001606 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001607 }
1608 }
1609
Felipe Lemef0823852016-06-08 13:43:08 -07001610 void writePolicyAL() {
1611 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612
1613 FileOutputStream fos = null;
1614 try {
1615 fos = mPolicyFile.startWrite();
1616
1617 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001618 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619 out.startDocument(null, true);
1620
1621 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001622 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001623 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001624
1625 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001626 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1627 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001628 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001629 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001630
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001631 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001632 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1633 final String subscriberId = template.getSubscriberId();
1634 if (subscriberId != null) {
1635 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001636 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001637 final String networkId = template.getNetworkId();
1638 if (networkId != null) {
1639 out.attribute(null, ATTR_NETWORK_ID, networkId);
1640 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001641 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001642 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001643 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1644 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001645 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1646 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001647 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001648 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 out.endTag(null, TAG_NETWORK_POLICY);
1650 }
1651
1652 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001653 for (int i = 0; i < mUidPolicy.size(); i++) {
1654 final int uid = mUidPolicy.keyAt(i);
1655 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656
Jeff Sharkey497e4432011-06-14 17:27:29 -07001657 // skip writing empty policies
1658 if (policy == POLICY_NONE) continue;
1659
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001660 out.startTag(null, TAG_UID_POLICY);
1661 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001663 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001664 }
1665
1666 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001667
1668 // write all whitelists
1669 out.startTag(null, TAG_WHITELIST);
1670
1671 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001672 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001673 for (int i = 0; i < size; i++) {
1674 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1675 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1676 writeIntAttribute(out, ATTR_UID, uid);
1677 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1678 }
1679
Felipe Lemea9505cc2016-02-26 10:28:41 -08001680 // revoked restrict background whitelist
1681 size = mRestrictBackgroundWhitelistRevokedUids.size();
1682 for (int i = 0; i < size; i++) {
1683 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1684 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1685 writeIntAttribute(out, ATTR_UID, uid);
1686 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1687 }
1688
Felipe Lemeb85a6372016-01-14 16:16:16 -08001689 out.endTag(null, TAG_WHITELIST);
1690
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001691 out.endDocument();
1692
1693 mPolicyFile.finishWrite(fos);
1694 } catch (IOException e) {
1695 if (fos != null) {
1696 mPolicyFile.failWrite(fos);
1697 }
1698 }
1699 }
1700
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001701 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001702 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001703 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001704
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001705 if (!UserHandle.isApp(uid)) {
1706 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001707 }
Felipe Lemef0823852016-06-08 13:43:08 -07001708 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001709 final long token = Binder.clearCallingIdentity();
1710 try {
1711 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1712 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001713 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001714 }
1715 } finally {
1716 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001717 }
1718 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001719 }
1720
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001721 @Override
1722 public void addUidPolicy(int uid, int policy) {
1723 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001724
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001725 if (!UserHandle.isApp(uid)) {
1726 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1727 }
1728
Felipe Lemef0823852016-06-08 13:43:08 -07001729 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001730 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1731 policy |= oldPolicy;
1732 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001733 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001734 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001735 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001736 }
1737
1738 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001739 public void removeUidPolicy(int uid, int policy) {
1740 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1741
1742 if (!UserHandle.isApp(uid)) {
1743 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1744 }
1745
Felipe Lemef0823852016-06-08 13:43:08 -07001746 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001747 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1748 policy = oldPolicy & ~policy;
1749 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001750 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001751 }
1752 }
1753 }
1754
Felipe Lemef0823852016-06-08 13:43:08 -07001755 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1756 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001757
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001758 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1759 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1760 isBlacklisted ? 1 : 0).sendToTarget();
1761
1762 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001763 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001764 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1765 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001766 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001767 .sendToTarget();
1768 }
1769 }
1770
Felipe Lemef0823852016-06-08 13:43:08 -07001771 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001772 mUidPolicy.put(uid, policy);
1773
1774 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001775 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001776 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001777 synchronized (mNetworkPoliciesSecondLock) {
1778 writePolicyAL();
1779 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001780 }
1781 }
1782
1783 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001784 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001785 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1786
Felipe Lemef0823852016-06-08 13:43:08 -07001787 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001788 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001789 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001790 }
1791
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001792 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001793 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001794 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1795
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001796 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001797 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001798 for (int i = 0; i < mUidPolicy.size(); i++) {
1799 final int uid = mUidPolicy.keyAt(i);
1800 final int uidPolicy = mUidPolicy.valueAt(i);
1801 if (uidPolicy == policy) {
1802 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001803 }
1804 }
1805 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001806 return uids;
1807 }
1808
1809 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001810 * Removes any persistable state associated with given {@link UserHandle}, persisting
1811 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001812 */
Felipe Lemef0823852016-06-08 13:43:08 -07001813 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001814
Felipe Lemef0823852016-06-08 13:43:08 -07001815 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001816 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001817
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001818 // Remove entries from restricted background UID whitelist
1819 int[] wlUids = new int[0];
1820 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1821 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1822 if (UserHandle.getUserId(uid) == userId) {
1823 wlUids = appendInt(wlUids, uid);
1824 }
1825 }
1826
1827 if (wlUids.length > 0) {
1828 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001829 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001830 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001831 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001832 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001833
1834 // Remove entries from revoked default restricted background UID whitelist
1835 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1836 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1837 if (UserHandle.getUserId(uid) == userId) {
1838 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001839 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001840 }
1841 }
1842
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001843 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001844 int[] uids = new int[0];
1845 for (int i = 0; i < mUidPolicy.size(); i++) {
1846 final int uid = mUidPolicy.keyAt(i);
1847 if (UserHandle.getUserId(uid) == userId) {
1848 uids = appendInt(uids, uid);
1849 }
1850 }
1851
1852 if (uids.length > 0) {
1853 for (int uid : uids) {
1854 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001855 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001856 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001857 }
Felipe Lemef0823852016-06-08 13:43:08 -07001858 synchronized (mNetworkPoliciesSecondLock) {
1859 updateRulesForGlobalChangeAL(true);
1860 if (writePolicy && changed) {
1861 writePolicyAL();
1862 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001863 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001864 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001865 }
1866
1867 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001868 public void setConnectivityListener(INetworkPolicyListener listener) {
1869 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1870 if (mConnectivityListener != null) {
1871 throw new IllegalStateException("Connectivity listener already registered");
1872 }
1873 mConnectivityListener = listener;
1874 }
1875
1876 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001877 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001878 // TODO: create permission for observing network policy
1879 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001880 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001881 }
1882
1883 @Override
1884 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001885 // TODO: create permission for observing network policy
1886 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001887 mListeners.unregister(listener);
1888 }
1889
Jeff Sharkey1b861272011-05-22 00:34:52 -07001890 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001891 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001892 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1893
Felipe Leme6a05eee2016-02-19 14:43:51 -08001894 final long token = Binder.clearCallingIdentity();
1895 try {
1896 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001897 synchronized (mUidRulesFirstLock) {
1898 synchronized (mNetworkPoliciesSecondLock) {
1899 normalizePoliciesNL(policies);
1900 updateNetworkEnabledNL();
1901 updateNetworkRulesNL();
1902 updateNotificationsNL();
1903 writePolicyAL();
1904 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001905 }
1906 } finally {
1907 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001908 }
1909 }
1910
Felipe Lemef0823852016-06-08 13:43:08 -07001911 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001912 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001913 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1914 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001915 }
1916
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001917 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001918 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001919 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001920 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001921 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1922 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1923 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001924 } catch (SecurityException e) {
1925 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001926
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001927 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1928 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1929 return new NetworkPolicy[0];
1930 }
Svet Ganov16a16892015-04-16 10:32:04 -07001931 }
1932
Felipe Lemef0823852016-06-08 13:43:08 -07001933 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001934 final int size = mNetworkPolicy.size();
1935 final NetworkPolicy[] policies = new NetworkPolicy[size];
1936 for (int i = 0; i < size; i++) {
1937 policies[i] = mNetworkPolicy.valueAt(i);
1938 }
1939 return policies;
1940 }
1941 }
1942
Felipe Lemef0823852016-06-08 13:43:08 -07001943 private void normalizePoliciesNL() {
1944 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001945 }
1946
Felipe Lemef0823852016-06-08 13:43:08 -07001947 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001948 final TelephonyManager tele = TelephonyManager.from(mContext);
1949 final String[] merged = tele.getMergedSubscriberIds();
1950
1951 mNetworkPolicy.clear();
1952 for (NetworkPolicy policy : policies) {
1953 // When two normalized templates conflict, prefer the most
1954 // restrictive policy
1955 policy.template = NetworkTemplate.normalize(policy.template, merged);
1956 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1957 if (existing == null || existing.compareTo(policy) > 0) {
1958 if (existing != null) {
1959 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1960 }
1961 mNetworkPolicy.put(policy.template, policy);
1962 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001963 }
1964 }
1965
1966 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001967 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001968 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001969
1970 final long token = Binder.clearCallingIdentity();
1971 try {
1972 performSnooze(template, TYPE_LIMIT);
1973 } finally {
1974 Binder.restoreCallingIdentity(token);
1975 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001976 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001977
Dianne Hackborn497175b2014-07-01 12:56:08 -07001978 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001979 maybeRefreshTrustedTime();
1980 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001981 synchronized (mUidRulesFirstLock) {
1982 synchronized (mNetworkPoliciesSecondLock) {
1983 // find and snooze local policy that matches
1984 final NetworkPolicy policy = mNetworkPolicy.get(template);
1985 if (policy == null) {
1986 throw new IllegalArgumentException("unable to find policy for " + template);
1987 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001988
Felipe Lemef0823852016-06-08 13:43:08 -07001989 switch (type) {
1990 case TYPE_WARNING:
1991 policy.lastWarningSnooze = currentTime;
1992 break;
1993 case TYPE_LIMIT:
1994 policy.lastLimitSnooze = currentTime;
1995 break;
1996 default:
1997 throw new IllegalArgumentException("unexpected type");
1998 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001999
Felipe Lemef0823852016-06-08 13:43:08 -07002000 normalizePoliciesNL();
2001 updateNetworkEnabledNL();
2002 updateNetworkRulesNL();
2003 updateNotificationsNL();
2004 writePolicyAL();
2005 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002006 }
2007 }
2008
2009 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002010 public void onTetheringChanged(String iface, boolean tethering) {
2011 // No need to enforce permission because setRestrictBackground() will do it.
2012 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002013 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002014 if (mRestrictBackground && tethering) {
2015 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2016 setRestrictBackground(false);
2017 }
2018 }
2019 }
2020
2021 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002022 public void setRestrictBackground(boolean restrictBackground) {
2023 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002024 final long token = Binder.clearCallingIdentity();
2025 try {
2026 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002027 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002028 if (restrictBackground == mRestrictBackground) {
2029 // Ideally, UI should never allow this scenario...
2030 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2031 return;
2032 }
Felipe Lemef0823852016-06-08 13:43:08 -07002033 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002034 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002035
Felipe Leme6a05eee2016-02-19 14:43:51 -08002036 } finally {
2037 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002038 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002039
2040 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2041 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002042 }
2043
Felipe Lemef0823852016-06-08 13:43:08 -07002044 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002045 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002046 final boolean oldRestrictBackground = mRestrictBackground;
2047 mRestrictBackground = restrictBackground;
2048 // Must whitelist foreground apps before turning data saver mode on.
2049 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2050 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002051 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002052 try {
2053 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2054 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2055 mRestrictBackground = oldRestrictBackground;
2056 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002057 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002058 return;
2059 }
2060 } catch (RemoteException e) {
2061 // ignored; service lives in system_server
2062 }
Felipe Lemef0823852016-06-08 13:43:08 -07002063 synchronized (mNetworkPoliciesSecondLock) {
2064 updateNotificationsNL();
2065 writePolicyAL();
2066 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002067 }
2068
Jeff Sharkey46645002011-07-27 21:11:21 -07002069 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002070 public void addRestrictBackgroundWhitelistedUid(int uid) {
2071 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002072 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002073 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002074 int changed;
2075 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002076 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002077 if (oldStatus) {
2078 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2079 return;
2080 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002081 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002082 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002083 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002084 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2085 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2086 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2087 + " from revoked restrict background whitelist");
2088 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2089 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002090 if (needFirewallRules) {
2091 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002092 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002093 }
2094 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002095 synchronized (mNetworkPoliciesSecondLock) {
2096 writePolicyAL();
2097 }
2098 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002099 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002100 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2101 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002102 }
2103
2104 @Override
2105 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2106 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002107 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002108 synchronized (mUidRulesFirstLock) {
2109 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002110 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002111 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2112 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002113 }
2114
Felipe Leme70c57c22016-03-29 10:45:13 -07002115 /**
2116 * Removes a uid from the restricted background whitelist, returning whether its current
2117 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2118 */
Felipe Lemef0823852016-06-08 13:43:08 -07002119 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002120 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002121 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002122 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002123 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2124 return false;
2125 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002126 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002127 if (oldStatus) {
2128 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2129 mRestrictBackgroundWhitelistUids.delete(uid);
2130 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002131 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2132 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2133 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2134 + " to revoked restrict background whitelist");
2135 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2136 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002137 if (needFirewallRules) {
2138 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002139 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002140 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002141 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002142 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002143 synchronized (mNetworkPoliciesSecondLock) {
2144 writePolicyAL();
2145 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002146 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002147 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2148 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002149 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002150 }
2151
2152 @Override
2153 public int[] getRestrictBackgroundWhitelistedUids() {
2154 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002155 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002156 final int size = mRestrictBackgroundWhitelistUids.size();
2157 final int[] whitelist = new int[size];
2158 for (int i = 0; i < size; i++) {
2159 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2160 }
2161 if (LOGV) {
2162 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2163 + mRestrictBackgroundWhitelistUids);
2164 }
2165 return whitelist;
2166 }
2167 }
2168
2169 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002170 public int getRestrictBackgroundByCaller() {
2171 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2172 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002173
Felipe Lemef0823852016-06-08 13:43:08 -07002174 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002175 // Must clear identity because getUidPolicy() is restricted to system.
2176 final long token = Binder.clearCallingIdentity();
2177 final int policy;
2178 try {
2179 policy = getUidPolicy(uid);
2180 } finally {
2181 Binder.restoreCallingIdentity(token);
2182 }
2183 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2184 // App is blacklisted.
2185 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2186 }
Felipe Leme1b103232016-01-22 09:44:57 -08002187 if (!mRestrictBackground) {
2188 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2189 }
2190 return mRestrictBackgroundWhitelistUids.get(uid)
2191 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2192 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2193 }
2194 }
2195
2196 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002197 public boolean getRestrictBackground() {
2198 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2199
Felipe Lemef0823852016-06-08 13:43:08 -07002200 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002201 return mRestrictBackground;
2202 }
2203 }
2204
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002205 @Override
2206 public void setDeviceIdleMode(boolean enabled) {
2207 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2208
Felipe Lemef0823852016-06-08 13:43:08 -07002209 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002210 if (mDeviceIdleMode != enabled) {
2211 mDeviceIdleMode = enabled;
2212 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002213 // Device idle change means we need to rebuild rules for all
2214 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002215 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002216 }
2217 if (enabled) {
2218 EventLogTags.writeDeviceIdleOnPhase("net");
2219 } else {
2220 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002221 }
2222 }
2223 }
2224 }
2225
Felipe Lemef0823852016-06-08 13:43:08 -07002226 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002227 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2228 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002229 if (policy.template.matches(ident)) {
2230 return policy;
2231 }
2232 }
2233 return null;
2234 }
2235
2236 @Override
2237 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2238 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2239
2240 // only returns usage summary, so we don't require caller to have
2241 // READ_NETWORK_USAGE_HISTORY.
2242 final long token = Binder.clearCallingIdentity();
2243 try {
2244 return getNetworkQuotaInfoUnchecked(state);
2245 } finally {
2246 Binder.restoreCallingIdentity(token);
2247 }
2248 }
2249
2250 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2251 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2252
2253 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002254 synchronized (mNetworkPoliciesSecondLock) {
2255 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002256 }
2257
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002258 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002259 // missing policy means we can't derive useful quota info
2260 return null;
2261 }
2262
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002263 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002264
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002265 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002266 final long start = computeLastCycleBoundary(currentTime, policy);
2267 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002268 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002269
2270 // report soft and hard limits under policy
2271 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2272 : NetworkQuotaInfo.NO_LIMIT;
2273 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2274 : NetworkQuotaInfo.NO_LIMIT;
2275
2276 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2277 }
2278
Jeff Sharkey46645002011-07-27 21:11:21 -07002279 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002280 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002281 if (state.networkInfo == null) {
2282 return false;
2283 }
2284
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002285 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2286
2287 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002288 synchronized (mNetworkPoliciesSecondLock) {
2289 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002290 }
2291
2292 if (policy != null) {
2293 return policy.metered;
2294 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002295 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002296 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002297 return true;
2298 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002299 return false;
2300 }
2301 }
2302
2303 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002304 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002305 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002306
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002307 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2308
Dianne Hackborn497175b2014-07-01 12:56:08 -07002309 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002310 for (String arg : args) {
2311 argSet.add(arg);
2312 }
2313
Felipe Lemef0823852016-06-08 13:43:08 -07002314 synchronized (mUidRulesFirstLock) {
2315 synchronized (mNetworkPoliciesSecondLock) {
2316 if (argSet.contains("--unsnooze")) {
2317 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2318 mNetworkPolicy.valueAt(i).clearSnooze();
2319 }
2320
2321 normalizePoliciesNL();
2322 updateNetworkEnabledNL();
2323 updateNetworkRulesNL();
2324 updateNotificationsNL();
2325 writePolicyAL();
2326
2327 fout.println("Cleared snooze timestamps");
2328 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002329 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002330
Felipe Lemef0823852016-06-08 13:43:08 -07002331 fout.print("System ready: "); fout.println(mSystemReady);
2332 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2333 fout.print("Restrict power: "); fout.println(mRestrictPower);
2334 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2335 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002336 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002337 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2338 fout.println(mNetworkPolicy.valueAt(i).toString());
2339 }
2340 fout.decreaseIndent();
2341
2342 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2343
2344 fout.println("Policy for UIDs:");
2345 fout.increaseIndent();
2346 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002347 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002348 final int uid = mUidPolicy.keyAt(i);
2349 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002350 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002351 fout.print(uid);
2352 fout.print(" policy=");
2353 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2354 fout.println();
2355 }
2356 fout.decreaseIndent();
2357
2358 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2359 if (size > 0) {
2360 fout.println("Power save whitelist (except idle) app ids:");
2361 fout.increaseIndent();
2362 for (int i = 0; i < size; i++) {
2363 fout.print("UID=");
2364 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2365 fout.print(": ");
2366 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2367 fout.println();
2368 }
2369 fout.decreaseIndent();
2370 }
2371
2372 size = mPowerSaveWhitelistAppIds.size();
2373 if (size > 0) {
2374 fout.println("Power save whitelist app ids:");
2375 fout.increaseIndent();
2376 for (int i = 0; i < size; i++) {
2377 fout.print("UID=");
2378 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2379 fout.print(": ");
2380 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2381 fout.println();
2382 }
2383 fout.decreaseIndent();
2384 }
2385
2386 size = mRestrictBackgroundWhitelistUids.size();
2387 if (size > 0) {
2388 fout.println("Restrict background whitelist uids:");
2389 fout.increaseIndent();
2390 for (int i = 0; i < size; i++) {
2391 fout.print("UID=");
2392 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2393 fout.println();
2394 }
2395 fout.decreaseIndent();
2396 }
2397
2398 size = mDefaultRestrictBackgroundWhitelistUids.size();
2399 if (size > 0) {
2400 fout.println("Default restrict background whitelist uids:");
2401 fout.increaseIndent();
2402 for (int i = 0; i < size; i++) {
2403 fout.print("UID=");
2404 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2405 fout.println();
2406 }
2407 fout.decreaseIndent();
2408 }
2409
2410 size = mRestrictBackgroundWhitelistRevokedUids.size();
2411 if (size > 0) {
2412 fout.println("Default restrict background whitelist uids revoked by users:");
2413 fout.increaseIndent();
2414 for (int i = 0; i < size; i++) {
2415 fout.print("UID=");
2416 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2417 fout.println();
2418 }
2419 fout.decreaseIndent();
2420 }
2421
2422 final SparseBooleanArray knownUids = new SparseBooleanArray();
2423 collectKeys(mUidState, knownUids);
2424 collectKeys(mUidRules, knownUids);
2425
2426 fout.println("Status for all known UIDs:");
2427 fout.increaseIndent();
2428 size = knownUids.size();
2429 for (int i = 0; i < size; i++) {
2430 final int uid = knownUids.keyAt(i);
2431 fout.print("UID=");
2432 fout.print(uid);
2433
2434 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2435 fout.print(" state=");
2436 fout.print(state);
2437 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2438 fout.print(" (fg)");
2439 } else {
2440 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2441 ? " (fg svc)" : " (bg)");
2442 }
2443
2444 final int uidRules = mUidRules.get(uid, RULE_NONE);
2445 fout.print(" rules=");
2446 fout.print(uidRulesToString(uidRules));
2447 fout.println();
2448 }
2449 fout.decreaseIndent();
2450
2451 fout.println("Status for just UIDs with rules:");
2452 fout.increaseIndent();
2453 size = mUidRules.size();
2454 for (int i = 0; i < size; i++) {
2455 final int uid = mUidRules.keyAt(i);
2456 fout.print("UID=");
2457 fout.print(uid);
2458 final int uidRules = mUidRules.get(uid, RULE_NONE);
2459 fout.print(" rules=");
2460 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002461 fout.println();
2462 }
2463 fout.decreaseIndent();
2464 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002465 }
2466 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002467
2468 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002469 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2470 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002471 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002472 this, in, out, err, args, resultReceiver);
2473 }
2474
2475 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002476 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002477 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2478
Felipe Lemef0823852016-06-08 13:43:08 -07002479 synchronized (mUidRulesFirstLock) {
2480 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002481 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002482 }
2483
Felipe Lemef0823852016-06-08 13:43:08 -07002484 private boolean isUidForegroundUL(int uid) {
2485 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002486 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2487 }
2488
Felipe Lemef0823852016-06-08 13:43:08 -07002489 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002490 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002491 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002492 }
2493
Felipe Lemef0823852016-06-08 13:43:08 -07002494 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002495 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2496 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2497 }
2498
Felipe Lemef0823852016-06-08 13:43:08 -07002499 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002500 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002501 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002502 }
2503
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002504 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002505 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002506 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2507 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002508 */
Felipe Lemef0823852016-06-08 13:43:08 -07002509 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002510 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2511 if (oldUidState != uidState) {
2512 // state changed, push updated rules
2513 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002514 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002515 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2516 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002517 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002518 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002519 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002520 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002521 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002522 }
2523 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002524 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002525 }
Felipe Lemef0823852016-06-08 13:43:08 -07002526 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002527 }
Felipe Lemef0823852016-06-08 13:43:08 -07002528 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002529 }
2530 }
2531
Felipe Lemef0823852016-06-08 13:43:08 -07002532 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002533 final int index = mUidState.indexOfKey(uid);
2534 if (index >= 0) {
2535 final int oldUidState = mUidState.valueAt(index);
2536 mUidState.removeAt(index);
2537 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002538 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002539 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002540 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002541 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002542 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002543 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002544 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002545 }
Felipe Lemef0823852016-06-08 13:43:08 -07002546 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002547 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002548 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002549 }
2550 }
2551
Felipe Lemef28983d2016-03-25 12:18:23 -07002552 // adjust stats accounting based on foreground status
2553 private void updateNetworkStats(int uid, boolean uidForeground) {
2554 try {
2555 mNetworkStats.setUidForeground(uid, uidForeground);
2556 } catch (RemoteException e) {
2557 // ignored; service lives in system_server
2558 }
2559 }
2560
Felipe Lemef0823852016-06-08 13:43:08 -07002561 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002562 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002563 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002564 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002565 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002566 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002567 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002568 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002569 }
2570 }
2571
Felipe Leme011b98f2016-02-10 17:28:31 -08002572 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002573 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2574 }
2575
Felipe Lemef0823852016-06-08 13:43:08 -07002576 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002577 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2578 }
2579
Felipe Lemef0823852016-06-08 13:43:08 -07002580 void updateRulesForPowerSaveUL() {
2581 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002582 mUidFirewallPowerSaveRules);
2583 }
2584
Felipe Lemef0823852016-06-08 13:43:08 -07002585 void updateRuleForRestrictPowerUL(int uid) {
2586 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002587 }
2588
Felipe Lemef0823852016-06-08 13:43:08 -07002589 void updateRulesForDeviceIdleUL() {
2590 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002591 mUidFirewallDozableRules);
2592 }
2593
Felipe Lemef0823852016-06-08 13:43:08 -07002594 void updateRuleForDeviceIdleUL(int uid) {
2595 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002596 }
2597
Felipe Lemef28983d2016-03-25 12:18:23 -07002598 // NOTE: since both fw_dozable and fw_powersave uses the same map
2599 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002600 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002601 SparseIntArray rules) {
2602 if (enabled) {
2603 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002604 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002605 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002606 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002607 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002608 for (int ui = users.size() - 1; ui >= 0; ui--) {
2609 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002610 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002611 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2612 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2613 int uid = UserHandle.getUid(user.id, appId);
2614 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2615 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002616 }
2617 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2618 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2619 int uid = UserHandle.getUid(user.id, appId);
2620 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2621 }
2622 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002623 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002624 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002625 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2626 }
2627 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002628 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002629 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002630
Felipe Lemef0823852016-06-08 13:43:08 -07002631 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002632 }
2633
Felipe Lemef0823852016-06-08 13:43:08 -07002634 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002635 final int appId = UserHandle.getAppId(uid);
2636 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2637 }
2638
Felipe Lemef28983d2016-03-25 12:18:23 -07002639 // NOTE: since both fw_dozable and fw_powersave uses the same map
2640 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002641 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002642 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002643 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002644 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2645 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002646 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002647 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002648 }
2649 }
2650 }
2651
Felipe Lemef0823852016-06-08 13:43:08 -07002652 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002653 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2654 uidRules.clear();
2655
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002656 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002657 final List<UserInfo> users = mUserManager.getUsers();
2658 for (int ui = users.size() - 1; ui >= 0; ui--) {
2659 UserInfo user = users.get(ui);
2660 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2661 for (int uid : idleUids) {
2662 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002663 // quick check: if this uid doesn't have INTERNET permission, it
2664 // doesn't have network access anyway, so it is a waste to mess
2665 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002666 if (hasInternetPermissions(uid)) {
2667 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002668 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002669 }
2670 }
2671 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002672
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002673 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2674 }
2675
Felipe Lemef0823852016-06-08 13:43:08 -07002676 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002677 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002678
2679 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002680 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002681 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002682 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2683 } else {
2684 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2685 }
2686 }
2687
Felipe Lemef0823852016-06-08 13:43:08 -07002688 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002689 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002690 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002691 }
2692
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002693 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002694 * Update rules that might be changed by {@link #mRestrictBackground},
2695 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002696 */
Felipe Lemef0823852016-06-08 13:43:08 -07002697 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002698 long start;
2699 if (LOGD) start = System.currentTimeMillis();
2700
Felipe Lemef0823852016-06-08 13:43:08 -07002701 updateRulesForRestrictPowerUL();
2702 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002703
2704 // If the set of restricted networks may have changed, re-evaluate those.
2705 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002706 normalizePoliciesNL();
2707 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002708 }
2709 if (LOGD) {
2710 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002711 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002712 + delta + "ms");
2713 }
2714 }
2715
Felipe Lemef0823852016-06-08 13:43:08 -07002716 private void updateRulesForRestrictPowerUL() {
2717 updateRulesForDeviceIdleUL();
2718 updateRulesForAppIdleUL();
2719 updateRulesForPowerSaveUL();
2720 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002721 }
2722
Felipe Lemef0823852016-06-08 13:43:08 -07002723 private void updateRulesForRestrictBackgroundUL() {
2724 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002725 }
2726
2727 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2728 private static final int TYPE_RESTRICT_POWER = 2;
2729 @Retention(RetentionPolicy.SOURCE)
2730 @IntDef(flag = false, value = {
2731 TYPE_RESTRICT_BACKGROUND,
2732 TYPE_RESTRICT_POWER,
2733 })
2734 public @interface RestrictType {
2735 }
2736
2737 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002738 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002739 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002740
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002741 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002742 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002743 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002744 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2745 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2746 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002747
Felipe Leme03e689d2016-03-02 16:17:38 -08002748 final int usersSize = users.size();
2749 final int appsSize = apps.size();
2750 for (int i = 0; i < usersSize; i++) {
2751 final UserInfo user = users.get(i);
2752 for (int j = 0; j < appsSize; j++) {
2753 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002754 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002755 switch (type) {
2756 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002757 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002758 break;
2759 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002760 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002761 break;
2762 default:
2763 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2764 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002765 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002766 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002767 }
2768
Felipe Lemef0823852016-06-08 13:43:08 -07002769 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002770 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002771 for (int i = 0; i < users.size(); i++) {
2772 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002773 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002774 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002775 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002776 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002777 updateRuleForAppIdleUL(uid);
2778 updateRuleForDeviceIdleUL(uid);
2779 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002780 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002781 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002782 }
2783 }
2784 }
2785
Felipe Leme70c57c22016-03-29 10:45:13 -07002786 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2787 // methods below could be merged into a isUidValidForRules() method.
2788 private boolean isUidValidForBlacklistRules(int uid) {
2789 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002790 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002791 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002792 return true;
2793 }
2794
2795 return false;
2796 }
2797
Felipe Leme70c57c22016-03-29 10:45:13 -07002798 private boolean isUidValidForWhitelistRules(int uid) {
2799 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2800 }
2801
Amith Yamasani15e472352015-04-24 19:06:07 -07002802 private boolean isUidIdle(int uid) {
2803 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2804 final int userId = UserHandle.getUserId(uid);
2805
songjinshi0655edd2016-05-18 19:55:32 +08002806 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002807 for (String packageName : packages) {
2808 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2809 return false;
2810 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002811 }
2812 }
2813 return true;
2814 }
2815
2816 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002817 * Checks if an uid has INTERNET permissions.
2818 * <p>
2819 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002820 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002821 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002822 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002823 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002824 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002825 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002826 }
2827 } catch (RemoteException e) {
2828 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002829 return true;
2830 }
2831
2832 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002833 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002834 *
Felipe Leme781ba142016-05-09 16:24:48 -07002835 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002836 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002837 * <li>Doze mode
2838 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002839 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002840 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002841 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002842 *
2843 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002844 */
Felipe Lemef0823852016-06-08 13:43:08 -07002845 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002846 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002847 updateRuleForDeviceIdleUL(uid);
2848 updateRuleForAppIdleUL(uid);
2849 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002850
2851 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002852 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002853
2854 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002855 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002856 }
2857
Felipe Leme70c57c22016-03-29 10:45:13 -07002858 /**
2859 * Applies network rules to bandwidth controllers based on process state and user-defined
2860 * restrictions (blacklist / whitelist).
2861 *
2862 * <p>
2863 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2864 * networks:
2865 * <ul>
2866 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2867 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2868 * also blacklisted.
2869 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2870 * no UIDs other those whitelisted will have access.
2871 * <ul>
2872 *
2873 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2874 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2875 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2876 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002877 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002878 * {@link INetworkManagementService}, but this method should also be called in events (like
2879 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2880 * following rules should also be applied:
2881 *
2882 * <ul>
2883 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2884 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2885 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2886 * {@code bw_penalty_box}.
2887 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2888 * </ul>
2889 *
2890 * <p>For optimization, the rules are only applied on user apps that have internet access
2891 * permission, since there is no need to change the {@code iptables} rule if the app does not
2892 * have permission to use the internet.
2893 *
2894 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002895 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002896 */
Felipe Lemef0823852016-06-08 13:43:08 -07002897 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2898 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002899 }
2900
2901 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002902 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002903 * app is removed - it ignores the UID validity check.
2904 */
Felipe Lemef0823852016-06-08 13:43:08 -07002905 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002906 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2907 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2908 return;
2909 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002910
Dianne Hackborn497175b2014-07-01 12:56:08 -07002911 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002912 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002913 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002914
Felipe Leme781ba142016-05-09 16:24:48 -07002915 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2916 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2917 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2918 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002919
Felipe Leme70c57c22016-03-29 10:45:13 -07002920 // First step: define the new rule based on user restrictions and foreground state.
2921 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002922 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2923 newRule = RULE_TEMPORARY_ALLOW_METERED;
2924 } else if (isWhitelisted) {
2925 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002926 }
2927 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002928 if (isBlacklisted) {
2929 newRule = RULE_REJECT_METERED;
2930 } else if (mRestrictBackground && isWhitelisted) {
2931 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002932 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002933 }
Felipe Leme781ba142016-05-09 16:24:48 -07002934 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002935
Felipe Lemef28983d2016-03-25 12:18:23 -07002936 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002937 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002938 + ": isForeground=" +isForeground
2939 + ", isBlacklisted=" + isBlacklisted
2940 + ", isWhitelisted=" + isWhitelisted
2941 + ", oldRule=" + uidRulesToString(oldRule)
2942 + ", newRule=" + uidRulesToString(newRule)
2943 + ", newUidRules=" + uidRulesToString(newUidRules)
2944 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002945 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002946
Felipe Leme46c4fc32016-05-04 09:21:43 -07002947 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002948 mUidRules.delete(uid);
2949 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002950 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002951 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002952
Felipe Leme70c57c22016-03-29 10:45:13 -07002953 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002954 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002955 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002956 // Temporarily whitelist foreground app, removing from blacklist if necessary
2957 // (since bw_penalty_box prevails over bw_happy_box).
2958
2959 setMeteredNetworkWhitelist(uid, true);
2960 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2961 // but ideally it should be just:
2962 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002963 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002964 setMeteredNetworkBlacklist(uid, false);
2965 }
Felipe Leme781ba142016-05-09 16:24:48 -07002966 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002967 // Remove temporary whitelist from app that is not on foreground anymore.
2968
2969 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2970 // but ideally they should be just:
2971 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2972 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002973 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002974 setMeteredNetworkWhitelist(uid, false);
2975 }
Felipe Leme781ba142016-05-09 16:24:48 -07002976 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002977 setMeteredNetworkBlacklist(uid, true);
2978 }
Felipe Leme781ba142016-05-09 16:24:48 -07002979 } else if ((newRule & RULE_REJECT_METERED) != 0
2980 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002981 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002982 setMeteredNetworkBlacklist(uid, isBlacklisted);
2983 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002984 // Since blacklist prevails over whitelist, we need to handle the special case
2985 // where app is whitelisted and blacklisted at the same time (although such
2986 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07002987 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002988 }
Felipe Leme781ba142016-05-09 16:24:48 -07002989 } else if ((newRule & RULE_ALLOW_METERED) != 0
2990 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002991 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07002992 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07002993 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002994 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07002995 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
2996 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07002997 + ", whitelisted=" + isWhitelisted
2998 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07002999 + ", newRule=" + uidRulesToString(newUidRules)
3000 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003001 }
Felipe Leme781ba142016-05-09 16:24:48 -07003002
3003 // Dispatch changed rule to existing listeners.
3004 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3005 }
3006 }
3007
3008 /**
3009 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3010 * listeners in case of change.
3011 * <p>
3012 * There are 3 power-related rules that affects whether an app has background access on
3013 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3014 * restriction, it's added to the equivalent firewall chain:
3015 * <ul>
3016 * <li>App is idle: {@code fw_standby} firewall chain.
3017 * <li>Device is idle: {@code fw_dozable} firewall chain.
3018 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3019 * </ul>
3020 * <p>
3021 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3022 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3023 * <p>
3024 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3025 */
Felipe Lemef0823852016-06-08 13:43:08 -07003026 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003027 if (!isUidValidForBlacklistRules(uid)) {
3028 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3029 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003030 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003031
Felipe Leme781ba142016-05-09 16:24:48 -07003032 final boolean isIdle = isUidIdle(uid);
3033 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Leme781ba142016-05-09 16:24:48 -07003034 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003035 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003036
Felipe Lemef0823852016-06-08 13:43:08 -07003037 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003038 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3039 int newRule = RULE_NONE;
3040
3041 // First step: define the new rule based on user restrictions and foreground state.
3042
3043 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3044 // by considering the foreground and non-foreground states.
3045 if (isForeground) {
3046 if (restrictMode) {
3047 newRule = RULE_ALLOW_ALL;
3048 }
3049 } else if (restrictMode) {
3050 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3051 }
3052
3053 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3054
3055 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003056 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003057 + ", isIdle: " + isIdle
3058 + ", mRestrictPower: " + mRestrictPower
3059 + ", mDeviceIdleMode: " + mDeviceIdleMode
3060 + ", isForeground=" + isForeground
3061 + ", isWhitelisted=" + isWhitelisted
3062 + ", oldRule=" + uidRulesToString(oldRule)
3063 + ", newRule=" + uidRulesToString(newRule)
3064 + ", newUidRules=" + uidRulesToString(newUidRules)
3065 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3066 }
3067
3068 if (newUidRules == RULE_NONE) {
3069 mUidRules.delete(uid);
3070 } else {
3071 mUidRules.put(uid, newUidRules);
3072 }
3073
3074 // Second step: notify listeners if state changed.
3075 if (newRule != oldRule) {
3076 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003077 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003078 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003079 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3080 } else {
3081 // All scenarios should have been covered above
3082 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3083 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003084 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003085 + ", newRule=" + uidRulesToString(newUidRules)
3086 + ", oldRule=" + uidRulesToString(oldUidRules));
3087 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003088 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003089 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003090 }
3091
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003092 private class AppIdleStateChangeListener
3093 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3094
3095 @Override
3096 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3097 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003098 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3099 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003100 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003101 synchronized (mUidRulesFirstLock) {
3102 updateRuleForAppIdleUL(uid);
3103 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003104 }
3105 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003106 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003107 }
3108
3109 @Override
3110 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003111 synchronized (mUidRulesFirstLock) {
3112 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003113 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003114 }
3115 }
3116
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003117 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3118 if (listener != null) {
3119 try {
3120 listener.onUidRulesChanged(uid, uidRules);
3121 } catch (RemoteException ignored) {
3122 }
3123 }
3124 }
3125
3126 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3127 String[] meteredIfaces) {
3128 if (listener != null) {
3129 try {
3130 listener.onMeteredIfacesChanged(meteredIfaces);
3131 } catch (RemoteException ignored) {
3132 }
3133 }
3134 }
3135
3136 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3137 boolean restrictBackground) {
3138 if (listener != null) {
3139 try {
3140 listener.onRestrictBackgroundChanged(restrictBackground);
3141 } catch (RemoteException ignored) {
3142 }
3143 }
3144 }
3145
3146 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3147 int uid, boolean whitelisted) {
3148 if (listener != null) {
3149 try {
3150 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3151 } catch (RemoteException ignored) {
3152 }
3153 }
3154 }
3155
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003156 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3157 int uid, boolean blacklisted) {
3158 if (listener != null) {
3159 try {
3160 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3161 } catch (RemoteException ignored) {
3162 }
3163 }
3164 }
3165
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003166 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003167 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003168 public boolean handleMessage(Message msg) {
3169 switch (msg.what) {
3170 case MSG_RULES_CHANGED: {
3171 final int uid = msg.arg1;
3172 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003173 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003174 final int length = mListeners.beginBroadcast();
3175 for (int i = 0; i < length; i++) {
3176 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003177 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003178 }
3179 mListeners.finishBroadcast();
3180 return true;
3181 }
3182 case MSG_METERED_IFACES_CHANGED: {
3183 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003184 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003185 final int length = mListeners.beginBroadcast();
3186 for (int i = 0; i < length; i++) {
3187 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003188 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003189 }
3190 mListeners.finishBroadcast();
3191 return true;
3192 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003193 case MSG_LIMIT_REACHED: {
3194 final String iface = (String) msg.obj;
3195
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003196 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003197 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003198 if (mMeteredIfaces.contains(iface)) {
3199 try {
3200 // force stats update to make sure we have
3201 // numbers that caused alert to trigger.
3202 mNetworkStats.forceUpdate();
3203 } catch (RemoteException e) {
3204 // ignored; service lives in system_server
3205 }
3206
Felipe Lemef0823852016-06-08 13:43:08 -07003207 updateNetworkEnabledNL();
3208 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003209 }
3210 }
3211 return true;
3212 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003213 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3214 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003215 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003216 final int length = mListeners.beginBroadcast();
3217 for (int i = 0; i < length; i++) {
3218 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003219 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003220 }
3221 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003222 final Intent intent =
3223 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3224 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3225 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3226 return true;
3227 }
3228 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003229 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3230 // - when an app is whitelisted
3231 // - when an app is blacklisted
3232 //
3233 // Whether the internal listeners (INetworkPolicyListener implementations) or
3234 // app broadcast receivers are notified depend on the following rules:
3235 //
3236 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3237 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3238 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003239 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003240 final boolean changed = msg.arg2 == 1;
3241 final Boolean whitelisted = (Boolean) msg.obj;
3242
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003243 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003244 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003245 final boolean whitelistedBool = whitelisted.booleanValue();
3246 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3247 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003248 final int length = mListeners.beginBroadcast();
3249 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003250 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003251 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3252 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003253 }
3254 mListeners.finishBroadcast();
3255 }
Felipe Leme9778f762016-01-27 14:46:39 -08003256 final PackageManager pm = mContext.getPackageManager();
3257 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003258 if (changed && packages != null) {
3259 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003260 final int userId = UserHandle.getUserId(uid);
3261 for (String packageName : packages) {
3262 final Intent intent = new Intent(
3263 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3264 intent.setPackage(packageName);
3265 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3266 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3267 }
Felipe Leme9778f762016-01-27 14:46:39 -08003268 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003269 return true;
3270 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003271 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3272 final int uid = msg.arg1;
3273 final boolean blacklisted = msg.arg2 == 1;
3274
3275 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3276 blacklisted);
3277 final int length = mListeners.beginBroadcast();
3278 for (int i = 0; i < length; i++) {
3279 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3280 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3281 blacklisted);
3282 }
3283 mListeners.finishBroadcast();
3284 return true;
3285 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003286 case MSG_ADVISE_PERSIST_THRESHOLD: {
3287 final long lowestRule = (Long) msg.obj;
3288 try {
3289 // make sure stats are recorded frequently enough; we aim
3290 // for 2MB threshold for 2GB/month rules.
3291 final long persistThreshold = lowestRule / 1000;
3292 mNetworkStats.advisePersistThreshold(persistThreshold);
3293 } catch (RemoteException e) {
3294 // ignored; service lives in system_server
3295 }
3296 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003297 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003298 case MSG_UPDATE_INTERFACE_QUOTA: {
3299 removeInterfaceQuota((String) msg.obj);
3300 // int params need to be stitched back into a long
3301 setInterfaceQuota((String) msg.obj,
3302 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3303 return true;
3304 }
3305 case MSG_REMOVE_INTERFACE_QUOTA: {
3306 removeInterfaceQuota((String) msg.obj);
3307 return true;
3308 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003309 default: {
3310 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003311 }
3312 }
3313 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003314 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003315
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003316 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003317 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003318 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003319 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003320 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003321 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003322 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003323 }
3324 }
3325
3326 private void removeInterfaceQuota(String iface) {
3327 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003328 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003329 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003330 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003331 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003332 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003333 }
3334 }
3335
Felipe Leme70c57c22016-03-29 10:45:13 -07003336 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3337 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003338 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003339 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003340 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003341 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3342 } catch (RemoteException e) {
3343 // ignored; service lives in system_server
3344 }
3345 }
3346
3347 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3348 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3349 try {
3350 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3351 } catch (IllegalStateException e) {
3352 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003353 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003354 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003355 }
3356 }
3357
Amith Yamasani15e472352015-04-24 19:06:07 -07003358 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003359 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3360 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3361 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003362 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003363 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003364 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003365 int size = uidRules.size();
3366 int[] uids = new int[size];
3367 int[] rules = new int[size];
3368 for(int index = size - 1; index >= 0; --index) {
3369 uids[index] = uidRules.keyAt(index);
3370 rules[index] = uidRules.valueAt(index);
3371 }
3372 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003373 } catch (IllegalStateException e) {
3374 Log.wtf(TAG, "problem setting firewall uid rules", e);
3375 } catch (RemoteException e) {
3376 // ignored; service lives in system_server
3377 }
3378 }
3379
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003380 /**
3381 * Add or remove a uid to the firewall blacklist for all network ifaces.
3382 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003383 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003384 if (chain == FIREWALL_CHAIN_DOZABLE) {
3385 mUidFirewallDozableRules.put(uid, rule);
3386 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3387 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003388 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3389 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003390 }
3391
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003392 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003393 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003394 } catch (IllegalStateException e) {
3395 Log.wtf(TAG, "problem setting firewall uid rules", e);
3396 } catch (RemoteException e) {
3397 // ignored; service lives in system_server
3398 }
3399 }
3400
3401 /**
3402 * Add or remove a uid to the firewall blacklist for all network ifaces.
3403 */
Felipe Lemef0823852016-06-08 13:43:08 -07003404 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003405 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3406 mFirewallChainStates.get(chain) == enable) {
3407 // All is the same, nothing to do.
3408 return;
3409 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003410 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003411 try {
3412 mNetworkManager.setFirewallChainEnabled(chain, enable);
3413 } catch (IllegalStateException e) {
3414 Log.wtf(TAG, "problem enable firewall chain", e);
3415 } catch (RemoteException e) {
3416 // ignored; service lives in system_server
3417 }
3418 }
3419
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003420 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3421 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003422 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003423 } catch (RuntimeException e) {
3424 Slog.w(TAG, "problem reading network stats: " + e);
3425 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003426 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003427 // ignored; service lives in system_server
3428 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003429 }
3430 }
3431
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003432 private boolean isBandwidthControlEnabled() {
3433 final long token = Binder.clearCallingIdentity();
3434 try {
3435 return mNetworkManager.isBandwidthControlEnabled();
3436 } catch (RemoteException e) {
3437 // ignored; service lives in system_server
3438 return false;
3439 } finally {
3440 Binder.restoreCallingIdentity(token);
3441 }
3442 }
3443
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003444 /**
3445 * Try refreshing {@link #mTime} when stale.
3446 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003447 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003448 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003449 mTime.forceRefresh();
3450 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003451 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003452
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003453 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003454 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3455 }
3456
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003457 private static Intent buildAllowBackgroundDataIntent() {
3458 return new Intent(ACTION_ALLOW_BACKGROUND);
3459 }
3460
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003461 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3462 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3463 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3464 return intent;
3465 }
3466
Wei Liu546cb772016-07-21 16:19:01 -07003467 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003468 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003469 intent.setComponent(ComponentName.unflattenFromString(
3470 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003471 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3472 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3473 return intent;
3474 }
3475
Wei Liu546cb772016-07-21 16:19:01 -07003476 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003477 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003478 intent.setComponent(ComponentName.unflattenFromString(
3479 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003480 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3481 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3482 return intent;
3483 }
3484
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003485 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003486 public void addIdleHandler(IdleHandler handler) {
3487 mHandler.getLooper().getQueue().addIdleHandler(handler);
3488 }
3489
Jeff Sharkey1b861272011-05-22 00:34:52 -07003490 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3491 final int size = source.size();
3492 for (int i = 0; i < size; i++) {
3493 target.put(source.keyAt(i), true);
3494 }
3495 }
3496
Stuart Scottf1fb3972015-04-02 18:00:02 -07003497 @Override
3498 public void factoryReset(String subscriber) {
3499 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3500
Stuart Scotte3e314d2015-04-20 14:07:45 -07003501 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3502 return;
3503 }
3504
Stuart Scottf1fb3972015-04-02 18:00:02 -07003505 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003506 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003507 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3508 for (NetworkPolicy policy : policies) {
3509 if (policy.template.equals(template)) {
3510 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3511 policy.inferred = false;
3512 policy.clearSnooze();
3513 }
3514 }
3515 setNetworkPolicies(policies);
3516
3517 // Turn restrict background data off
3518 setRestrictBackground(false);
3519
Stuart Scotte3e314d2015-04-20 14:07:45 -07003520 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3521 // Remove app's "restrict background data" flag
3522 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3523 setUidPolicy(uid, POLICY_NONE);
3524 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003525 }
3526 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003527
3528 private class MyPackageMonitor extends PackageMonitor {
3529
3530 @Override
3531 public void onPackageRemoved(String packageName, int uid) {
3532 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003533 synchronized (mUidRulesFirstLock) {
3534 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3535 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003536 }
3537 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003538 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003539
3540 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3541
3542 @Override
3543 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003544 synchronized (mUidRulesFirstLock) {
3545 boolean changed = removeUserStateUL(userId, false);
3546 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003547 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003548 synchronized (mNetworkPoliciesSecondLock) {
3549 writePolicyAL();
3550 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003551 }
3552 }
3553 }
3554 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003555}