blob: 7545959fcce538c32ad018859a22082be12d819c [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;
Felipe Leme84d39732016-09-08 13:26:55 -070093import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070094import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070096import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070099import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.Notification;
101import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700102import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700103import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700104import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700106import android.content.Intent;
107import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700109import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700111import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700112import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700113import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700116import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700119import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700122import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700124import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700125import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700127import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiConfiguration;
129import android.net.wifi.WifiInfo;
130import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700131import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700132import android.os.Environment;
133import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700134import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700136import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700137import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700138import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700141import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700142import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600143import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.ServiceManager;
Felipe Leme873a83a2016-09-07 11:34:10 -0700145import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700146import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700147import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700148import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800149import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700150import android.telephony.TelephonyManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700151import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700152import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700153import android.util.ArrayMap;
154import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700155import android.util.AtomicFile;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700156import android.util.DebugUtils;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700157import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700159import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700160import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161import android.util.SparseBooleanArray;
162import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.TrustedTime;
164import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165
Jeff Sharkey497e4432011-06-14 17:27:29 -0700166import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700167import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800168import com.android.internal.annotations.VisibleForTesting;
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;
Felipe Leme84d39732016-09-08 13:26:55 -0700293 private static final int MSG_SET_FIREWALL_RULES = 13;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700294
Jeff Sharkey75279902011-05-24 18:39:45 -0700295 private final Context mContext;
296 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700297 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700298 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700299 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700300 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700301 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302
303 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700304 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700305 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700306 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700307
Felipe Lemef0823852016-06-08 13:43:08 -0700308 // See main javadoc for instructions on how to use these locks.
309 final Object mUidRulesFirstLock = new Object();
310 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700311
Felipe Lemef0823852016-06-08 13:43:08 -0700312 @GuardedBy("allLocks") volatile boolean mSystemReady;
313
Felipe Lemef0823852016-06-08 13:43:08 -0700314 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
315 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
316 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700317
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700318 private final boolean mSuppressDefaultPolicy;
319
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700320 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800321 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700322 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800323 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700324
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700325 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700326 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700327 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700328 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700329
Felipe Lemef0823852016-06-08 13:43:08 -0700330 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700331 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700332 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700333 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700334 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800335 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700336
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700337 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700338 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700339 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
340
Jeff Sharkey32566012014-12-02 18:30:14 -0800341 /**
342 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700343 * in power save mode, except device idle (doze) still applies.
344 * TODO: An int array might be sufficient
345 */
Felipe Lemef0823852016-06-08 13:43:08 -0700346 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700347 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
348
349 /**
350 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800351 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700352 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800353 */
Felipe Lemef0823852016-06-08 13:43:08 -0700354 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700355 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700356
Felipe Lemef0823852016-06-08 13:43:08 -0700357 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700358 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
359
Felipe Lemeb85a6372016-01-14 16:16:16 -0800360 /**
361 * UIDs that have been white-listed to avoid restricted background.
362 */
Felipe Lemef0823852016-06-08 13:43:08 -0700363 @GuardedBy("mUidRulesFirstLock")
Felipe Lemeb85a6372016-01-14 16:16:16 -0800364 private final SparseBooleanArray mRestrictBackgroundWhitelistUids = new SparseBooleanArray();
365
Felipe Lemea9505cc2016-02-26 10:28:41 -0800366 /**
367 * UIDs that have been initially white-listed by system to avoid restricted background.
368 */
Felipe Lemef0823852016-06-08 13:43:08 -0700369 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800370 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
371 new SparseBooleanArray();
372
373 /**
374 * UIDs that have been initially white-listed by system to avoid restricted background,
375 * but later revoked by user.
376 */
Felipe Lemef0823852016-06-08 13:43:08 -0700377 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800378 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
379 new SparseBooleanArray();
380
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700381 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700382 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800383 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700384 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800386 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700387
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700388 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700390 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700391
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700392 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700393 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800394 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700395
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600396 /** Higher priority listener before general event dispatch */
397 private INetworkPolicyListener mConnectivityListener;
398
Jeff Sharkey32566012014-12-02 18:30:14 -0800399 private final RemoteCallbackList<INetworkPolicyListener>
400 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700401
Dianne Hackborn497175b2014-07-01 12:56:08 -0700402 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700403
Felipe Lemef0823852016-06-08 13:43:08 -0700404 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700405 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700406
Svet Ganov16a16892015-04-16 10:32:04 -0700407 private final AppOpsManager mAppOps;
408
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 Lemef8dd7b42016-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 Lemef8dd7b42016-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
Felipe Lemed17fda42016-04-29 11:12:45 -0700450 // Expose private service for system components to use.
451 LocalServices.addService(NetworkPolicyManagerInternal.class,
452 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700453 }
454
455 public void bindConnectivityManager(IConnectivityManager connManager) {
456 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700457 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700458
Jeff Sharkey497e4432011-06-14 17:27:29 -0700459 public void bindNotificationManager(INotificationManager notifManager) {
460 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
461 }
462
Felipe Lemef0823852016-06-08 13:43:08 -0700463 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700464 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700465 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
466 mPowerSaveWhitelistExceptIdleAppIds.clear();
467 if (whitelist != null) {
468 for (int uid : whitelist) {
469 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
470 }
471 }
472 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700473 mPowerSaveWhitelistAppIds.clear();
474 if (whitelist != null) {
475 for (int uid : whitelist) {
476 mPowerSaveWhitelistAppIds.put(uid, true);
477 }
478 }
479 } catch (RemoteException e) {
480 }
481 }
482
Felipe Lemea9505cc2016-02-26 10:28:41 -0800483 /**
484 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
485 * revoke the whitelist.
486 *
487 * @return whether any uid has been added to {@link #mRestrictBackgroundWhitelistUids}.
488 */
Felipe Lemef0823852016-06-08 13:43:08 -0700489 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800490 final List<UserInfo> users = mUserManager.getUsers();
491 final int numberUsers = users.size();
492
Felipe Lemea110eec2016-04-29 09:58:06 -0700493 boolean changed = false;
494 for (int i = 0; i < numberUsers; i++) {
495 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700496 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700497 }
498 return changed;
499 }
500
Felipe Lemef0823852016-06-08 13:43:08 -0700501 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700502 final SystemConfig sysConfig = SystemConfig.getInstance();
503 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800504 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
505 boolean changed = false;
506 for (int i = 0; i < allowDataUsage.size(); i++) {
507 final String pkg = allowDataUsage.valueAt(i);
508 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700509 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
510 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800511 final ApplicationInfo app;
512 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700513 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800514 } catch (PackageManager.NameNotFoundException e) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700515 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
516 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800517 continue;
518 }
519 if (!app.isPrivilegedApp()) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700520 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
521 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800522 continue;
523 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700524 final int uid = UserHandle.getUid(userId, app.uid);
525 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
526 if (LOGD)
527 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
528 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800529 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700530 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Leme6fa02e92016-08-31 08:47:50 -0700531 if (LOGD)
532 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
533 + userId + ") to restrict background whitelist");
Felipe Lemea110eec2016-04-29 09:58:06 -0700534 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() {
Felipe Leme873a83a2016-09-07 11:34:10 -0700572 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
573 try {
574 if (!isBandwidthControlEnabled()) {
575 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
576 return;
577 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700578
Felipe Leme873a83a2016-09-07 11:34:10 -0700579 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700580
Felipe Leme873a83a2016-09-07 11:34:10 -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 }
Felipe Lemef0823852016-06-08 13:43:08 -0700595 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700596 }
Felipe Leme873a83a2016-09-07 11:34:10 -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 Lemef0823852016-06-08 13:43:08 -0700608
Felipe Leme873a83a2016-09-07 11:34:10 -0700609 setRestrictBackgroundUL(mRestrictBackground);
610 updateRulesForGlobalChangeAL(false);
611 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700612 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800613 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700614
615 try {
616 mActivityManager.registerUidObserver(mUidObserver,
617 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
618 mNetworkManager.registerObserver(mAlertObserver);
619 } catch (RemoteException e) {
620 // ignored; both services live in system_server
621 }
622
623 // 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
628 DeviceIdleController.LocalService deviceIdleService
629 = LocalServices.getService(DeviceIdleController.LocalService.class);
630 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
631
632 // watch for network interfaces to be claimed
633 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
634 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
635
636 // listen for package changes to update policy
637 final IntentFilter packageFilter = new IntentFilter();
638 packageFilter.addAction(ACTION_PACKAGE_ADDED);
639 packageFilter.addDataScheme("package");
640 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
641
642 // 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
652 // listen for stats update events
653 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
654 mContext.registerReceiver(
655 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
656
657 // 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
661 // 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
666 // listen for configured wifi networks to be removed
667 final IntentFilter wifiConfigFilter =
668 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
669 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
670
671 // listen for wifi state changes to catch metered hint
672 final IntentFilter wifiStateFilter = new IntentFilter(
673 WifiManager.NETWORK_STATE_CHANGED_ACTION);
674 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
675
676 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
677 } finally {
678 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700679 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700680 }
681
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700682 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700683 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700684 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
685 try {
686 synchronized (mUidRulesFirstLock) {
687 updateUidStateUL(uid, procState);
688 }
689 } finally {
690 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700691 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700692 }
693
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700694 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700695 synchronized (mUidRulesFirstLock) {
696 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700697 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700698 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700699
700 @Override public void onUidActive(int uid) throws RemoteException {
701 }
702
703 @Override public void onUidIdle(int uid) throws RemoteException {
704 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700705 };
706
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700707 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700708 @Override
709 public void onReceive(Context context, Intent intent) {
710 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700711 synchronized (mUidRulesFirstLock) {
712 updatePowerSaveWhitelistUL();
713 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700714 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700715 }
716 }
717 };
718
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700719 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
720 @Override
721 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700722 synchronized (mUidRulesFirstLock) {
723 updatePowerSaveTempWhitelistUL();
724 updateRulesForTempWhitelistChangeUL();
725 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700726 }
727 }
728 };
729
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700730 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700731 @Override
732 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700733 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700734
735 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700736 final int uid = intent.getIntExtra(EXTRA_UID, -1);
737 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700738
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700739 if (ACTION_PACKAGE_ADDED.equals(action)) {
740 // update rules for UID, since it might be subject to
741 // global background data policy
742 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700743 synchronized (mUidRulesFirstLock) {
744 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700745 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700746 }
747 }
748 };
749
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700750 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700751 @Override
752 public void onReceive(Context context, Intent intent) {
753 // on background handler thread, and UID_REMOVED is protected
754
755 final int uid = intent.getIntExtra(EXTRA_UID, -1);
756 if (uid == -1) return;
757
758 // remove any policy and update rules to clean up
759 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700760 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700761 mUidPolicy.delete(uid);
Felipe Lemef1da90f2016-09-08 17:26:00 -0700762 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -0700763 updateRestrictionRulesForUidUL(uid);
764 synchronized (mNetworkPoliciesSecondLock) {
765 writePolicyAL();
766 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700767 }
768 }
769 };
770
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700771 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700772 @Override
773 public void onReceive(Context context, Intent intent) {
774 // on background handler thread, and USER_ADDED and USER_REMOVED
775 // broadcasts are protected
776
777 final String action = intent.getAction();
778 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
779 if (userId == -1) return;
780
Amith Yamasani15e472352015-04-24 19:06:07 -0700781 switch (action) {
782 case ACTION_USER_REMOVED:
783 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700784 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800785 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700786 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700787 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700788 if (action == ACTION_USER_ADDED) {
789 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700790 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700791 }
792 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700793 synchronized (mNetworkPoliciesSecondLock) {
794 updateRulesForGlobalChangeAL(true);
795 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700796 }
797 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700798 }
799 }
800 };
801
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700802 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700803 * Receiver that watches for {@link INetworkStatsService} updates, which we
804 * use to check against {@link NetworkPolicy#warningBytes}.
805 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700806 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700807 @Override
808 public void onReceive(Context context, Intent intent) {
809 // on background handler thread, and verified
810 // READ_NETWORK_USAGE_HISTORY permission above.
811
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800812 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700813 synchronized (mNetworkPoliciesSecondLock) {
814 updateNetworkEnabledNL();
815 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700816 }
817 }
818 };
819
820 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700821 * Receiver that watches for {@link Notification} control of
822 * {@link #mRestrictBackground}.
823 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700824 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700825 @Override
826 public void onReceive(Context context, Intent intent) {
827 // on background handler thread, and verified MANAGE_NETWORK_POLICY
828 // permission above.
829
830 setRestrictBackground(false);
831 }
832 };
833
834 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800835 * Receiver that watches for {@link Notification} control of
836 * {@link NetworkPolicy#lastWarningSnooze}.
837 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700838 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800839 @Override
840 public void onReceive(Context context, Intent intent) {
841 // on background handler thread, and verified MANAGE_NETWORK_POLICY
842 // permission above.
843
844 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
845 performSnooze(template, TYPE_WARNING);
846 }
847 };
848
849 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700850 * Receiver that watches for {@link WifiConfiguration} to be changed.
851 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700852 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700853 @Override
854 public void onReceive(Context context, Intent intent) {
855 // on background handler thread, and verified CONNECTIVITY_INTERNAL
856 // permission above.
857
858 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
859 if (reason == CHANGE_REASON_REMOVED) {
860 final WifiConfiguration config = intent.getParcelableExtra(
861 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700862 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800863 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700864 synchronized (mUidRulesFirstLock) {
865 synchronized (mNetworkPoliciesSecondLock) {
866 if (mNetworkPolicy.containsKey(template)) {
867 mNetworkPolicy.remove(template);
868 writePolicyAL();
869 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700870 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700871 }
872 }
873 }
874 }
875 };
876
877 /**
878 * Receiver that watches {@link WifiInfo} state changes to infer metered
879 * state. Ignores hints when policy is user-defined.
880 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700881 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700882 @Override
883 public void onReceive(Context context, Intent intent) {
884 // on background handler thread, and verified CONNECTIVITY_INTERNAL
885 // permission above.
886
887 // ignore when not connected
888 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
889 if (!netInfo.isConnected()) return;
890
891 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
892 final boolean meteredHint = info.getMeteredHint();
893
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800894 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700895 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700896 NetworkPolicy policy = mNetworkPolicy.get(template);
897 if (policy == null && meteredHint) {
898 // policy doesn't exist, and AP is hinting that it's
899 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800900 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700901 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700902
903 } else if (policy != null && policy.inferred) {
904 // policy exists, and was inferred: update its current
905 // metered state.
906 policy.metered = meteredHint;
907
908 // since this is inferred for each wifi session, just update
909 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700910 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700911 }
912 }
913 }
914 };
915
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800916 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
917 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
918 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
919 metered, true);
920 }
921
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700922 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700923 * Observer that watches for {@link INetworkManagementService} alerts.
924 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700925 final private INetworkManagementEventObserver mAlertObserver
926 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700927 @Override
928 public void limitReached(String limitName, String iface) {
929 // only someone like NMS should be calling us
930 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
931
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800932 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
933 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700934 }
935 }
936 };
937
938 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700939 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
940 * to show visible notifications as needed.
941 */
Felipe Lemef0823852016-06-08 13:43:08 -0700942 void updateNotificationsNL() {
943 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700944
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700945 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700946 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948
949 // TODO: when switching to kernel notifications, compute next future
950 // cycle boundary to recompute notifications.
951
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700952 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800953 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700954 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
955 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700956 // ignore policies that aren't relevant to user
957 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700958 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700959
Jeff Sharkey497e4432011-06-14 17:27:29 -0700960 final long start = computeLastCycleBoundary(currentTime, policy);
961 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700962 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700964 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800965 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700966 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
967 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700968 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700969 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700970 }
971
Jeff Sharkey497e4432011-06-14 17:27:29 -0700972 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700973 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700974
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800975 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700976 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700977 }
978 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700979 }
980
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700981 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700982 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
983 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700984 if (!mActiveNotifs.contains(tag)) {
985 cancelNotification(tag);
986 }
987 }
988 }
989
990 /**
991 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700992 * current device state, such as when
993 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
994 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700995 */
996 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800997 if (template.isMatchRuleMobile()) {
998 final TelephonyManager tele = TelephonyManager.from(mContext);
999 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001000
Jeff Sharkey32566012014-12-02 18:30:14 -08001001 // Mobile template is relevant when any active subscriber matches
1002 final int[] subIds = sub.getActiveSubscriptionIdList();
1003 for (int subId : subIds) {
1004 final String subscriberId = tele.getSubscriberId(subId);
1005 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001006 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001007 if (template.matches(probeIdent)) {
1008 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001009 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001010 }
1011 return false;
1012 } else {
1013 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001014 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001015 }
1016
1017 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001018 * Notify that given {@link NetworkTemplate} is over
1019 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1020 */
Felipe Lemef0823852016-06-08 13:43:08 -07001021 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001023 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001024 mOverLimitNotified.add(template);
1025 }
1026 }
1027
Felipe Lemef0823852016-06-08 13:43:08 -07001028 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001029 mOverLimitNotified.remove(template);
1030 }
1031
1032 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001033 * Build unique tag that identifies an active {@link NetworkPolicy}
1034 * notification of a specific type, like {@link #TYPE_LIMIT}.
1035 */
1036 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001037 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 }
1039
1040 /**
1041 * Show notification for combined {@link NetworkPolicy} and specific type,
1042 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1043 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045 final String tag = buildNotificationTag(policy, type);
1046 final Notification.Builder builder = new Notification.Builder(mContext);
1047 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001048 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001049 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001050 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001051
1052 final Resources res = mContext.getResources();
1053 switch (type) {
1054 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001055 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Jeff Sharkey8ca953d2011-09-14 19:56:11 -07001056 final CharSequence body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001058 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059 builder.setTicker(title);
1060 builder.setContentTitle(title);
1061 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001062 builder.setDefaults(Notification.DEFAULT_ALL);
1063 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001064
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001065 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1066 builder.setDeleteIntent(PendingIntent.getBroadcast(
1067 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1068
Wei Liu546cb772016-07-21 16:19:01 -07001069 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001070 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001071 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1072
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 break;
1074 }
1075 case TYPE_LIMIT: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 final CharSequence body = res.getText(R.string.data_usage_limit_body);
1077
1078 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001079 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001080 switch (policy.template.getMatchRule()) {
1081 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001082 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001084 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001085 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001087 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001088 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001090 case MATCH_WIFI:
1091 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001092 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001093 break;
1094 default:
1095 title = null;
1096 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001097 }
1098
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001099 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001100 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001101 builder.setTicker(title);
1102 builder.setContentTitle(title);
1103 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001104
Wei Liu546cb772016-07-21 16:19:01 -07001105 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001106 builder.setContentIntent(PendingIntent.getActivity(
1107 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1108 break;
1109 }
1110 case TYPE_LIMIT_SNOOZED: {
1111 final long overBytes = totalBytes - policy.limitBytes;
1112 final CharSequence body = res.getString(R.string.data_usage_limit_snoozed_body,
1113 Formatter.formatFileSize(mContext, overBytes));
1114
1115 final CharSequence title;
1116 switch (policy.template.getMatchRule()) {
1117 case MATCH_MOBILE_3G_LOWER:
1118 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1119 break;
1120 case MATCH_MOBILE_4G:
1121 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1122 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001123 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001124 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1125 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001126 case MATCH_WIFI:
1127 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1128 break;
1129 default:
1130 title = null;
1131 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001132 }
1133
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001134 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001135 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001136 builder.setTicker(title);
1137 builder.setContentTitle(title);
1138 builder.setContentText(body);
1139
Wei Liu546cb772016-07-21 16:19:01 -07001140 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001141 builder.setContentIntent(PendingIntent.getActivity(
1142 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001143 break;
1144 }
1145 }
1146
1147 // TODO: move to NotificationManager once we can mock it
1148 try {
1149 final String packageName = mContext.getPackageName();
1150 final int[] idReceived = new int[1];
1151 mNotifManager.enqueueNotificationWithTag(
Dianne Hackbornf265ea92013-01-31 15:00:51 -08001152 packageName, packageName, tag, 0x0, builder.getNotification(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001153 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001154 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001155 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001156 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001157 }
1158 }
1159
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001160 private void cancelNotification(String tag) {
1161 // TODO: move to NotificationManager once we can mock it
1162 try {
1163 final String packageName = mContext.getPackageName();
1164 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001165 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001166 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001167 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 }
1169 }
1170
1171 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001172 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001173 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001174 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001175 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001176 @Override
1177 public void onReceive(Context context, Intent intent) {
1178 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1179 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001180
1181 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001182 synchronized (mNetworkPoliciesSecondLock) {
1183 ensureActiveMobilePolicyNL();
1184 normalizePoliciesNL();
1185 updateNetworkEnabledNL();
1186 updateNetworkRulesNL();
1187 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001188 }
1189 }
1190 };
1191
1192 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001193 * Proactively control network data connections when they exceed
1194 * {@link NetworkPolicy#limitBytes}.
1195 */
Felipe Lemef0823852016-06-08 13:43:08 -07001196 void updateNetworkEnabledNL() {
1197 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198
1199 // TODO: reset any policy-disabled networks when any policy is removed
1200 // completely, which is currently rare case.
1201
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001202 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001203 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1204 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001205 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001206 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001207 setNetworkTemplateEnabled(policy.template, true);
1208 continue;
1209 }
1210
1211 final long start = computeLastCycleBoundary(currentTime, policy);
1212 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001213 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001214
1215 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001216 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1217 && policy.lastLimitSnooze < start;
1218 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001219
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001220 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001221 }
1222 }
1223
1224 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001225 * Proactively disable networks that match the given
1226 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227 */
1228 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001229 // TODO: reach into ConnectivityManager to proactively disable bringing
1230 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001231
1232 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1233 // If mobile data usage hits the limit or if the user resumes the data, we need to
1234 // notify telephony.
1235 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1236 final TelephonyManager tm = TelephonyManager.from(mContext);
1237
1238 final int[] subIds = sm.getActiveSubscriptionIdList();
1239 for (int subId : subIds) {
1240 final String subscriberId = tm.getSubscriberId(subId);
1241 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1242 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1243 // Template is matched when subscriber id matches.
1244 if (template.matches(probeIdent)) {
1245 tm.setPolicyDataEnabled(enabled, subId);
1246 }
1247 }
1248 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001249 }
1250
1251 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001252 * Examine all connected {@link NetworkState}, looking for
1253 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1254 * remaining quota based on usage cycle and historical stats.
1255 */
Felipe Lemef0823852016-06-08 13:43:08 -07001256 void updateNetworkRulesNL() {
1257 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001258
1259 final NetworkState[] states;
1260 try {
1261 states = mConnManager.getAllNetworkState();
1262 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001263 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 return;
1265 }
1266
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001267 // First, generate identities of all connected networks so we can
1268 // quickly compare them against all defined policies below.
1269 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001270 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001272 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001273 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001274
1275 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001276 if (baseIface != null) {
1277 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001278 }
1279
1280 // Stacked interfaces are considered to have same identity as
1281 // their parent network.
1282 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1283 for (LinkProperties stackedLink : stackedLinks) {
1284 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001285 if (stackedIface != null) {
1286 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001287 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001288 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 }
1290 }
1291
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001292 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001293 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001294 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001295 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001296 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001298 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001299 for (int j = connIdents.size() - 1; j >= 0; j--) {
1300 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1301 if (policy.template.matches(ident.second)) {
1302 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 }
1304 }
1305
1306 if (ifaceList.size() > 0) {
1307 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001308 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001309 }
1310 }
1311
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001312 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001313 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001314
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001315 // apply each policy that we found ifaces for; compute remaining data
1316 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001317 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001318 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1319 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1320 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001322 final long start;
1323 final long totalBytes;
1324 if (policy.hasCycle()) {
1325 start = computeLastCycleBoundary(currentTime, policy);
1326 totalBytes = getTotalBytes(policy.template, start, currentTime);
1327 } else {
1328 start = Long.MAX_VALUE;
1329 totalBytes = 0;
1330 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001331
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001333 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001334 }
1335
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001336 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001337 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001338 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001339 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001340 if (!hasLimit) {
1341 // metered network, but no policy limit; we still need to
1342 // restrict apps, so push really high quota.
1343 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001344 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001345 // snoozing past quota, but we still need to restrict apps,
1346 // so push really high quota.
1347 quotaBytes = Long.MAX_VALUE;
1348 } else {
1349 // remaining "quota" bytes are based on total usage in
1350 // current cycle. kernel doesn't like 0-byte rules, so we
1351 // set 1-byte quota and disable the radio later.
1352 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1353 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001354
1355 if (ifaces.length > 1) {
1356 // TODO: switch to shared quota once NMS supports
1357 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001358 }
1359
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001360 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001361 // long quotaBytes split up into two ints to fit in message
1362 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1363 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1364 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001365 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001366 }
1367 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001368
1369 // keep track of lowest warning or limit of active policies
1370 if (hasWarning && policy.warningBytes < lowestRule) {
1371 lowestRule = policy.warningBytes;
1372 }
1373 if (hasLimit && policy.limitBytes < lowestRule) {
1374 lowestRule = policy.limitBytes;
1375 }
1376 }
1377
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001378 for (int i = connIfaces.size()-1; i >= 0; i--) {
1379 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001380 // long quotaBytes split up into two ints to fit in message
1381 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1382 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1383 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001384 newMeteredIfaces.add(iface);
1385 }
1386
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001387 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001389 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001390 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1391 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001392 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001393 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1394 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001395 }
1396 }
1397 mMeteredIfaces = newMeteredIfaces;
1398
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001399 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001400 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001401 }
1402
1403 /**
1404 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1405 * have at least a default mobile policy defined.
1406 */
Felipe Lemef0823852016-06-08 13:43:08 -07001407 private void ensureActiveMobilePolicyNL() {
1408 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001409 if (mSuppressDefaultPolicy) return;
1410
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001411 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001412 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001413
Jeff Sharkey32566012014-12-02 18:30:14 -08001414 final int[] subIds = sub.getActiveSubscriptionIdList();
1415 for (int subId : subIds) {
1416 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001417 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001418 }
1419 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001420
Felipe Lemef0823852016-06-08 13:43:08 -07001421 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001422 // Poke around to see if we already have a policy
1423 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001424 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001425 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1426 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1427 if (template.matches(probeIdent)) {
1428 if (LOGD) {
1429 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1430 + NetworkIdentity.scrubSubscriberId(subscriberId));
1431 }
1432 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001433 }
1434 }
1435
Jeff Sharkey32566012014-12-02 18:30:14 -08001436 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1437 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001438
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001440 final int dataWarningConfig = mContext.getResources().getInteger(
1441 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1442 final long warningBytes;
1443 if (dataWarningConfig == WARNING_DISABLED) {
1444 warningBytes = WARNING_DISABLED;
1445 } else {
1446 warningBytes = dataWarningConfig * MB_IN_BYTES;
1447 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001448
Jeff Sharkey32566012014-12-02 18:30:14 -08001449 final Time time = new Time();
1450 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001451
Jeff Sharkey32566012014-12-02 18:30:14 -08001452 final int cycleDay = time.monthDay;
1453 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001454
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1456 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1457 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001458 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001459 }
1460
Felipe Lemef0823852016-06-08 13:43:08 -07001461 private void readPolicyAL() {
1462 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001463
1464 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001465 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001466 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001467
1468 FileInputStream fis = null;
1469 try {
1470 fis = mPolicyFile.openRead();
1471 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001472 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473
1474 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001475 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001476 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001477 while ((type = in.next()) != END_DOCUMENT) {
1478 final String tag = in.getName();
1479 if (type == START_TAG) {
1480 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001481 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001482 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001483 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1484 mRestrictBackground = readBooleanAttribute(
1485 in, ATTR_RESTRICT_BACKGROUND);
1486 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001487 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001488 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001489 if (mRestrictBackground != oldValue) {
1490 // Some early services may have read the default value,
1491 // so notify them that it's changed
1492 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1493 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1494 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001495
1496 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1497 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1498 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001499 final String networkId;
1500 if (version >= VERSION_ADDED_NETWORK_ID) {
1501 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1502 } else {
1503 networkId = null;
1504 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001506 final String cycleTimezone;
1507 if (version >= VERSION_ADDED_TIMEZONE) {
1508 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1509 } else {
1510 cycleTimezone = Time.TIMEZONE_UTC;
1511 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1513 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001514 final long lastLimitSnooze;
1515 if (version >= VERSION_SPLIT_SNOOZE) {
1516 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1517 } else if (version >= VERSION_ADDED_SNOOZE) {
1518 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001519 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001520 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001521 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001522 final boolean metered;
1523 if (version >= VERSION_ADDED_METERED) {
1524 metered = readBooleanAttribute(in, ATTR_METERED);
1525 } else {
1526 switch (networkTemplate) {
1527 case MATCH_MOBILE_3G_LOWER:
1528 case MATCH_MOBILE_4G:
1529 case MATCH_MOBILE_ALL:
1530 metered = true;
1531 break;
1532 default:
1533 metered = false;
1534 }
1535 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001536 final long lastWarningSnooze;
1537 if (version >= VERSION_SPLIT_SNOOZE) {
1538 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1539 } else {
1540 lastWarningSnooze = SNOOZE_NEVER;
1541 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001542 final boolean inferred;
1543 if (version >= VERSION_ADDED_INFERRED) {
1544 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1545 } else {
1546 inferred = false;
1547 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548
Jeff Sharkey32566012014-12-02 18:30:14 -08001549 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1550 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001551 if (template.isPersistable()) {
1552 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1553 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1554 lastLimitSnooze, metered, inferred));
1555 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001556
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001557 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001558 final int uid = readIntAttribute(in, ATTR_UID);
1559 final int policy = readIntAttribute(in, ATTR_POLICY);
1560
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001562 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001563 } else {
1564 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1565 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001566 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001567 final int appId = readIntAttribute(in, ATTR_APP_ID);
1568 final int policy = readIntAttribute(in, ATTR_POLICY);
1569
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001570 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001571 // app policy is deprecated so this is only used in pre system user split.
1572 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001573 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001574 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001575 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001576 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001577 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001578 } else if (TAG_WHITELIST.equals(tag)) {
1579 insideWhitelist = true;
1580 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1581 final int uid = readIntAttribute(in, ATTR_UID);
1582 mRestrictBackgroundWhitelistUids.put(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001583 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1584 final int uid = readIntAttribute(in, ATTR_UID);
1585 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001587 } else if (type == END_TAG) {
1588 if (TAG_WHITELIST.equals(tag)) {
1589 insideWhitelist = false;
1590 }
1591
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001592 }
1593 }
1594
1595 } catch (FileNotFoundException e) {
1596 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001597 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001598 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001599 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001600 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001601 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001602 } finally {
1603 IoUtils.closeQuietly(fis);
1604 }
1605 }
1606
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001607 /**
1608 * Upgrade legacy background data flags, notifying listeners of one last
1609 * change to always-true.
1610 */
Felipe Lemef0823852016-06-08 13:43:08 -07001611 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001612 mRestrictBackground = Settings.Secure.getInt(
1613 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1614
1615 // kick off one last broadcast if restricted
1616 if (mRestrictBackground) {
1617 final Intent broadcast = new Intent(
1618 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001619 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001620 }
1621 }
1622
Felipe Lemef0823852016-06-08 13:43:08 -07001623 void writePolicyAL() {
1624 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625
1626 FileOutputStream fos = null;
1627 try {
1628 fos = mPolicyFile.startWrite();
1629
1630 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001631 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001632 out.startDocument(null, true);
1633
1634 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001635 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001636 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001637
1638 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001639 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1640 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001641 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001642 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001643
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001645 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1646 final String subscriberId = template.getSubscriberId();
1647 if (subscriberId != null) {
1648 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001650 final String networkId = template.getNetworkId();
1651 if (networkId != null) {
1652 out.attribute(null, ATTR_NETWORK_ID, networkId);
1653 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001655 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1657 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001658 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1659 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001660 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001661 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001662 out.endTag(null, TAG_NETWORK_POLICY);
1663 }
1664
1665 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001666 for (int i = 0; i < mUidPolicy.size(); i++) {
1667 final int uid = mUidPolicy.keyAt(i);
1668 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669
Jeff Sharkey497e4432011-06-14 17:27:29 -07001670 // skip writing empty policies
1671 if (policy == POLICY_NONE) continue;
1672
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001673 out.startTag(null, TAG_UID_POLICY);
1674 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001675 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001676 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677 }
1678
1679 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001680
1681 // write all whitelists
1682 out.startTag(null, TAG_WHITELIST);
1683
1684 // restrict background whitelist
Felipe Lemea9505cc2016-02-26 10:28:41 -08001685 int size = mRestrictBackgroundWhitelistUids.size();
Felipe Lemeb85a6372016-01-14 16:16:16 -08001686 for (int i = 0; i < size; i++) {
1687 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1688 out.startTag(null, TAG_RESTRICT_BACKGROUND);
1689 writeIntAttribute(out, ATTR_UID, uid);
1690 out.endTag(null, TAG_RESTRICT_BACKGROUND);
1691 }
1692
Felipe Lemea9505cc2016-02-26 10:28:41 -08001693 // revoked restrict background whitelist
1694 size = mRestrictBackgroundWhitelistRevokedUids.size();
1695 for (int i = 0; i < size; i++) {
1696 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1697 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1698 writeIntAttribute(out, ATTR_UID, uid);
1699 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1700 }
1701
Felipe Lemeb85a6372016-01-14 16:16:16 -08001702 out.endTag(null, TAG_WHITELIST);
1703
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001704 out.endDocument();
1705
1706 mPolicyFile.finishWrite(fos);
1707 } catch (IOException e) {
1708 if (fos != null) {
1709 mPolicyFile.failWrite(fos);
1710 }
1711 }
1712 }
1713
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001714 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001715 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001717
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001718 if (!UserHandle.isApp(uid)) {
1719 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001720 }
Felipe Lemef0823852016-06-08 13:43:08 -07001721 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001722 final long token = Binder.clearCallingIdentity();
1723 try {
1724 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1725 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001726 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001727 }
1728 } finally {
1729 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001730 }
1731 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001732 }
1733
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001734 @Override
1735 public void addUidPolicy(int uid, int policy) {
1736 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001737
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001738 if (!UserHandle.isApp(uid)) {
1739 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1740 }
1741
Felipe Lemef0823852016-06-08 13:43:08 -07001742 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001743 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1744 policy |= oldPolicy;
1745 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001746 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001747 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001748 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001749 }
1750
1751 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001752 public void removeUidPolicy(int uid, int policy) {
1753 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1754
1755 if (!UserHandle.isApp(uid)) {
1756 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1757 }
1758
Felipe Lemef0823852016-06-08 13:43:08 -07001759 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001760 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1761 policy = oldPolicy & ~policy;
1762 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001763 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001764 }
1765 }
1766 }
1767
Felipe Lemef0823852016-06-08 13:43:08 -07001768 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1769 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001770
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001771 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1772 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1773 isBlacklisted ? 1 : 0).sendToTarget();
1774
1775 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001776 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001777 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1778 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001779 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001780 .sendToTarget();
1781 }
1782 }
1783
Felipe Lemef0823852016-06-08 13:43:08 -07001784 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001785 mUidPolicy.put(uid, policy);
1786
1787 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001788 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001789 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001790 synchronized (mNetworkPoliciesSecondLock) {
1791 writePolicyAL();
1792 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001793 }
1794 }
1795
1796 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001797 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001798 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1799
Felipe Lemef0823852016-06-08 13:43:08 -07001800 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001801 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001802 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001803 }
1804
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001805 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001806 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001807 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1808
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001809 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001810 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001811 for (int i = 0; i < mUidPolicy.size(); i++) {
1812 final int uid = mUidPolicy.keyAt(i);
1813 final int uidPolicy = mUidPolicy.valueAt(i);
1814 if (uidPolicy == policy) {
1815 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001816 }
1817 }
1818 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001819 return uids;
1820 }
1821
1822 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001823 * Removes any persistable state associated with given {@link UserHandle}, persisting
1824 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001825 */
Felipe Lemef0823852016-06-08 13:43:08 -07001826 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001827
Felipe Lemef0823852016-06-08 13:43:08 -07001828 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001829 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001830
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001831 // Remove entries from restricted background UID whitelist
1832 int[] wlUids = new int[0];
1833 for (int i = 0; i < mRestrictBackgroundWhitelistUids.size(); i++) {
1834 final int uid = mRestrictBackgroundWhitelistUids.keyAt(i);
1835 if (UserHandle.getUserId(uid) == userId) {
1836 wlUids = appendInt(wlUids, uid);
1837 }
1838 }
1839
1840 if (wlUids.length > 0) {
1841 for (int uid : wlUids) {
Felipe Lemef0823852016-06-08 13:43:08 -07001842 removeRestrictBackgroundWhitelistedUidUL(uid, false, false);
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001843 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001844 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001845 }
Felipe Lemea110eec2016-04-29 09:58:06 -07001846
1847 // Remove entries from revoked default restricted background UID whitelist
1848 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1849 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1850 if (UserHandle.getUserId(uid) == userId) {
1851 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001852 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001853 }
1854 }
1855
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001856 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001857 int[] uids = new int[0];
1858 for (int i = 0; i < mUidPolicy.size(); i++) {
1859 final int uid = mUidPolicy.keyAt(i);
1860 if (UserHandle.getUserId(uid) == userId) {
1861 uids = appendInt(uids, uid);
1862 }
1863 }
1864
1865 if (uids.length > 0) {
1866 for (int uid : uids) {
1867 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001868 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001869 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001870 }
Felipe Lemef0823852016-06-08 13:43:08 -07001871 synchronized (mNetworkPoliciesSecondLock) {
1872 updateRulesForGlobalChangeAL(true);
1873 if (writePolicy && changed) {
1874 writePolicyAL();
1875 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001876 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001877 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001878 }
1879
1880 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001881 public void setConnectivityListener(INetworkPolicyListener listener) {
1882 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1883 if (mConnectivityListener != null) {
1884 throw new IllegalStateException("Connectivity listener already registered");
1885 }
1886 mConnectivityListener = listener;
1887 }
1888
1889 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001890 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001891 // TODO: create permission for observing network policy
1892 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001893 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001894 }
1895
1896 @Override
1897 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001898 // TODO: create permission for observing network policy
1899 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001900 mListeners.unregister(listener);
1901 }
1902
Jeff Sharkey1b861272011-05-22 00:34:52 -07001903 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001904 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001905 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1906
Felipe Leme6a05eee2016-02-19 14:43:51 -08001907 final long token = Binder.clearCallingIdentity();
1908 try {
1909 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001910 synchronized (mUidRulesFirstLock) {
1911 synchronized (mNetworkPoliciesSecondLock) {
1912 normalizePoliciesNL(policies);
1913 updateNetworkEnabledNL();
1914 updateNetworkRulesNL();
1915 updateNotificationsNL();
1916 writePolicyAL();
1917 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001918 }
1919 } finally {
1920 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001921 }
1922 }
1923
Felipe Lemef0823852016-06-08 13:43:08 -07001924 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001925 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001926 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1927 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001928 }
1929
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001930 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001931 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001932 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001933 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001934 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1935 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1936 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001937 } catch (SecurityException e) {
1938 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001940 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1941 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1942 return new NetworkPolicy[0];
1943 }
Svet Ganov16a16892015-04-16 10:32:04 -07001944 }
1945
Felipe Lemef0823852016-06-08 13:43:08 -07001946 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001947 final int size = mNetworkPolicy.size();
1948 final NetworkPolicy[] policies = new NetworkPolicy[size];
1949 for (int i = 0; i < size; i++) {
1950 policies[i] = mNetworkPolicy.valueAt(i);
1951 }
1952 return policies;
1953 }
1954 }
1955
Felipe Lemef0823852016-06-08 13:43:08 -07001956 private void normalizePoliciesNL() {
1957 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001958 }
1959
Felipe Lemef0823852016-06-08 13:43:08 -07001960 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001961 final TelephonyManager tele = TelephonyManager.from(mContext);
1962 final String[] merged = tele.getMergedSubscriberIds();
1963
1964 mNetworkPolicy.clear();
1965 for (NetworkPolicy policy : policies) {
1966 // When two normalized templates conflict, prefer the most
1967 // restrictive policy
1968 policy.template = NetworkTemplate.normalize(policy.template, merged);
1969 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1970 if (existing == null || existing.compareTo(policy) > 0) {
1971 if (existing != null) {
1972 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1973 }
1974 mNetworkPolicy.put(policy.template, policy);
1975 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001976 }
1977 }
1978
1979 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001980 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001981 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001982
1983 final long token = Binder.clearCallingIdentity();
1984 try {
1985 performSnooze(template, TYPE_LIMIT);
1986 } finally {
1987 Binder.restoreCallingIdentity(token);
1988 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001989 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001990
Dianne Hackborn497175b2014-07-01 12:56:08 -07001991 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001992 maybeRefreshTrustedTime();
1993 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001994 synchronized (mUidRulesFirstLock) {
1995 synchronized (mNetworkPoliciesSecondLock) {
1996 // find and snooze local policy that matches
1997 final NetworkPolicy policy = mNetworkPolicy.get(template);
1998 if (policy == null) {
1999 throw new IllegalArgumentException("unable to find policy for " + template);
2000 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002001
Felipe Lemef0823852016-06-08 13:43:08 -07002002 switch (type) {
2003 case TYPE_WARNING:
2004 policy.lastWarningSnooze = currentTime;
2005 break;
2006 case TYPE_LIMIT:
2007 policy.lastLimitSnooze = currentTime;
2008 break;
2009 default:
2010 throw new IllegalArgumentException("unexpected type");
2011 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002012
Felipe Lemef0823852016-06-08 13:43:08 -07002013 normalizePoliciesNL();
2014 updateNetworkEnabledNL();
2015 updateNetworkRulesNL();
2016 updateNotificationsNL();
2017 writePolicyAL();
2018 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002019 }
2020 }
2021
2022 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002023 public void onTetheringChanged(String iface, boolean tethering) {
2024 // No need to enforce permission because setRestrictBackground() will do it.
2025 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002026 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002027 if (mRestrictBackground && tethering) {
2028 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2029 setRestrictBackground(false);
2030 }
2031 }
2032 }
2033
2034 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002035 public void setRestrictBackground(boolean restrictBackground) {
2036 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002037 final long token = Binder.clearCallingIdentity();
2038 try {
2039 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002040 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002041 if (restrictBackground == mRestrictBackground) {
2042 // Ideally, UI should never allow this scenario...
2043 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2044 return;
2045 }
Felipe Lemef0823852016-06-08 13:43:08 -07002046 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002047 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002048
Felipe Leme6a05eee2016-02-19 14:43:51 -08002049 } finally {
2050 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002051 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002052
2053 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2054 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002055 }
2056
Felipe Lemef0823852016-06-08 13:43:08 -07002057 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Lemea1540892016-06-21 13:08:55 -07002058 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002059 final boolean oldRestrictBackground = mRestrictBackground;
2060 mRestrictBackground = restrictBackground;
2061 // Must whitelist foreground apps before turning data saver mode on.
2062 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2063 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002064 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002065 try {
2066 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2067 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2068 mRestrictBackground = oldRestrictBackground;
2069 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002070 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002071 return;
2072 }
2073 } catch (RemoteException e) {
2074 // ignored; service lives in system_server
2075 }
Felipe Lemef0823852016-06-08 13:43:08 -07002076 synchronized (mNetworkPoliciesSecondLock) {
2077 updateNotificationsNL();
2078 writePolicyAL();
2079 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002080 }
2081
Jeff Sharkey46645002011-07-27 21:11:21 -07002082 @Override
Felipe Lemeb85a6372016-01-14 16:16:16 -08002083 public void addRestrictBackgroundWhitelistedUid(int uid) {
2084 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002085 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002086 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002087 int changed;
2088 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002089 oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002090 if (oldStatus) {
2091 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2092 return;
2093 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002094 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002095 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Lemeb85a6372016-01-14 16:16:16 -08002096 mRestrictBackgroundWhitelistUids.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002097 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2098 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2099 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2100 + " from revoked restrict background whitelist");
2101 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2102 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002103 if (needFirewallRules) {
2104 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002105 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002106 }
2107 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002108 synchronized (mNetworkPoliciesSecondLock) {
2109 writePolicyAL();
2110 }
2111 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002112 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002113 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2114 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002115 }
2116
2117 @Override
2118 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2119 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002120 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002121 synchronized (mUidRulesFirstLock) {
2122 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002123 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002124 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2125 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002126 }
2127
Felipe Leme70c57c22016-03-29 10:45:13 -07002128 /**
2129 * Removes a uid from the restricted background whitelist, returning whether its current
2130 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2131 */
Felipe Lemef0823852016-06-08 13:43:08 -07002132 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002133 boolean updateNow) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002134 final boolean oldStatus = mRestrictBackgroundWhitelistUids.get(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002135 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002136 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2137 return false;
2138 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002139 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002140 if (oldStatus) {
2141 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
2142 mRestrictBackgroundWhitelistUids.delete(uid);
2143 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002144 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2145 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2146 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2147 + " to revoked restrict background whitelist");
2148 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2149 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002150 if (needFirewallRules) {
2151 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002152 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002153 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002154 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002155 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002156 synchronized (mNetworkPoliciesSecondLock) {
2157 writePolicyAL();
2158 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002159 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002160 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2161 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002162 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002163 }
2164
2165 @Override
2166 public int[] getRestrictBackgroundWhitelistedUids() {
2167 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Lemef0823852016-06-08 13:43:08 -07002168 synchronized (mUidRulesFirstLock) {
Felipe Lemeb85a6372016-01-14 16:16:16 -08002169 final int size = mRestrictBackgroundWhitelistUids.size();
2170 final int[] whitelist = new int[size];
2171 for (int i = 0; i < size; i++) {
2172 whitelist[i] = mRestrictBackgroundWhitelistUids.keyAt(i);
2173 }
2174 if (LOGV) {
2175 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2176 + mRestrictBackgroundWhitelistUids);
2177 }
2178 return whitelist;
2179 }
2180 }
2181
2182 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002183 public int getRestrictBackgroundByCaller() {
2184 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2185 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002186
Felipe Lemef0823852016-06-08 13:43:08 -07002187 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002188 // Must clear identity because getUidPolicy() is restricted to system.
2189 final long token = Binder.clearCallingIdentity();
2190 final int policy;
2191 try {
2192 policy = getUidPolicy(uid);
2193 } finally {
2194 Binder.restoreCallingIdentity(token);
2195 }
2196 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2197 // App is blacklisted.
2198 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2199 }
Felipe Leme1b103232016-01-22 09:44:57 -08002200 if (!mRestrictBackground) {
2201 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2202 }
2203 return mRestrictBackgroundWhitelistUids.get(uid)
2204 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2205 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2206 }
2207 }
2208
2209 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002210 public boolean getRestrictBackground() {
2211 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2212
Felipe Lemef0823852016-06-08 13:43:08 -07002213 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002214 return mRestrictBackground;
2215 }
2216 }
2217
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002218 @Override
2219 public void setDeviceIdleMode(boolean enabled) {
2220 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002221 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2222 try {
2223 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002224 if (mDeviceIdleMode == enabled) {
2225 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002226 }
Felipe Lemeea014392016-09-06 13:59:54 -07002227 mDeviceIdleMode = enabled;
2228 if (mSystemReady) {
2229 // Device idle change means we need to rebuild rules for all
2230 // known apps, so do a global refresh.
2231 updateRulesForRestrictPowerUL();
2232 }
2233 }
2234 if (enabled) {
2235 EventLogTags.writeDeviceIdleOnPhase("net");
2236 } else {
2237 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002238 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002239 } finally {
2240 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002241 }
2242 }
2243
Felipe Lemef0823852016-06-08 13:43:08 -07002244 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002245 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2246 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002247 if (policy.template.matches(ident)) {
2248 return policy;
2249 }
2250 }
2251 return null;
2252 }
2253
2254 @Override
2255 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2256 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2257
2258 // only returns usage summary, so we don't require caller to have
2259 // READ_NETWORK_USAGE_HISTORY.
2260 final long token = Binder.clearCallingIdentity();
2261 try {
2262 return getNetworkQuotaInfoUnchecked(state);
2263 } finally {
2264 Binder.restoreCallingIdentity(token);
2265 }
2266 }
2267
2268 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2269 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2270
2271 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002272 synchronized (mNetworkPoliciesSecondLock) {
2273 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002274 }
2275
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002276 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002277 // missing policy means we can't derive useful quota info
2278 return null;
2279 }
2280
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002281 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002282
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002283 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002284 final long start = computeLastCycleBoundary(currentTime, policy);
2285 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002286 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002287
2288 // report soft and hard limits under policy
2289 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2290 : NetworkQuotaInfo.NO_LIMIT;
2291 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2292 : NetworkQuotaInfo.NO_LIMIT;
2293
2294 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2295 }
2296
Jeff Sharkey46645002011-07-27 21:11:21 -07002297 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002298 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002299 if (state.networkInfo == null) {
2300 return false;
2301 }
2302
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002303 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2304
2305 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002306 synchronized (mNetworkPoliciesSecondLock) {
2307 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002308 }
2309
2310 if (policy != null) {
2311 return policy.metered;
2312 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002313 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002314 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002315 return true;
2316 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002317 return false;
2318 }
2319 }
2320
2321 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002322 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002323 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002324
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002325 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2326
Dianne Hackborn497175b2014-07-01 12:56:08 -07002327 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002328 for (String arg : args) {
2329 argSet.add(arg);
2330 }
2331
Felipe Lemef0823852016-06-08 13:43:08 -07002332 synchronized (mUidRulesFirstLock) {
2333 synchronized (mNetworkPoliciesSecondLock) {
2334 if (argSet.contains("--unsnooze")) {
2335 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2336 mNetworkPolicy.valueAt(i).clearSnooze();
2337 }
2338
2339 normalizePoliciesNL();
2340 updateNetworkEnabledNL();
2341 updateNetworkRulesNL();
2342 updateNotificationsNL();
2343 writePolicyAL();
2344
2345 fout.println("Cleared snooze timestamps");
2346 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002347 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002348
Felipe Lemef0823852016-06-08 13:43:08 -07002349 fout.print("System ready: "); fout.println(mSystemReady);
2350 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2351 fout.print("Restrict power: "); fout.println(mRestrictPower);
2352 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2353 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002354 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002355 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2356 fout.println(mNetworkPolicy.valueAt(i).toString());
2357 }
2358 fout.decreaseIndent();
2359
2360 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2361
2362 fout.println("Policy for UIDs:");
2363 fout.increaseIndent();
2364 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002365 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002366 final int uid = mUidPolicy.keyAt(i);
2367 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002368 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002369 fout.print(uid);
2370 fout.print(" policy=");
2371 fout.print(DebugUtils.flagsToString(NetworkPolicyManager.class, "POLICY_", policy));
2372 fout.println();
2373 }
2374 fout.decreaseIndent();
2375
2376 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2377 if (size > 0) {
2378 fout.println("Power save whitelist (except idle) app ids:");
2379 fout.increaseIndent();
2380 for (int i = 0; i < size; i++) {
2381 fout.print("UID=");
2382 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2383 fout.print(": ");
2384 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2385 fout.println();
2386 }
2387 fout.decreaseIndent();
2388 }
2389
2390 size = mPowerSaveWhitelistAppIds.size();
2391 if (size > 0) {
2392 fout.println("Power save whitelist app ids:");
2393 fout.increaseIndent();
2394 for (int i = 0; i < size; i++) {
2395 fout.print("UID=");
2396 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2397 fout.print(": ");
2398 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2399 fout.println();
2400 }
2401 fout.decreaseIndent();
2402 }
2403
2404 size = mRestrictBackgroundWhitelistUids.size();
2405 if (size > 0) {
2406 fout.println("Restrict background whitelist uids:");
2407 fout.increaseIndent();
2408 for (int i = 0; i < size; i++) {
2409 fout.print("UID=");
2410 fout.print(mRestrictBackgroundWhitelistUids.keyAt(i));
2411 fout.println();
2412 }
2413 fout.decreaseIndent();
2414 }
2415
2416 size = mDefaultRestrictBackgroundWhitelistUids.size();
2417 if (size > 0) {
2418 fout.println("Default restrict background whitelist uids:");
2419 fout.increaseIndent();
2420 for (int i = 0; i < size; i++) {
2421 fout.print("UID=");
2422 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2423 fout.println();
2424 }
2425 fout.decreaseIndent();
2426 }
2427
2428 size = mRestrictBackgroundWhitelistRevokedUids.size();
2429 if (size > 0) {
2430 fout.println("Default restrict background whitelist uids revoked by users:");
2431 fout.increaseIndent();
2432 for (int i = 0; i < size; i++) {
2433 fout.print("UID=");
2434 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2435 fout.println();
2436 }
2437 fout.decreaseIndent();
2438 }
2439
2440 final SparseBooleanArray knownUids = new SparseBooleanArray();
2441 collectKeys(mUidState, knownUids);
2442 collectKeys(mUidRules, knownUids);
2443
2444 fout.println("Status for all known UIDs:");
2445 fout.increaseIndent();
2446 size = knownUids.size();
2447 for (int i = 0; i < size; i++) {
2448 final int uid = knownUids.keyAt(i);
2449 fout.print("UID=");
2450 fout.print(uid);
2451
2452 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2453 fout.print(" state=");
2454 fout.print(state);
2455 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2456 fout.print(" (fg)");
2457 } else {
2458 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2459 ? " (fg svc)" : " (bg)");
2460 }
2461
2462 final int uidRules = mUidRules.get(uid, RULE_NONE);
2463 fout.print(" rules=");
2464 fout.print(uidRulesToString(uidRules));
2465 fout.println();
2466 }
2467 fout.decreaseIndent();
2468
2469 fout.println("Status for just UIDs with rules:");
2470 fout.increaseIndent();
2471 size = mUidRules.size();
2472 for (int i = 0; i < size; i++) {
2473 final int uid = mUidRules.keyAt(i);
2474 fout.print("UID=");
2475 fout.print(uid);
2476 final int uidRules = mUidRules.get(uid, RULE_NONE);
2477 fout.print(" rules=");
2478 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002479 fout.println();
2480 }
2481 fout.decreaseIndent();
2482 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002483 }
2484 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002485
2486 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002487 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2488 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002489 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002490 this, in, out, err, args, resultReceiver);
2491 }
2492
2493 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002494 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002495 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2496
Felipe Lemef0823852016-06-08 13:43:08 -07002497 synchronized (mUidRulesFirstLock) {
2498 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002499 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002500 }
2501
Felipe Lemef0823852016-06-08 13:43:08 -07002502 private boolean isUidForegroundUL(int uid) {
2503 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002504 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2505 }
2506
Felipe Lemef0823852016-06-08 13:43:08 -07002507 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002508 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002509 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002510 }
2511
Felipe Lemef0823852016-06-08 13:43:08 -07002512 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002513 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2514 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2515 }
2516
Felipe Lemef0823852016-06-08 13:43:08 -07002517 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002518 // only really in foreground when screen is also on
Felipe Lemef8dd7b42016-08-10 13:00:32 -07002519 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002520 }
2521
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002522 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002523 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002524 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2525 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002526 */
Felipe Lemef0823852016-06-08 13:43:08 -07002527 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002528 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2529 try {
2530 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2531 if (oldUidState != uidState) {
2532 // state changed, push updated rules
2533 mUidState.put(uid, uidState);
2534 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2535 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2536 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2537 if (isUidIdle(uid)) {
2538 updateRuleForAppIdleUL(uid);
2539 }
2540 if (mDeviceIdleMode) {
2541 updateRuleForDeviceIdleUL(uid);
2542 }
2543 if (mRestrictPower) {
2544 updateRuleForRestrictPowerUL(uid);
2545 }
2546 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002547 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002548 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002549 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002550 } finally {
2551 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002552 }
2553 }
2554
Felipe Lemef0823852016-06-08 13:43:08 -07002555 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002556 final int index = mUidState.indexOfKey(uid);
2557 if (index >= 0) {
2558 final int oldUidState = mUidState.valueAt(index);
2559 mUidState.removeAt(index);
2560 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002561 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002562 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002563 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002564 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002565 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002566 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002567 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002568 }
Felipe Lemef0823852016-06-08 13:43:08 -07002569 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002570 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002571 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002572 }
2573 }
2574
Felipe Lemef28983d2016-03-25 12:18:23 -07002575 // adjust stats accounting based on foreground status
2576 private void updateNetworkStats(int uid, boolean uidForeground) {
2577 try {
2578 mNetworkStats.setUidForeground(uid, uidForeground);
2579 } catch (RemoteException e) {
2580 // ignored; service lives in system_server
2581 }
2582 }
2583
Felipe Lemef0823852016-06-08 13:43:08 -07002584 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002585 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002586 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002587 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002588 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002589 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002590 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002591 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002592 }
2593 }
2594
Felipe Leme011b98f2016-02-10 17:28:31 -08002595 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002596 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2597 }
2598
Felipe Lemef0823852016-06-08 13:43:08 -07002599 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002600 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2601 }
2602
Felipe Lemef0823852016-06-08 13:43:08 -07002603 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002604 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2605 try {
2606 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2607 mUidFirewallPowerSaveRules);
2608 } finally {
2609 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2610 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002611 }
2612
Felipe Lemef0823852016-06-08 13:43:08 -07002613 void updateRuleForRestrictPowerUL(int uid) {
2614 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002615 }
2616
Felipe Lemef0823852016-06-08 13:43:08 -07002617 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002618 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2619 try {
2620 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2621 mUidFirewallDozableRules);
2622 } finally {
2623 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2624 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002625 }
2626
Felipe Lemef0823852016-06-08 13:43:08 -07002627 void updateRuleForDeviceIdleUL(int uid) {
2628 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002629 }
2630
Felipe Lemef28983d2016-03-25 12:18:23 -07002631 // NOTE: since both fw_dozable and fw_powersave uses the same map
2632 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002633 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002634 SparseIntArray rules) {
2635 if (enabled) {
2636 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002637 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002638 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002639 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002640 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002641 for (int ui = users.size() - 1; ui >= 0; ui--) {
2642 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002643 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002644 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2645 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2646 int uid = UserHandle.getUid(user.id, appId);
2647 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2648 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002649 }
2650 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2651 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2652 int uid = UserHandle.getUid(user.id, appId);
2653 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2654 }
2655 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002656 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002657 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002658 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2659 }
2660 }
Felipe Leme84d39732016-09-08 13:26:55 -07002661 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2662 } else {
2663 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002664 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002665 }
2666
Felipe Lemef0823852016-06-08 13:43:08 -07002667 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002668 final int appId = UserHandle.getAppId(uid);
2669 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2670 }
2671
Felipe Lemef28983d2016-03-25 12:18:23 -07002672 // NOTE: since both fw_dozable and fw_powersave uses the same map
2673 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002674 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002675 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002676 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002677 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2678 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002679 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002680 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002681 }
2682 }
2683 }
2684
Felipe Lemef0823852016-06-08 13:43:08 -07002685 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002686 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2687 try {
2688 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2689 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002690
Felipe Leme873a83a2016-09-07 11:34:10 -07002691 // Fully update the app idle firewall chain.
2692 final List<UserInfo> users = mUserManager.getUsers();
2693 for (int ui = users.size() - 1; ui >= 0; ui--) {
2694 UserInfo user = users.get(ui);
2695 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2696 for (int uid : idleUids) {
2697 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2698 // quick check: if this uid doesn't have INTERNET permission, it
2699 // doesn't have network access anyway, so it is a waste to mess
2700 // with it here.
2701 if (hasInternetPermissions(uid)) {
2702 uidRules.put(uid, FIREWALL_RULE_DENY);
2703 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002704 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002705 }
2706 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002707
Felipe Leme84d39732016-09-08 13:26:55 -07002708 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002709 } finally {
2710 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2711 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002712 }
2713
Felipe Lemef0823852016-06-08 13:43:08 -07002714 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002715 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002716
2717 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002718 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002719 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002720 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2721 } else {
2722 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2723 }
2724 }
2725
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002726 /**
2727 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2728 * changed.
2729 */
Felipe Lemef0823852016-06-08 13:43:08 -07002730 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002731 boolean paroled = mUsageStats.isAppIdleParoleOn();
2732 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002733 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002734
2735 int ruleCount = mUidFirewallStandbyRules.size();
2736 for (int i = 0; i < ruleCount; i++) {
2737 int uid = mUidFirewallStandbyRules.keyAt(i);
2738 int oldRules = mUidRules.get(uid);
2739 if (enableChain) {
2740 // Chain wasn't enabled before and the other power-related
2741 // chains are whitelists, so we can clear the
2742 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2743 // the effective rules result in blocking network access.
2744 oldRules &= MASK_METERED_NETWORKS;
2745 } else {
2746 // Skip if it had no restrictions to begin with
2747 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2748 }
2749 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
2750 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002751 }
2752
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002753 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002754 * Update rules that might be changed by {@link #mRestrictBackground},
2755 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002756 */
Felipe Lemef0823852016-06-08 13:43:08 -07002757 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002758 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2759 try {
Felipe Leme09700462016-09-08 09:33:48 -07002760 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002761 updateRulesForRestrictPowerUL();
2762 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002763
Felipe Leme873a83a2016-09-07 11:34:10 -07002764 // If the set of restricted networks may have changed, re-evaluate those.
2765 if (restrictedNetworksChanged) {
2766 normalizePoliciesNL();
2767 updateNetworkRulesNL();
2768 }
2769 } finally {
2770 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002771 }
2772 }
2773
Felipe Leme09700462016-09-08 09:33:48 -07002774 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002775 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002776 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2777 try {
2778 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002779 updateRulesForPowerSaveUL();
2780 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2781 } finally {
2782 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2783 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002784 }
2785
Felipe Lemef0823852016-06-08 13:43:08 -07002786 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002787 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2788 try {
2789 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2790 } finally {
2791 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2792 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002793 }
2794
2795 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2796 private static final int TYPE_RESTRICT_POWER = 2;
2797 @Retention(RetentionPolicy.SOURCE)
2798 @IntDef(flag = false, value = {
2799 TYPE_RESTRICT_BACKGROUND,
2800 TYPE_RESTRICT_POWER,
2801 })
2802 public @interface RestrictType {
2803 }
2804
2805 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002806 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002807 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2808 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2809 }
2810 try {
2811 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002812
Felipe Leme873a83a2016-09-07 11:34:10 -07002813 // update rules for all installed applications
2814 final List<UserInfo> users = mUserManager.getUsers();
2815 final List<ApplicationInfo> apps = pm.getInstalledApplications(
2816 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2817 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2818 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002819
Felipe Leme873a83a2016-09-07 11:34:10 -07002820 final int usersSize = users.size();
2821 final int appsSize = apps.size();
2822 for (int i = 0; i < usersSize; i++) {
2823 final UserInfo user = users.get(i);
2824 for (int j = 0; j < appsSize; j++) {
2825 final ApplicationInfo app = apps.get(j);
2826 final int uid = UserHandle.getUid(user.id, app.uid);
2827 switch (type) {
2828 case TYPE_RESTRICT_BACKGROUND:
2829 updateRulesForDataUsageRestrictionsUL(uid);
2830 break;
2831 case TYPE_RESTRICT_POWER:
2832 updateRulesForPowerRestrictionsUL(uid);
2833 break;
2834 default:
2835 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2836 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002837 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002838 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002839 } finally {
2840 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2841 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2842 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002843 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002844 }
2845
Felipe Lemef0823852016-06-08 13:43:08 -07002846 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002847 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002848 for (int i = 0; i < users.size(); i++) {
2849 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002850 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002851 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002852 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002853 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002854 updateRuleForAppIdleUL(uid);
2855 updateRuleForDeviceIdleUL(uid);
2856 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002857 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002858 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002859 }
2860 }
2861 }
2862
Felipe Leme70c57c22016-03-29 10:45:13 -07002863 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2864 // methods below could be merged into a isUidValidForRules() method.
2865 private boolean isUidValidForBlacklistRules(int uid) {
2866 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002867 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002868 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002869 return true;
2870 }
2871
2872 return false;
2873 }
2874
Felipe Leme70c57c22016-03-29 10:45:13 -07002875 private boolean isUidValidForWhitelistRules(int uid) {
2876 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2877 }
2878
Amith Yamasani15e472352015-04-24 19:06:07 -07002879 private boolean isUidIdle(int uid) {
2880 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2881 final int userId = UserHandle.getUserId(uid);
2882
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002883 if (!ArrayUtils.isEmpty(packages)) {
2884 for (String packageName : packages) {
2885 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2886 return false;
2887 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002888 }
2889 }
2890 return true;
2891 }
2892
2893 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002894 * Checks if an uid has INTERNET permissions.
2895 * <p>
2896 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002897 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002898 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002899 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002900 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002901 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002902 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002903 }
2904 } catch (RemoteException e) {
2905 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002906 return true;
2907 }
2908
2909 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002910 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002911 *
Felipe Leme781ba142016-05-09 16:24:48 -07002912 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002913 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002914 * <li>Doze mode
2915 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002916 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002917 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002918 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002919 *
2920 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002921 */
Felipe Lemef0823852016-06-08 13:43:08 -07002922 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002923 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002924 updateRuleForDeviceIdleUL(uid);
2925 updateRuleForAppIdleUL(uid);
2926 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002927
2928 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002929 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002930
2931 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002932 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002933 }
2934
Felipe Leme70c57c22016-03-29 10:45:13 -07002935 /**
2936 * Applies network rules to bandwidth controllers based on process state and user-defined
2937 * restrictions (blacklist / whitelist).
2938 *
2939 * <p>
2940 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2941 * networks:
2942 * <ul>
2943 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2944 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2945 * also blacklisted.
2946 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2947 * no UIDs other those whitelisted will have access.
2948 * <ul>
2949 *
2950 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2951 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2952 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2953 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002954 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002955 * {@link INetworkManagementService}, but this method should also be called in events (like
2956 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2957 * following rules should also be applied:
2958 *
2959 * <ul>
2960 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2961 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2962 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2963 * {@code bw_penalty_box}.
2964 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2965 * </ul>
2966 *
2967 * <p>For optimization, the rules are only applied on user apps that have internet access
2968 * permission, since there is no need to change the {@code iptables} rule if the app does not
2969 * have permission to use the internet.
2970 *
2971 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002972 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002973 */
Felipe Lemef0823852016-06-08 13:43:08 -07002974 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2975 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002976 }
2977
2978 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002979 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002980 * app is removed - it ignores the UID validity check.
2981 */
Felipe Lemef0823852016-06-08 13:43:08 -07002982 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002983 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2984 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2985 return;
2986 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002987
Dianne Hackborn497175b2014-07-01 12:56:08 -07002988 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002989 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002990 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002991
Felipe Leme781ba142016-05-09 16:24:48 -07002992 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
2993 final boolean isWhitelisted = mRestrictBackgroundWhitelistUids.get(uid);
2994 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2995 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002996
Felipe Leme70c57c22016-03-29 10:45:13 -07002997 // First step: define the new rule based on user restrictions and foreground state.
2998 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002999 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3000 newRule = RULE_TEMPORARY_ALLOW_METERED;
3001 } else if (isWhitelisted) {
3002 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003003 }
3004 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003005 if (isBlacklisted) {
3006 newRule = RULE_REJECT_METERED;
3007 } else if (mRestrictBackground && isWhitelisted) {
3008 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003009 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003010 }
Felipe Leme781ba142016-05-09 16:24:48 -07003011 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003012
Felipe Lemef28983d2016-03-25 12:18:23 -07003013 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003014 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003015 + ": isForeground=" +isForeground
3016 + ", isBlacklisted=" + isBlacklisted
3017 + ", isWhitelisted=" + isWhitelisted
3018 + ", oldRule=" + uidRulesToString(oldRule)
3019 + ", newRule=" + uidRulesToString(newRule)
3020 + ", newUidRules=" + uidRulesToString(newUidRules)
3021 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003022 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003023
Felipe Leme46c4fc32016-05-04 09:21:43 -07003024 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003025 mUidRules.delete(uid);
3026 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003027 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003028 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003029
Felipe Leme70c57c22016-03-29 10:45:13 -07003030 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003031 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07003032 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003033 // Temporarily whitelist foreground app, removing from blacklist if necessary
3034 // (since bw_penalty_box prevails over bw_happy_box).
3035
3036 setMeteredNetworkWhitelist(uid, true);
3037 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3038 // but ideally it should be just:
3039 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003040 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003041 setMeteredNetworkBlacklist(uid, false);
3042 }
Felipe Leme781ba142016-05-09 16:24:48 -07003043 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003044 // Remove temporary whitelist from app that is not on foreground anymore.
3045
3046 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3047 // but ideally they should be just:
3048 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3049 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003050 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003051 setMeteredNetworkWhitelist(uid, false);
3052 }
Felipe Leme781ba142016-05-09 16:24:48 -07003053 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003054 setMeteredNetworkBlacklist(uid, true);
3055 }
Felipe Leme781ba142016-05-09 16:24:48 -07003056 } else if ((newRule & RULE_REJECT_METERED) != 0
3057 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003058 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003059 setMeteredNetworkBlacklist(uid, isBlacklisted);
3060 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003061 // Since blacklist prevails over whitelist, we need to handle the special case
3062 // where app is whitelisted and blacklisted at the same time (although such
3063 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003064 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003065 }
Felipe Leme781ba142016-05-09 16:24:48 -07003066 } else if ((newRule & RULE_ALLOW_METERED) != 0
3067 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003068 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003069 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003070 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003071 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003072 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3073 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003074 + ", whitelisted=" + isWhitelisted
3075 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003076 + ", newRule=" + uidRulesToString(newUidRules)
3077 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003078 }
Felipe Leme781ba142016-05-09 16:24:48 -07003079
3080 // Dispatch changed rule to existing listeners.
3081 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3082 }
3083 }
3084
3085 /**
3086 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3087 * listeners in case of change.
3088 * <p>
3089 * There are 3 power-related rules that affects whether an app has background access on
3090 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3091 * restriction, it's added to the equivalent firewall chain:
3092 * <ul>
3093 * <li>App is idle: {@code fw_standby} firewall chain.
3094 * <li>Device is idle: {@code fw_dozable} firewall chain.
3095 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3096 * </ul>
3097 * <p>
3098 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3099 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3100 * <p>
3101 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3102 */
Felipe Lemef0823852016-06-08 13:43:08 -07003103 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003104 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3105
3106 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
3107
3108 if (newUidRules == RULE_NONE) {
3109 mUidRules.delete(uid);
3110 } else {
3111 mUidRules.put(uid, newUidRules);
3112 }
3113 }
3114
3115 /**
3116 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3117 *
3118 * @param uid the uid of the app to update rules for
3119 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3120 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3121 *
3122 * @return the new computed rules for the uid
3123 */
3124 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003125 if (!isUidValidForBlacklistRules(uid)) {
3126 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003127 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003128 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003129
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003130 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003131 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003132 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003133
Felipe Lemef0823852016-06-08 13:43:08 -07003134 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003135 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3136 int newRule = RULE_NONE;
3137
3138 // First step: define the new rule based on user restrictions and foreground state.
3139
3140 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3141 // by considering the foreground and non-foreground states.
3142 if (isForeground) {
3143 if (restrictMode) {
3144 newRule = RULE_ALLOW_ALL;
3145 }
3146 } else if (restrictMode) {
3147 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3148 }
3149
3150 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3151
3152 if (LOGV) {
Felipe Lemef8dd7b42016-08-10 13:00:32 -07003153 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003154 + ", isIdle: " + isIdle
3155 + ", mRestrictPower: " + mRestrictPower
3156 + ", mDeviceIdleMode: " + mDeviceIdleMode
3157 + ", isForeground=" + isForeground
3158 + ", isWhitelisted=" + isWhitelisted
3159 + ", oldRule=" + uidRulesToString(oldRule)
3160 + ", newRule=" + uidRulesToString(newRule)
3161 + ", newUidRules=" + uidRulesToString(newUidRules)
3162 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3163 }
3164
Felipe Leme781ba142016-05-09 16:24:48 -07003165 // Second step: notify listeners if state changed.
3166 if (newRule != oldRule) {
3167 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003168 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003169 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003170 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3171 } else {
3172 // All scenarios should have been covered above
3173 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3174 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003175 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003176 + ", newRule=" + uidRulesToString(newUidRules)
3177 + ", oldRule=" + uidRulesToString(oldUidRules));
3178 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003179 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003180 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003181
3182 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003183 }
3184
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003185 private class AppIdleStateChangeListener
3186 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3187
3188 @Override
3189 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3190 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003191 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3192 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003193 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003194 synchronized (mUidRulesFirstLock) {
3195 updateRuleForAppIdleUL(uid);
3196 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003197 }
3198 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003199 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003200 }
3201
3202 @Override
3203 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003204 synchronized (mUidRulesFirstLock) {
3205 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003206 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003207 }
3208 }
3209
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003210 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3211 if (listener != null) {
3212 try {
3213 listener.onUidRulesChanged(uid, uidRules);
3214 } catch (RemoteException ignored) {
3215 }
3216 }
3217 }
3218
3219 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3220 String[] meteredIfaces) {
3221 if (listener != null) {
3222 try {
3223 listener.onMeteredIfacesChanged(meteredIfaces);
3224 } catch (RemoteException ignored) {
3225 }
3226 }
3227 }
3228
3229 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3230 boolean restrictBackground) {
3231 if (listener != null) {
3232 try {
3233 listener.onRestrictBackgroundChanged(restrictBackground);
3234 } catch (RemoteException ignored) {
3235 }
3236 }
3237 }
3238
3239 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3240 int uid, boolean whitelisted) {
3241 if (listener != null) {
3242 try {
3243 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3244 } catch (RemoteException ignored) {
3245 }
3246 }
3247 }
3248
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003249 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3250 int uid, boolean blacklisted) {
3251 if (listener != null) {
3252 try {
3253 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3254 } catch (RemoteException ignored) {
3255 }
3256 }
3257 }
3258
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003259 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003260 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003261 public boolean handleMessage(Message msg) {
3262 switch (msg.what) {
3263 case MSG_RULES_CHANGED: {
3264 final int uid = msg.arg1;
3265 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003266 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003267 final int length = mListeners.beginBroadcast();
3268 for (int i = 0; i < length; i++) {
3269 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003270 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003271 }
3272 mListeners.finishBroadcast();
3273 return true;
3274 }
3275 case MSG_METERED_IFACES_CHANGED: {
3276 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003277 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003278 final int length = mListeners.beginBroadcast();
3279 for (int i = 0; i < length; i++) {
3280 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003281 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003282 }
3283 mListeners.finishBroadcast();
3284 return true;
3285 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003286 case MSG_LIMIT_REACHED: {
3287 final String iface = (String) msg.obj;
3288
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003289 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003290 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003291 if (mMeteredIfaces.contains(iface)) {
3292 try {
3293 // force stats update to make sure we have
3294 // numbers that caused alert to trigger.
3295 mNetworkStats.forceUpdate();
3296 } catch (RemoteException e) {
3297 // ignored; service lives in system_server
3298 }
3299
Felipe Lemef0823852016-06-08 13:43:08 -07003300 updateNetworkEnabledNL();
3301 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003302 }
3303 }
3304 return true;
3305 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003306 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3307 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003308 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003309 final int length = mListeners.beginBroadcast();
3310 for (int i = 0; i < length; i++) {
3311 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003312 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003313 }
3314 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003315 final Intent intent =
3316 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3317 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3318 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3319 return true;
3320 }
3321 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003322 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3323 // - when an app is whitelisted
3324 // - when an app is blacklisted
3325 //
3326 // Whether the internal listeners (INetworkPolicyListener implementations) or
3327 // app broadcast receivers are notified depend on the following rules:
3328 //
3329 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3330 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3331 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003332 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003333 final boolean changed = msg.arg2 == 1;
3334 final Boolean whitelisted = (Boolean) msg.obj;
3335
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003336 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003337 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003338 final boolean whitelistedBool = whitelisted.booleanValue();
3339 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3340 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003341 final int length = mListeners.beginBroadcast();
3342 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003343 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003344 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3345 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003346 }
3347 mListeners.finishBroadcast();
3348 }
Felipe Leme9778f762016-01-27 14:46:39 -08003349 final PackageManager pm = mContext.getPackageManager();
3350 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003351 if (changed && packages != null) {
3352 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003353 final int userId = UserHandle.getUserId(uid);
3354 for (String packageName : packages) {
3355 final Intent intent = new Intent(
3356 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3357 intent.setPackage(packageName);
3358 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3359 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3360 }
Felipe Leme9778f762016-01-27 14:46:39 -08003361 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003362 return true;
3363 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003364 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3365 final int uid = msg.arg1;
3366 final boolean blacklisted = msg.arg2 == 1;
3367
3368 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3369 blacklisted);
3370 final int length = mListeners.beginBroadcast();
3371 for (int i = 0; i < length; i++) {
3372 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3373 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3374 blacklisted);
3375 }
3376 mListeners.finishBroadcast();
3377 return true;
3378 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003379 case MSG_ADVISE_PERSIST_THRESHOLD: {
3380 final long lowestRule = (Long) msg.obj;
3381 try {
3382 // make sure stats are recorded frequently enough; we aim
3383 // for 2MB threshold for 2GB/month rules.
3384 final long persistThreshold = lowestRule / 1000;
3385 mNetworkStats.advisePersistThreshold(persistThreshold);
3386 } catch (RemoteException e) {
3387 // ignored; service lives in system_server
3388 }
3389 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003390 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003391 case MSG_UPDATE_INTERFACE_QUOTA: {
3392 removeInterfaceQuota((String) msg.obj);
3393 // int params need to be stitched back into a long
3394 setInterfaceQuota((String) msg.obj,
3395 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3396 return true;
3397 }
3398 case MSG_REMOVE_INTERFACE_QUOTA: {
3399 removeInterfaceQuota((String) msg.obj);
3400 return true;
3401 }
Felipe Leme84d39732016-09-08 13:26:55 -07003402 case MSG_SET_FIREWALL_RULES: {
3403 final int chain = msg.arg1;
3404 final int toggle = msg.arg2;
3405 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3406 if (uidRules != null) {
3407 setUidFirewallRules(chain, uidRules);
3408 }
3409 if (toggle != CHAIN_TOGGLE_NONE) {
3410 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3411 }
3412 return true;
3413 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003414 default: {
3415 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003416 }
3417 }
3418 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003419 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003420
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003421 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003422 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003423 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003424 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003425 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003426 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003427 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003428 }
3429 }
3430
3431 private void removeInterfaceQuota(String iface) {
3432 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003433 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003434 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003435 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003436 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003437 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003438 }
3439 }
3440
Felipe Leme70c57c22016-03-29 10:45:13 -07003441 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3442 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003443 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003444 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003445 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003446 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3447 } catch (RemoteException e) {
3448 // ignored; service lives in system_server
3449 }
3450 }
3451
3452 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3453 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3454 try {
3455 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3456 } catch (IllegalStateException e) {
3457 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003458 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003459 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003460 }
3461 }
3462
Felipe Leme84d39732016-09-08 13:26:55 -07003463 private static final int CHAIN_TOGGLE_NONE = 0;
3464 private static final int CHAIN_TOGGLE_ENABLE = 1;
3465 private static final int CHAIN_TOGGLE_DISABLE = 2;
3466 @Retention(RetentionPolicy.SOURCE)
3467 @IntDef(flag = false, value = {
3468 CHAIN_TOGGLE_NONE,
3469 CHAIN_TOGGLE_ENABLE,
3470 CHAIN_TOGGLE_DISABLE
3471 })
3472 public @interface ChainToggleType {
3473 }
3474
3475 /**
3476 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3477 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3478 *
3479 * @param chain firewall chain.
3480 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3481 * @param toggle whether the chain should be enabled, disabled, or not changed.
3482 */
3483 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3484 @ChainToggleType int toggle) {
3485 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3486 }
3487
Amith Yamasani15e472352015-04-24 19:06:07 -07003488 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003489 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3490 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3491 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003492 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003493 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003494 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003495 int size = uidRules.size();
3496 int[] uids = new int[size];
3497 int[] rules = new int[size];
3498 for(int index = size - 1; index >= 0; --index) {
3499 uids[index] = uidRules.keyAt(index);
3500 rules[index] = uidRules.valueAt(index);
3501 }
3502 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003503 } catch (IllegalStateException e) {
3504 Log.wtf(TAG, "problem setting firewall uid rules", e);
3505 } catch (RemoteException e) {
3506 // ignored; service lives in system_server
3507 }
3508 }
3509
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003510 /**
3511 * Add or remove a uid to the firewall blacklist for all network ifaces.
3512 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003513 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003514 if (chain == FIREWALL_CHAIN_DOZABLE) {
3515 mUidFirewallDozableRules.put(uid, rule);
3516 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3517 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003518 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3519 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003520 }
3521
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003522 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003523 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003524 } catch (IllegalStateException e) {
3525 Log.wtf(TAG, "problem setting firewall uid rules", e);
3526 } catch (RemoteException e) {
3527 // ignored; service lives in system_server
3528 }
3529 }
3530
3531 /**
3532 * Add or remove a uid to the firewall blacklist for all network ifaces.
3533 */
Felipe Lemef0823852016-06-08 13:43:08 -07003534 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003535 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3536 mFirewallChainStates.get(chain) == enable) {
3537 // All is the same, nothing to do.
3538 return;
3539 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003540 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003541 try {
3542 mNetworkManager.setFirewallChainEnabled(chain, enable);
3543 } catch (IllegalStateException e) {
3544 Log.wtf(TAG, "problem enable firewall chain", e);
3545 } catch (RemoteException e) {
3546 // ignored; service lives in system_server
3547 }
3548 }
3549
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003550 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3551 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003552 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003553 } catch (RuntimeException e) {
3554 Slog.w(TAG, "problem reading network stats: " + e);
3555 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003556 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003557 // ignored; service lives in system_server
3558 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003559 }
3560 }
3561
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003562 private boolean isBandwidthControlEnabled() {
3563 final long token = Binder.clearCallingIdentity();
3564 try {
3565 return mNetworkManager.isBandwidthControlEnabled();
3566 } catch (RemoteException e) {
3567 // ignored; service lives in system_server
3568 return false;
3569 } finally {
3570 Binder.restoreCallingIdentity(token);
3571 }
3572 }
3573
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003574 /**
3575 * Try refreshing {@link #mTime} when stale.
3576 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003577 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003578 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003579 mTime.forceRefresh();
3580 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003581 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003582
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003583 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003584 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3585 }
3586
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003587 private static Intent buildAllowBackgroundDataIntent() {
3588 return new Intent(ACTION_ALLOW_BACKGROUND);
3589 }
3590
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003591 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3592 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3593 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3594 return intent;
3595 }
3596
Wei Liu546cb772016-07-21 16:19:01 -07003597 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003598 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003599 intent.setComponent(ComponentName.unflattenFromString(
3600 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003601 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3602 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3603 return intent;
3604 }
3605
Wei Liu546cb772016-07-21 16:19:01 -07003606 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003607 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003608 intent.setComponent(ComponentName.unflattenFromString(
3609 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003610 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3611 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3612 return intent;
3613 }
3614
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003615 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003616 public void addIdleHandler(IdleHandler handler) {
3617 mHandler.getLooper().getQueue().addIdleHandler(handler);
3618 }
3619
Jeff Sharkey1b861272011-05-22 00:34:52 -07003620 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3621 final int size = source.size();
3622 for (int i = 0; i < size; i++) {
3623 target.put(source.keyAt(i), true);
3624 }
3625 }
3626
Stuart Scottf1fb3972015-04-02 18:00:02 -07003627 @Override
3628 public void factoryReset(String subscriber) {
3629 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3630
Stuart Scotte3e314d2015-04-20 14:07:45 -07003631 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3632 return;
3633 }
3634
Stuart Scottf1fb3972015-04-02 18:00:02 -07003635 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003636 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003637 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3638 for (NetworkPolicy policy : policies) {
3639 if (policy.template.equals(template)) {
3640 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3641 policy.inferred = false;
3642 policy.clearSnooze();
3643 }
3644 }
3645 setNetworkPolicies(policies);
3646
3647 // Turn restrict background data off
3648 setRestrictBackground(false);
3649
Stuart Scotte3e314d2015-04-20 14:07:45 -07003650 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3651 // Remove app's "restrict background data" flag
3652 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3653 setUidPolicy(uid, POLICY_NONE);
3654 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003655 }
3656 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003657
Felipe Lemed17fda42016-04-29 11:12:45 -07003658 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3659
3660 @Override
3661 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003662 synchronized (mUidRulesFirstLock) {
3663 boolean changed = removeUserStateUL(userId, false);
3664 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003665 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003666 synchronized (mNetworkPoliciesSecondLock) {
3667 writePolicyAL();
3668 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003669 }
3670 }
3671 }
3672 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003673}