blob: 4a042dabb0fb12a05c32c05a2022f9243affc4b5 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
56import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070060import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070069import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
70import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
71import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
72import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
73import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
74import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
75import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070076import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
83import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
84import static com.android.internal.util.XmlUtils.writeIntAttribute;
85import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070086import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070087import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060088
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080090import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070092
Dianne Hackborn88e98df2015-03-23 13:29:14 -070093import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070094import android.annotation.IntDef;
Dianne Hackborn497175b2014-07-01 12:56:08 -070095import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070096import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070097import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070098import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700100import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700101import android.app.Notification;
102import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700103import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700105import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700106import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.Intent;
108import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700110import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700111import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700112import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700113import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700116import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700117import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700119import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700120import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700122import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700123import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.net.NetworkPolicy;
Jeff Sharkey7c3e4422015-10-12 18:07:38 -0700125import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700126import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700128import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700129import android.net.wifi.WifiConfiguration;
130import android.net.wifi.WifiInfo;
131import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700132import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import android.os.Environment;
134import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700135import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700136import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700137import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700138import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700139import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700140import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700141import android.os.PowerManagerInternal;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700142import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700143import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600144import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700145import android.os.ServiceManager;
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;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400151import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700152import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700153import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700154import android.util.ArrayMap;
155import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700156import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700157import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700159import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700160import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161import android.util.SparseBooleanArray;
162import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.TrustedTime;
164import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165
Jeff Sharkey497e4432011-06-14 17:27:29 -0700166import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700167import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800168import com.android.internal.annotations.VisibleForTesting;
Felipe Lemeb85a6372016-01-14 16:16:16 -0800169import com.android.internal.content.PackageMonitor;
Jeff Sharkey32566012014-12-02 18:30:14 -0800170import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700171import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700172import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700173import com.android.server.DeviceIdleController;
174import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700175import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800176import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600177
178import libcore.io.IoUtils;
179
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700181
182import org.xmlpull.v1.XmlPullParser;
183import org.xmlpull.v1.XmlPullParserException;
184import org.xmlpull.v1.XmlSerializer;
185
186import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700187import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import java.io.FileInputStream;
189import java.io.FileNotFoundException;
190import java.io.FileOutputStream;
191import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700192import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700193import java.lang.annotation.Retention;
194import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100195import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import java.util.ArrayList;
197import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700198import java.util.List;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700200/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700201 * Service that maintains low-level network policy rules, using
202 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 * <p>
204 * Derives active rules by combining a given policy with other system status,
205 * and delivers to listeners, such as {@link ConnectivityManager}, for
206 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700207 *
208 * <p>
209 * This class uses 2-3 locks to synchronize state:
210 * <ul>
211 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
212 * rules).
213 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
214 * as network policies).
215 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
216 * must be held.
217 * </ul>
218 *
219 * <p>
220 * As such, methods that require synchronization have the following prefixes:
221 * <ul>
222 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
223 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
224 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
225 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
226 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700227 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700228public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800229 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700230 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700231 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700232
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700233 private static final int VERSION_INIT = 1;
234 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700235 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800236 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800237 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800238 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700239 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700240 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700241 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700242 private static final int VERSION_SWITCH_UID = 10;
243 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700244
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800245 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700246 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800247 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700248 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700250 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700251
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700252 private static final String TAG_POLICY_LIST = "policy-list";
253 private static final String TAG_NETWORK_POLICY = "network-policy";
254 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700255 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800256 private static final String TAG_WHITELIST = "whitelist";
257 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800258 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259
260 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700261 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700262 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
263 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700264 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800266 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700267 private static final String ATTR_WARNING_BYTES = "warningBytes";
268 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700269 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800270 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
271 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800272 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700273 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700275 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 private static final String ATTR_POLICY = "policy";
277
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800279 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800280 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800281 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
284
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700285 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700286 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800287 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800288 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700289 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Felipe Leme9778f762016-01-27 14:46:39 -0800290 private static final int MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED = 9;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700291 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
292 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme99d5d3d2016-05-16 13:30:57 -0700293 private static final int MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED = 12;
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 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800361 * UIDs that have been initially white-listed by system to avoid restricted background.
362 */
Felipe Lemef0823852016-06-08 13:43:08 -0700363 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800364 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
365 new SparseBooleanArray();
366
367 /**
368 * UIDs that have been initially white-listed by system to avoid restricted background,
369 * but later revoked by user.
370 */
Felipe Lemef0823852016-06-08 13:43:08 -0700371 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800372 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
373 new SparseBooleanArray();
374
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700375 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700376 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800377 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700378 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800380 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700381
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700382 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700384 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700385
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700386 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800388 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700389
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600390 /** Higher priority listener before general event dispatch */
391 private INetworkPolicyListener mConnectivityListener;
392
Jeff Sharkey32566012014-12-02 18:30:14 -0800393 private final RemoteCallbackList<INetworkPolicyListener>
394 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700395
Dianne Hackborn497175b2014-07-01 12:56:08 -0700396 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700397
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700399 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700400
Svet Ganov16a16892015-04-16 10:32:04 -0700401 private final AppOpsManager mAppOps;
402
Felipe Lemeb85a6372016-01-14 16:16:16 -0800403 private final MyPackageMonitor mPackageMonitor;
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800404 private final IPackageManager mIPm;
405
Felipe Lemeb85a6372016-01-14 16:16:16 -0800406
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700407 // TODO: keep whitelist of system-critical services that should never have
408 // rules enforced, such as system, phone, and radio UIDs.
409
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700410 // TODO: migrate notifications to SystemUI
411
Jeff Sharkey75279902011-05-24 18:39:45 -0700412 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700413 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
414 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700415 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
416 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700417 }
418
419 private static File getSystemDir() {
420 return new File(Environment.getDataDirectory(), "system");
421 }
422
423 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700424 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700425 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700426 mContext = checkNotNull(context, "missing context");
427 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700428 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700429 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700430 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700431 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700432 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700433 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700434 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700435
Amith Yamasani450a16b2013-09-18 16:28:50 -0700436 HandlerThread thread = new HandlerThread(TAG);
437 thread.start();
438 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700440 mSuppressDefaultPolicy = suppressDefaultPolicy;
441
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700442 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700443
444 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800445
446 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700447
448 // Expose private service for system components to use.
449 LocalServices.addService(NetworkPolicyManagerInternal.class,
450 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700451 }
452
453 public void bindConnectivityManager(IConnectivityManager connManager) {
454 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700455 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700456
Jeff Sharkey497e4432011-06-14 17:27:29 -0700457 public void bindNotificationManager(INotificationManager notifManager) {
458 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
459 }
460
Felipe Lemef0823852016-06-08 13:43:08 -0700461 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700462 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700463 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
464 mPowerSaveWhitelistExceptIdleAppIds.clear();
465 if (whitelist != null) {
466 for (int uid : whitelist) {
467 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
468 }
469 }
470 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700471 mPowerSaveWhitelistAppIds.clear();
472 if (whitelist != null) {
473 for (int uid : whitelist) {
474 mPowerSaveWhitelistAppIds.put(uid, true);
475 }
476 }
477 } catch (RemoteException e) {
478 }
479 }
480
Felipe Lemea9505cc2016-02-26 10:28:41 -0800481 /**
482 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
483 * revoke the whitelist.
484 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700485 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800486 */
Felipe Lemef0823852016-06-08 13:43:08 -0700487 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800488 final List<UserInfo> users = mUserManager.getUsers();
489 final int numberUsers = users.size();
490
Felipe Lemea110eec2016-04-29 09:58:06 -0700491 boolean changed = false;
492 for (int i = 0; i < numberUsers; i++) {
493 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700494 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700495 }
496 return changed;
497 }
498
Felipe Lemef0823852016-06-08 13:43:08 -0700499 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700500 final SystemConfig sysConfig = SystemConfig.getInstance();
501 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800502 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
503 boolean changed = false;
504 for (int i = 0; i < allowDataUsage.size(); i++) {
505 final String pkg = allowDataUsage.valueAt(i);
506 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700507 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
508 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800509 final ApplicationInfo app;
510 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700511 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800512 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700513 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
514 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800515 continue;
516 }
517 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700518 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
519 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800520 continue;
521 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700522 final int uid = UserHandle.getUid(userId, app.uid);
523 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
524 if (LOGD)
525 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
526 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800527 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700528 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700529 if (LOGD)
530 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
531 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700532 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700533 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800534 }
535 }
536 return changed;
537 }
538
Felipe Lemef0823852016-06-08 13:43:08 -0700539 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700540 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700541 // Clear the states of the current whitelist
542 final int N = mPowerSaveTempWhitelistAppIds.size();
543 for (int i = 0; i < N; i++) {
544 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
545 }
546 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700547 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700548 if (whitelist != null) {
549 for (int uid : whitelist) {
550 mPowerSaveTempWhitelistAppIds.put(uid, true);
551 }
552 }
553 } catch (RemoteException e) {
554 }
555 }
556
Amith Yamasani06f08062015-06-12 13:23:33 -0700557 /**
558 * Remove unnecessary entries in the temp whitelist
559 */
Felipe Lemef0823852016-06-08 13:43:08 -0700560 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700561 final int N = mPowerSaveTempWhitelistAppIds.size();
562 for (int i = N - 1; i >= 0; i--) {
563 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
564 mPowerSaveTempWhitelistAppIds.removeAt(i);
565 }
566 }
567 }
568
Jeff Sharkeya4620792011-05-20 15:29:23 -0700569 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700570 if (!isBandwidthControlEnabled()) {
571 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
572 return;
573 }
574
Amith Yamasani15e472352015-04-24 19:06:07 -0700575 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
576
Felipe Lemeb85a6372016-01-14 16:16:16 -0800577 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
578
Felipe Lemef0823852016-06-08 13:43:08 -0700579 synchronized (mUidRulesFirstLock) {
580 synchronized (mNetworkPoliciesSecondLock) {
581 updatePowerSaveWhitelistUL();
582 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
583 mPowerManagerInternal.registerLowPowerModeObserver(
584 new PowerManagerInternal.LowPowerModeListener() {
585 @Override
586 public void onLowPowerModeChanged(boolean enabled) {
587 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
588 synchronized (mUidRulesFirstLock) {
589 if (mRestrictPower != enabled) {
590 mRestrictPower = enabled;
591 updateRulesForRestrictPowerUL();
592 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700593 }
594 }
Felipe Lemef0823852016-06-08 13:43:08 -0700595 });
596 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
597
598 mSystemReady = true;
599
600 // read policy from disk
601 readPolicyAL();
602
603 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
604 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700605 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700606
Felipe Lemef0823852016-06-08 13:43:08 -0700607 setRestrictBackgroundUL(mRestrictBackground);
608 updateRulesForGlobalChangeAL(false);
609 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800610 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700611 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700612
Jeff Sharkeya4620792011-05-20 15:29:23 -0700613 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700614 mActivityManager.registerUidObserver(mUidObserver,
615 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700616 mNetworkManager.registerObserver(mAlertObserver);
617 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700618 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700619 }
620
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700621 // listen for changes to power save whitelist
622 final IntentFilter whitelistFilter = new IntentFilter(
623 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
624 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
625
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700626 DeviceIdleController.LocalService deviceIdleService
627 = LocalServices.getService(DeviceIdleController.LocalService.class);
628 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
629
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700630 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900631 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700632 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
633
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700634 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700635 final IntentFilter packageFilter = new IntentFilter();
636 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700637 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700638 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700639
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700640 // listen for UID changes to update policy
641 mContext.registerReceiver(
642 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
643
644 // listen for user changes to update policy
645 final IntentFilter userFilter = new IntentFilter();
646 userFilter.addAction(ACTION_USER_ADDED);
647 userFilter.addAction(ACTION_USER_REMOVED);
648 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
649
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700650 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700651 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
652 mContext.registerReceiver(
653 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
654
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700655 // listen for restrict background changes from notifications
656 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
657 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
658
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800659 // listen for snooze warning from notifications
660 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
661 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
662 MANAGE_NETWORK_POLICY, mHandler);
663
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700664 // listen for configured wifi networks to be removed
665 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700666 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700667
668 // listen for wifi state changes to catch metered hint
669 final IntentFilter wifiStateFilter = new IntentFilter(
670 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700671 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700672
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700673 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700674
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700675 }
676
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700677 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700678 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700679 synchronized (mUidRulesFirstLock) {
680 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700681 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700682 }
683
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700684 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700685 synchronized (mUidRulesFirstLock) {
686 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700687 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700688 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700689
690 @Override public void onUidActive(int uid) throws RemoteException {
691 }
692
693 @Override public void onUidIdle(int uid) throws RemoteException {
694 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700695 };
696
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700697 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700698 @Override
699 public void onReceive(Context context, Intent intent) {
700 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700701 synchronized (mUidRulesFirstLock) {
702 updatePowerSaveWhitelistUL();
703 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700704 }
705 }
706 };
707
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700708 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
709 @Override
710 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700711 synchronized (mUidRulesFirstLock) {
712 updatePowerSaveTempWhitelistUL();
713 updateRulesForTempWhitelistChangeUL();
714 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700715 }
716 }
717 };
718
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700719 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700720 @Override
721 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700722 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700723
724 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700725 final int uid = intent.getIntExtra(EXTRA_UID, -1);
726 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700727
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700728 if (ACTION_PACKAGE_ADDED.equals(action)) {
729 // update rules for UID, since it might be subject to
730 // global background data policy
731 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700732 synchronized (mUidRulesFirstLock) {
733 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700734 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700735 }
736 }
737 };
738
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700739 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700740 @Override
741 public void onReceive(Context context, Intent intent) {
742 // on background handler thread, and UID_REMOVED is protected
743
744 final int uid = intent.getIntExtra(EXTRA_UID, -1);
745 if (uid == -1) return;
746
747 // remove any policy and update rules to clean up
748 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700749 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700750 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700751 updateRestrictionRulesForUidUL(uid);
752 synchronized (mNetworkPoliciesSecondLock) {
753 writePolicyAL();
754 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700755 }
756 }
757 };
758
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700759 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700760 @Override
761 public void onReceive(Context context, Intent intent) {
762 // on background handler thread, and USER_ADDED and USER_REMOVED
763 // broadcasts are protected
764
765 final String action = intent.getAction();
766 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
767 if (userId == -1) return;
768
Amith Yamasani15e472352015-04-24 19:06:07 -0700769 switch (action) {
770 case ACTION_USER_REMOVED:
771 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700772 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800773 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700774 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700775 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700776 if (action == ACTION_USER_ADDED) {
777 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700778 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700779 }
780 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700781 synchronized (mNetworkPoliciesSecondLock) {
782 updateRulesForGlobalChangeAL(true);
783 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700784 }
785 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700786 }
787 }
788 };
789
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700790 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700791 * Receiver that watches for {@link INetworkStatsService} updates, which we
792 * use to check against {@link NetworkPolicy#warningBytes}.
793 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700794 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700795 @Override
796 public void onReceive(Context context, Intent intent) {
797 // on background handler thread, and verified
798 // READ_NETWORK_USAGE_HISTORY permission above.
799
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800800 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700801 synchronized (mNetworkPoliciesSecondLock) {
802 updateNetworkEnabledNL();
803 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700804 }
805 }
806 };
807
808 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700809 * Receiver that watches for {@link Notification} control of
810 * {@link #mRestrictBackground}.
811 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700812 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700813 @Override
814 public void onReceive(Context context, Intent intent) {
815 // on background handler thread, and verified MANAGE_NETWORK_POLICY
816 // permission above.
817
818 setRestrictBackground(false);
819 }
820 };
821
822 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800823 * Receiver that watches for {@link Notification} control of
824 * {@link NetworkPolicy#lastWarningSnooze}.
825 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700826 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800827 @Override
828 public void onReceive(Context context, Intent intent) {
829 // on background handler thread, and verified MANAGE_NETWORK_POLICY
830 // permission above.
831
832 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
833 performSnooze(template, TYPE_WARNING);
834 }
835 };
836
837 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700838 * Receiver that watches for {@link WifiConfiguration} to be changed.
839 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700840 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700841 @Override
842 public void onReceive(Context context, Intent intent) {
843 // on background handler thread, and verified CONNECTIVITY_INTERNAL
844 // permission above.
845
846 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
847 if (reason == CHANGE_REASON_REMOVED) {
848 final WifiConfiguration config = intent.getParcelableExtra(
849 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700850 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800851 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700852 synchronized (mUidRulesFirstLock) {
853 synchronized (mNetworkPoliciesSecondLock) {
854 if (mNetworkPolicy.containsKey(template)) {
855 mNetworkPolicy.remove(template);
856 writePolicyAL();
857 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700858 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700859 }
860 }
861 }
862 }
863 };
864
865 /**
866 * Receiver that watches {@link WifiInfo} state changes to infer metered
867 * state. Ignores hints when policy is user-defined.
868 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700869 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700870 @Override
871 public void onReceive(Context context, Intent intent) {
872 // on background handler thread, and verified CONNECTIVITY_INTERNAL
873 // permission above.
874
875 // ignore when not connected
876 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
877 if (!netInfo.isConnected()) return;
878
879 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
880 final boolean meteredHint = info.getMeteredHint();
881
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800882 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700883 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700884 NetworkPolicy policy = mNetworkPolicy.get(template);
885 if (policy == null && meteredHint) {
886 // policy doesn't exist, and AP is hinting that it's
887 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800888 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700889 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700890
891 } else if (policy != null && policy.inferred) {
892 // policy exists, and was inferred: update its current
893 // metered state.
894 policy.metered = meteredHint;
895
896 // since this is inferred for each wifi session, just update
897 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700898 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700899 }
900 }
901 }
902 };
903
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800904 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
905 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
906 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
907 metered, true);
908 }
909
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700910 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700911 * Observer that watches for {@link INetworkManagementService} alerts.
912 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700913 final private INetworkManagementEventObserver mAlertObserver
914 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700915 @Override
916 public void limitReached(String limitName, String iface) {
917 // only someone like NMS should be calling us
918 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
919
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800920 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
921 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700922 }
923 }
924 };
925
926 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
928 * to show visible notifications as needed.
929 */
Felipe Lemef0823852016-06-08 13:43:08 -0700930 void updateNotificationsNL() {
931 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700932
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700933 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700934 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700935 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700936
937 // TODO: when switching to kernel notifications, compute next future
938 // cycle boundary to recompute notifications.
939
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700940 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800941 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700942 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
943 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700944 // ignore policies that aren't relevant to user
945 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700946 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948 final long start = computeLastCycleBoundary(currentTime, policy);
949 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700950 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700952 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800953 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700954 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
955 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700956 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700957 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700958 }
959
Jeff Sharkey497e4432011-06-14 17:27:29 -0700960 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700961 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800963 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700964 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700965 }
966 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700967 }
968
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700969 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700970 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
971 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 if (!mActiveNotifs.contains(tag)) {
973 cancelNotification(tag);
974 }
975 }
976 }
977
978 /**
979 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700980 * current device state, such as when
981 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
982 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700983 */
984 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800985 if (template.isMatchRuleMobile()) {
986 final TelephonyManager tele = TelephonyManager.from(mContext);
987 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700988
Jeff Sharkey32566012014-12-02 18:30:14 -0800989 // Mobile template is relevant when any active subscriber matches
990 final int[] subIds = sub.getActiveSubscriptionIdList();
991 for (int subId : subIds) {
992 final String subscriberId = tele.getSubscriberId(subId);
993 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700994 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800995 if (template.matches(probeIdent)) {
996 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700997 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800998 }
999 return false;
1000 } else {
1001 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001002 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001003 }
1004
1005 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001006 * Notify that given {@link NetworkTemplate} is over
1007 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1008 */
Felipe Lemef0823852016-06-08 13:43:08 -07001009 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001010 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001011 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001012 mOverLimitNotified.add(template);
1013 }
1014 }
1015
Felipe Lemef0823852016-06-08 13:43:08 -07001016 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001017 mOverLimitNotified.remove(template);
1018 }
1019
1020 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001021 * Build unique tag that identifies an active {@link NetworkPolicy}
1022 * notification of a specific type, like {@link #TYPE_LIMIT}.
1023 */
1024 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001025 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001026 }
1027
1028 /**
1029 * Show notification for combined {@link NetworkPolicy} and specific type,
1030 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1031 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001033 final String tag = buildNotificationTag(policy, type);
1034 final Notification.Builder builder = new Notification.Builder(mContext);
1035 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001036 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001037 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001038 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039
1040 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001041 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 switch (type) {
1043 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001044 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001045 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001047 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001048 builder.setTicker(title);
1049 builder.setContentTitle(title);
1050 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001051 builder.setDefaults(Notification.DEFAULT_ALL);
1052 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001053
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001054 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1055 builder.setDeleteIntent(PendingIntent.getBroadcast(
1056 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1057
Wei Liu546cb772016-07-21 16:19:01 -07001058 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001059 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001060 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1061
Jeff Sharkey497e4432011-06-14 17:27:29 -07001062 break;
1063 }
1064 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001065 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066
1067 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001068 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001069 switch (policy.template.getMatchRule()) {
1070 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001073 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001079 case MATCH_WIFI:
1080 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001081 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001082 break;
1083 default:
1084 title = null;
1085 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086 }
1087
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001088 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001089 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001090 builder.setTicker(title);
1091 builder.setContentTitle(title);
1092 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001093
Wei Liu546cb772016-07-21 16:19:01 -07001094 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001095 builder.setContentIntent(PendingIntent.getActivity(
1096 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1097 break;
1098 }
1099 case TYPE_LIMIT_SNOOZED: {
1100 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001101 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102 Formatter.formatFileSize(mContext, overBytes));
1103
1104 final CharSequence title;
1105 switch (policy.template.getMatchRule()) {
1106 case MATCH_MOBILE_3G_LOWER:
1107 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1108 break;
1109 case MATCH_MOBILE_4G:
1110 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1111 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001112 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001113 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1114 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 case MATCH_WIFI:
1116 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1117 break;
1118 default:
1119 title = null;
1120 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001121 }
1122
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001123 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001124 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 builder.setTicker(title);
1126 builder.setContentTitle(title);
1127 builder.setContentText(body);
1128
Wei Liu546cb772016-07-21 16:19:01 -07001129 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001130 builder.setContentIntent(PendingIntent.getActivity(
1131 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 break;
1133 }
1134 }
1135
1136 // TODO: move to NotificationManager once we can mock it
1137 try {
1138 final String packageName = mContext.getPackageName();
1139 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001140 if(!TextUtils.isEmpty(body)) {
1141 builder.setStyle(new Notification.BigTextStyle()
1142 .bigText(body));
1143 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001144 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001145 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001146 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001147 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001149 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150 }
1151 }
1152
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001153 private void cancelNotification(String tag) {
1154 // TODO: move to NotificationManager once we can mock it
1155 try {
1156 final String packageName = mContext.getPackageName();
1157 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001158 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001159 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001160 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001161 }
1162 }
1163
1164 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001165 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001166 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001167 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001168 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001169 @Override
1170 public void onReceive(Context context, Intent intent) {
1171 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1172 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001173
1174 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001175 synchronized (mNetworkPoliciesSecondLock) {
1176 ensureActiveMobilePolicyNL();
1177 normalizePoliciesNL();
1178 updateNetworkEnabledNL();
1179 updateNetworkRulesNL();
1180 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001181 }
1182 }
1183 };
1184
1185 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 * Proactively control network data connections when they exceed
1187 * {@link NetworkPolicy#limitBytes}.
1188 */
Felipe Lemef0823852016-06-08 13:43:08 -07001189 void updateNetworkEnabledNL() {
1190 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001191
1192 // TODO: reset any policy-disabled networks when any policy is removed
1193 // completely, which is currently rare case.
1194
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001195 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001196 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1197 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001199 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001200 setNetworkTemplateEnabled(policy.template, true);
1201 continue;
1202 }
1203
1204 final long start = computeLastCycleBoundary(currentTime, policy);
1205 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001206 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001207
1208 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001209 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1210 && policy.lastLimitSnooze < start;
1211 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001212
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001213 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001214 }
1215 }
1216
1217 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 * Proactively disable networks that match the given
1219 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001220 */
1221 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001222 // TODO: reach into ConnectivityManager to proactively disable bringing
1223 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001224
1225 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1226 // If mobile data usage hits the limit or if the user resumes the data, we need to
1227 // notify telephony.
1228 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1229 final TelephonyManager tm = TelephonyManager.from(mContext);
1230
1231 final int[] subIds = sm.getActiveSubscriptionIdList();
1232 for (int subId : subIds) {
1233 final String subscriberId = tm.getSubscriberId(subId);
1234 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1235 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1236 // Template is matched when subscriber id matches.
1237 if (template.matches(probeIdent)) {
1238 tm.setPolicyDataEnabled(enabled, subId);
1239 }
1240 }
1241 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001242 }
1243
1244 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001245 * Examine all connected {@link NetworkState}, looking for
1246 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1247 * remaining quota based on usage cycle and historical stats.
1248 */
Felipe Lemef0823852016-06-08 13:43:08 -07001249 void updateNetworkRulesNL() {
1250 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001251
1252 final NetworkState[] states;
1253 try {
1254 states = mConnManager.getAllNetworkState();
1255 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001256 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 return;
1258 }
1259
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001260 // First, generate identities of all connected networks so we can
1261 // quickly compare them against all defined policies below.
1262 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001263 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001264 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001265 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001266 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001267
1268 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001269 if (baseIface != null) {
1270 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001271 }
1272
1273 // Stacked interfaces are considered to have same identity as
1274 // their parent network.
1275 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1276 for (LinkProperties stackedLink : stackedLinks) {
1277 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001278 if (stackedIface != null) {
1279 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001280 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001281 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001282 }
1283 }
1284
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001285 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001286 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001287 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001288 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001289 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001290
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001292 for (int j = connIdents.size() - 1; j >= 0; j--) {
1293 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1294 if (policy.template.matches(ident.second)) {
1295 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001296 }
1297 }
1298
1299 if (ifaceList.size() > 0) {
1300 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001301 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 }
1303 }
1304
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001305 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001306 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001307
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001308 // apply each policy that we found ifaces for; compute remaining data
1309 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001310 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001311 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1312 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1313 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001315 final long start;
1316 final long totalBytes;
1317 if (policy.hasCycle()) {
1318 start = computeLastCycleBoundary(currentTime, policy);
1319 totalBytes = getTotalBytes(policy.template, start, currentTime);
1320 } else {
1321 start = Long.MAX_VALUE;
1322 totalBytes = 0;
1323 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001325 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001326 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 }
1328
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001329 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001330 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001331 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001332 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001333 if (!hasLimit) {
1334 // metered network, but no policy limit; we still need to
1335 // restrict apps, so push really high quota.
1336 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001337 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001338 // snoozing past quota, but we still need to restrict apps,
1339 // so push really high quota.
1340 quotaBytes = Long.MAX_VALUE;
1341 } else {
1342 // remaining "quota" bytes are based on total usage in
1343 // current cycle. kernel doesn't like 0-byte rules, so we
1344 // set 1-byte quota and disable the radio later.
1345 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1346 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001347
1348 if (ifaces.length > 1) {
1349 // TODO: switch to shared quota once NMS supports
1350 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001351 }
1352
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001353 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001354 // long quotaBytes split up into two ints to fit in message
1355 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1356 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1357 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001358 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001359 }
1360 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001361
1362 // keep track of lowest warning or limit of active policies
1363 if (hasWarning && policy.warningBytes < lowestRule) {
1364 lowestRule = policy.warningBytes;
1365 }
1366 if (hasLimit && policy.limitBytes < lowestRule) {
1367 lowestRule = policy.limitBytes;
1368 }
1369 }
1370
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001371 for (int i = connIfaces.size()-1; i >= 0; i--) {
1372 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001373 // long quotaBytes split up into two ints to fit in message
1374 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1375 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1376 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001377 newMeteredIfaces.add(iface);
1378 }
1379
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001380 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001382 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001383 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1384 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001385 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001386 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1387 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001388 }
1389 }
1390 mMeteredIfaces = newMeteredIfaces;
1391
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001392 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001393 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001394 }
1395
1396 /**
1397 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1398 * have at least a default mobile policy defined.
1399 */
Felipe Lemef0823852016-06-08 13:43:08 -07001400 private void ensureActiveMobilePolicyNL() {
1401 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001402 if (mSuppressDefaultPolicy) return;
1403
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001404 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001405 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001406
Jeff Sharkey32566012014-12-02 18:30:14 -08001407 final int[] subIds = sub.getActiveSubscriptionIdList();
1408 for (int subId : subIds) {
1409 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001410 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001411 }
1412 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001413
Felipe Lemef0823852016-06-08 13:43:08 -07001414 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001415 // Poke around to see if we already have a policy
1416 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001417 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001418 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1419 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1420 if (template.matches(probeIdent)) {
1421 if (LOGD) {
1422 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1423 + NetworkIdentity.scrubSubscriberId(subscriberId));
1424 }
1425 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001426 }
1427 }
1428
Jeff Sharkey32566012014-12-02 18:30:14 -08001429 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1430 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001431
Jeff Sharkey32566012014-12-02 18:30:14 -08001432 // Build default mobile policy, and assume usage cycle starts today
1433 final long warningBytes = mContext.getResources().getInteger(
1434 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001435
Jeff Sharkey32566012014-12-02 18:30:14 -08001436 final Time time = new Time();
1437 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001438
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 final int cycleDay = time.monthDay;
1440 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001441
Jeff Sharkey32566012014-12-02 18:30:14 -08001442 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1443 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1444 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001445 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001446 }
1447
Felipe Lemef0823852016-06-08 13:43:08 -07001448 private void readPolicyAL() {
1449 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001450
1451 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001452 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001453 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001454
1455 FileInputStream fis = null;
1456 try {
1457 fis = mPolicyFile.openRead();
1458 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001459 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001460
Felipe Leme46b451f2016-08-19 08:46:17 -07001461 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1462 // to skip UIDs that were explicitly blacklisted.
1463 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1464
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001466 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001467 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001468 while ((type = in.next()) != END_DOCUMENT) {
1469 final String tag = in.getName();
1470 if (type == START_TAG) {
1471 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001472 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001473 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001474 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1475 mRestrictBackground = readBooleanAttribute(
1476 in, ATTR_RESTRICT_BACKGROUND);
1477 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001478 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001479 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001480 if (mRestrictBackground != oldValue) {
1481 // Some early services may have read the default value,
1482 // so notify them that it's changed
1483 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1484 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1485 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001486
1487 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1488 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1489 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001490 final String networkId;
1491 if (version >= VERSION_ADDED_NETWORK_ID) {
1492 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1493 } else {
1494 networkId = null;
1495 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001497 final String cycleTimezone;
1498 if (version >= VERSION_ADDED_TIMEZONE) {
1499 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1500 } else {
1501 cycleTimezone = Time.TIMEZONE_UTC;
1502 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001503 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1504 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001505 final long lastLimitSnooze;
1506 if (version >= VERSION_SPLIT_SNOOZE) {
1507 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1508 } else if (version >= VERSION_ADDED_SNOOZE) {
1509 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001510 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001511 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001512 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001513 final boolean metered;
1514 if (version >= VERSION_ADDED_METERED) {
1515 metered = readBooleanAttribute(in, ATTR_METERED);
1516 } else {
1517 switch (networkTemplate) {
1518 case MATCH_MOBILE_3G_LOWER:
1519 case MATCH_MOBILE_4G:
1520 case MATCH_MOBILE_ALL:
1521 metered = true;
1522 break;
1523 default:
1524 metered = false;
1525 }
1526 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001527 final long lastWarningSnooze;
1528 if (version >= VERSION_SPLIT_SNOOZE) {
1529 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1530 } else {
1531 lastWarningSnooze = SNOOZE_NEVER;
1532 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001533 final boolean inferred;
1534 if (version >= VERSION_ADDED_INFERRED) {
1535 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1536 } else {
1537 inferred = false;
1538 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001539
Jeff Sharkey32566012014-12-02 18:30:14 -08001540 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1541 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001542 if (template.isPersistable()) {
1543 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1544 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1545 lastLimitSnooze, metered, inferred));
1546 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001548 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 final int uid = readIntAttribute(in, ATTR_UID);
1550 final int policy = readIntAttribute(in, ATTR_POLICY);
1551
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001552 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001553 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001554 } else {
1555 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1556 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001557 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001558 final int appId = readIntAttribute(in, ATTR_APP_ID);
1559 final int policy = readIntAttribute(in, ATTR_POLICY);
1560
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001562 // app policy is deprecated so this is only used in pre system user split.
1563 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001564 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001565 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001566 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001567 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001568 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001569 } else if (TAG_WHITELIST.equals(tag)) {
1570 insideWhitelist = true;
1571 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1572 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001573 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001574 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1575 final int uid = readIntAttribute(in, ATTR_UID);
1576 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001578 } else if (type == END_TAG) {
1579 if (TAG_WHITELIST.equals(tag)) {
1580 insideWhitelist = false;
1581 }
1582
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001583 }
1584 }
1585
Felipe Leme46b451f2016-08-19 08:46:17 -07001586 final int size = whitelistedRestrictBackground.size();
1587 for (int i = 0; i < size; i++) {
1588 final int uid = whitelistedRestrictBackground.keyAt(i);
1589 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1590 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1591 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1592 + " because its policy is " + uidPoliciesToString(policy));
1593 continue;
1594 }
1595 if (UserHandle.isApp(uid)) {
1596 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1597 if (LOGV)
1598 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1599 setUidPolicyUncheckedUL(uid, newPolicy, false);
1600 } else {
1601 Slog.w(TAG, "unable to update policy on UID " + uid);
1602 }
1603 }
1604
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 } catch (FileNotFoundException e) {
1606 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001607 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001608 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001609 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001611 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612 } finally {
1613 IoUtils.closeQuietly(fis);
1614 }
1615 }
1616
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001617 /**
1618 * Upgrade legacy background data flags, notifying listeners of one last
1619 * change to always-true.
1620 */
Felipe Lemef0823852016-06-08 13:43:08 -07001621 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001622 mRestrictBackground = Settings.Secure.getInt(
1623 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1624
1625 // kick off one last broadcast if restricted
1626 if (mRestrictBackground) {
1627 final Intent broadcast = new Intent(
1628 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001629 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001630 }
1631 }
1632
Felipe Lemef0823852016-06-08 13:43:08 -07001633 void writePolicyAL() {
1634 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001635
1636 FileOutputStream fos = null;
1637 try {
1638 fos = mPolicyFile.startWrite();
1639
1640 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001641 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642 out.startDocument(null, true);
1643
1644 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001645 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001646 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647
1648 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001649 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1650 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001651 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001652 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001653
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001655 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1656 final String subscriberId = template.getSubscriberId();
1657 if (subscriberId != null) {
1658 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001659 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001660 final String networkId = template.getNetworkId();
1661 if (networkId != null) {
1662 out.attribute(null, ATTR_NETWORK_ID, networkId);
1663 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001664 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001665 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001666 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1667 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001668 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1669 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001670 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001671 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001672 out.endTag(null, TAG_NETWORK_POLICY);
1673 }
1674
1675 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001676 for (int i = 0; i < mUidPolicy.size(); i++) {
1677 final int uid = mUidPolicy.keyAt(i);
1678 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001679
Jeff Sharkey497e4432011-06-14 17:27:29 -07001680 // skip writing empty policies
1681 if (policy == POLICY_NONE) continue;
1682
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001683 out.startTag(null, TAG_UID_POLICY);
1684 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001685 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001686 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001687 }
1688
1689 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001690
1691 // write all whitelists
1692 out.startTag(null, TAG_WHITELIST);
1693
Felipe Lemea9505cc2016-02-26 10:28:41 -08001694 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001695 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001696 for (int i = 0; i < size; i++) {
1697 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1698 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1699 writeIntAttribute(out, ATTR_UID, uid);
1700 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1701 }
1702
Felipe Lemeb85a6372016-01-14 16:16:16 -08001703 out.endTag(null, TAG_WHITELIST);
1704
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001705 out.endDocument();
1706
1707 mPolicyFile.finishWrite(fos);
1708 } catch (IOException e) {
1709 if (fos != null) {
1710 mPolicyFile.failWrite(fos);
1711 }
1712 }
1713 }
1714
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001715 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001716 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001717 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001718
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001719 if (!UserHandle.isApp(uid)) {
1720 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001721 }
Felipe Lemef0823852016-06-08 13:43:08 -07001722 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001723 final long token = Binder.clearCallingIdentity();
1724 try {
1725 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1726 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001727 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001728 }
1729 } finally {
1730 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001731 }
1732 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001733 }
1734
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001735 @Override
1736 public void addUidPolicy(int uid, int policy) {
1737 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001738
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001739 if (!UserHandle.isApp(uid)) {
1740 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1741 }
1742
Felipe Lemef0823852016-06-08 13:43:08 -07001743 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001744 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1745 policy |= oldPolicy;
1746 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001747 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001748 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001749 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001750 }
1751
1752 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001753 public void removeUidPolicy(int uid, int policy) {
1754 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1755
1756 if (!UserHandle.isApp(uid)) {
1757 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1758 }
1759
Felipe Lemef0823852016-06-08 13:43:08 -07001760 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001761 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1762 policy = oldPolicy & ~policy;
1763 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001764 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001765 }
1766 }
1767 }
1768
Felipe Lemef0823852016-06-08 13:43:08 -07001769 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1770 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001771
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001772 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1773 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1774 isBlacklisted ? 1 : 0).sendToTarget();
1775
1776 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001777 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001778 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1779 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001780 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001781 .sendToTarget();
1782 }
1783 }
1784
Felipe Lemef0823852016-06-08 13:43:08 -07001785 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001786 mUidPolicy.put(uid, policy);
1787
1788 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001789 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001790 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001791 synchronized (mNetworkPoliciesSecondLock) {
1792 writePolicyAL();
1793 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001794 }
1795 }
1796
1797 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001798 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001799 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1800
Felipe Lemef0823852016-06-08 13:43:08 -07001801 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001802 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001803 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001804 }
1805
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001806 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001807 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001808 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1809
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001810 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001811 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001812 for (int i = 0; i < mUidPolicy.size(); i++) {
1813 final int uid = mUidPolicy.keyAt(i);
1814 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001815 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1816 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001817 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001818 }
1819 }
1820 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001821 return uids;
1822 }
1823
1824 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001825 * Removes any persistable state associated with given {@link UserHandle}, persisting
1826 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001827 */
Felipe Lemef0823852016-06-08 13:43:08 -07001828 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001829
Felipe Lemef0823852016-06-08 13:43:08 -07001830 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001831 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001832
Felipe Lemea110eec2016-04-29 09:58:06 -07001833 // Remove entries from revoked default restricted background UID whitelist
1834 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1835 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1836 if (UserHandle.getUserId(uid) == userId) {
1837 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001838 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001839 }
1840 }
1841
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001842 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001843 int[] uids = new int[0];
1844 for (int i = 0; i < mUidPolicy.size(); i++) {
1845 final int uid = mUidPolicy.keyAt(i);
1846 if (UserHandle.getUserId(uid) == userId) {
1847 uids = appendInt(uids, uid);
1848 }
1849 }
1850
1851 if (uids.length > 0) {
1852 for (int uid : uids) {
1853 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001854 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001855 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001856 }
Felipe Lemef0823852016-06-08 13:43:08 -07001857 synchronized (mNetworkPoliciesSecondLock) {
1858 updateRulesForGlobalChangeAL(true);
1859 if (writePolicy && changed) {
1860 writePolicyAL();
1861 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001862 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001863 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001864 }
1865
1866 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001867 public void setConnectivityListener(INetworkPolicyListener listener) {
1868 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1869 if (mConnectivityListener != null) {
1870 throw new IllegalStateException("Connectivity listener already registered");
1871 }
1872 mConnectivityListener = listener;
1873 }
1874
1875 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001876 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001877 // TODO: create permission for observing network policy
1878 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001879 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001880 }
1881
1882 @Override
1883 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001884 // TODO: create permission for observing network policy
1885 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001886 mListeners.unregister(listener);
1887 }
1888
Jeff Sharkey1b861272011-05-22 00:34:52 -07001889 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001890 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001891 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1892
Felipe Leme6a05eee2016-02-19 14:43:51 -08001893 final long token = Binder.clearCallingIdentity();
1894 try {
1895 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001896 synchronized (mUidRulesFirstLock) {
1897 synchronized (mNetworkPoliciesSecondLock) {
1898 normalizePoliciesNL(policies);
1899 updateNetworkEnabledNL();
1900 updateNetworkRulesNL();
1901 updateNotificationsNL();
1902 writePolicyAL();
1903 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001904 }
1905 } finally {
1906 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001907 }
1908 }
1909
Felipe Lemef0823852016-06-08 13:43:08 -07001910 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001911 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001912 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1913 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001914 }
1915
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001916 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001917 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001918 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001919 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001920 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1921 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1922 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001923 } catch (SecurityException e) {
1924 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001925
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001926 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1927 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1928 return new NetworkPolicy[0];
1929 }
Svet Ganov16a16892015-04-16 10:32:04 -07001930 }
1931
Felipe Lemef0823852016-06-08 13:43:08 -07001932 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001933 final int size = mNetworkPolicy.size();
1934 final NetworkPolicy[] policies = new NetworkPolicy[size];
1935 for (int i = 0; i < size; i++) {
1936 policies[i] = mNetworkPolicy.valueAt(i);
1937 }
1938 return policies;
1939 }
1940 }
1941
Felipe Lemef0823852016-06-08 13:43:08 -07001942 private void normalizePoliciesNL() {
1943 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001944 }
1945
Felipe Lemef0823852016-06-08 13:43:08 -07001946 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001947 final TelephonyManager tele = TelephonyManager.from(mContext);
1948 final String[] merged = tele.getMergedSubscriberIds();
1949
1950 mNetworkPolicy.clear();
1951 for (NetworkPolicy policy : policies) {
1952 // When two normalized templates conflict, prefer the most
1953 // restrictive policy
1954 policy.template = NetworkTemplate.normalize(policy.template, merged);
1955 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1956 if (existing == null || existing.compareTo(policy) > 0) {
1957 if (existing != null) {
1958 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1959 }
1960 mNetworkPolicy.put(policy.template, policy);
1961 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001962 }
1963 }
1964
1965 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001966 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001967 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001968
1969 final long token = Binder.clearCallingIdentity();
1970 try {
1971 performSnooze(template, TYPE_LIMIT);
1972 } finally {
1973 Binder.restoreCallingIdentity(token);
1974 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001975 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001976
Dianne Hackborn497175b2014-07-01 12:56:08 -07001977 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001978 maybeRefreshTrustedTime();
1979 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001980 synchronized (mUidRulesFirstLock) {
1981 synchronized (mNetworkPoliciesSecondLock) {
1982 // find and snooze local policy that matches
1983 final NetworkPolicy policy = mNetworkPolicy.get(template);
1984 if (policy == null) {
1985 throw new IllegalArgumentException("unable to find policy for " + template);
1986 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001987
Felipe Lemef0823852016-06-08 13:43:08 -07001988 switch (type) {
1989 case TYPE_WARNING:
1990 policy.lastWarningSnooze = currentTime;
1991 break;
1992 case TYPE_LIMIT:
1993 policy.lastLimitSnooze = currentTime;
1994 break;
1995 default:
1996 throw new IllegalArgumentException("unexpected type");
1997 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001998
Felipe Lemef0823852016-06-08 13:43:08 -07001999 normalizePoliciesNL();
2000 updateNetworkEnabledNL();
2001 updateNetworkRulesNL();
2002 updateNotificationsNL();
2003 writePolicyAL();
2004 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002005 }
2006 }
2007
2008 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002009 public void onTetheringChanged(String iface, boolean tethering) {
2010 // No need to enforce permission because setRestrictBackground() will do it.
2011 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002012 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002013 if (mRestrictBackground && tethering) {
2014 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2015 setRestrictBackground(false);
2016 }
2017 }
2018 }
2019
2020 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002021 public void setRestrictBackground(boolean restrictBackground) {
2022 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002023 final long token = Binder.clearCallingIdentity();
2024 try {
2025 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002026 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002027 if (restrictBackground == mRestrictBackground) {
2028 // Ideally, UI should never allow this scenario...
2029 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2030 return;
2031 }
Felipe Lemef0823852016-06-08 13:43:08 -07002032 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002033 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002034
Felipe Leme6a05eee2016-02-19 14:43:51 -08002035 } finally {
2036 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002037 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002038
2039 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2040 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002041 }
2042
Felipe Lemef0823852016-06-08 13:43:08 -07002043 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002044 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002045 final boolean oldRestrictBackground = mRestrictBackground;
2046 mRestrictBackground = restrictBackground;
2047 // Must whitelist foreground apps before turning data saver mode on.
2048 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2049 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002050 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002051 try {
2052 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2053 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2054 mRestrictBackground = oldRestrictBackground;
2055 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002056 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002057 return;
2058 }
2059 } catch (RemoteException e) {
2060 // ignored; service lives in system_server
2061 }
Felipe Lemef0823852016-06-08 13:43:08 -07002062 synchronized (mNetworkPoliciesSecondLock) {
2063 updateNotificationsNL();
2064 writePolicyAL();
2065 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002066 }
2067
Felipe Leme46b451f2016-08-19 08:46:17 -07002068 /**
2069 * @deprecated - should use {@link #setUidPolicy(int, int)} directly.
2070 */
Jeff Sharkey46645002011-07-27 21:11:21 -07002071 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002072 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002073 public void addRestrictBackgroundWhitelistedUid(int uid) {
2074 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002075 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002076 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002077 int changed;
2078 synchronized (mUidRulesFirstLock) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002079 final int oldUidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2080 oldStatus = (oldUidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme47585ba2016-02-09 16:56:32 -08002081 if (oldStatus) {
2082 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2083 return;
2084 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002085 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002086 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -07002087 setUidPolicyUncheckedUL(uid, oldUidPolicy, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002088 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2089 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2090 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2091 + " from revoked restrict background whitelist");
2092 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2093 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002094 if (needFirewallRules) {
2095 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002096 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002097 }
2098 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002099 synchronized (mNetworkPoliciesSecondLock) {
2100 writePolicyAL();
2101 }
2102 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002103 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002104 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2105 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002106 }
2107
Felipe Leme46b451f2016-08-19 08:46:17 -07002108 /**
2109 * @deprecated - should use {@link #setUidPolicy(int, int)} directly.
2110 */
Felipe Lemeb85a6372016-01-14 16:16:16 -08002111 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002112 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002113 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2114 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002115 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002116 synchronized (mUidRulesFirstLock) {
2117 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002118 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002119 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2120 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002121 }
2122
Felipe Leme70c57c22016-03-29 10:45:13 -07002123 /**
2124 * Removes a uid from the restricted background whitelist, returning whether its current
2125 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2126 */
Felipe Lemef0823852016-06-08 13:43:08 -07002127 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002128 boolean updateNow) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002129 final boolean oldStatus =
2130 (mUidPolicy.get(uid, POLICY_NONE) & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme46c4fc32016-05-04 09:21:43 -07002131 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002132 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2133 return false;
2134 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002135 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002136 if (oldStatus) {
2137 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -07002138 mUidPolicy.delete(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002139 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002140 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2141 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2142 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2143 + " to revoked restrict background whitelist");
2144 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2145 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002146 if (needFirewallRules) {
2147 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002148 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002149 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002150 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002151 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002152 synchronized (mNetworkPoliciesSecondLock) {
2153 writePolicyAL();
2154 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002155 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002156 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2157 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002158 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002159 }
2160
Felipe Leme46b451f2016-08-19 08:46:17 -07002161 /**
2162 * @deprecated - should use {@link #getUidsWithPolicy(int)} instead, but first need to change
2163 * that method to use logical OR (|).
2164 */
Felipe Lemeb85a6372016-01-14 16:16:16 -08002165 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002166 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002167 public int[] getRestrictBackgroundWhitelistedUids() {
2168 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme46b451f2016-08-19 08:46:17 -07002169 int[] whitelist = null;
Felipe Lemef0823852016-06-08 13:43:08 -07002170 synchronized (mUidRulesFirstLock) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002171 // First calculate size
2172 int size = 0;
2173 int policySize = mUidPolicy.size();
2174 for (int i = 0; i < policySize; i++) {
2175 if ((mUidPolicy.valueAt(i) & POLICY_ALLOW_METERED_BACKGROUND) != 0) {
2176 size ++;
2177 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002178 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002179 whitelist = new int[size];
2180 // Then populate it.
2181 if (size > 0) {
2182 int index = 0;
2183 for (int i = 0; i < policySize; i++) {
2184 final int uid = mUidPolicy.keyAt(i);
2185 if ((mUidPolicy.valueAt(i) & POLICY_ALLOW_METERED_BACKGROUND) != 0) {
2186 whitelist[index++] = uid;
2187 }
2188 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002189 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002190 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002191 if (LOGV) {
2192 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2193 + Arrays.toString(whitelist));
2194 }
2195 return whitelist;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002196 }
2197
2198 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002199 public int getRestrictBackgroundByCaller() {
2200 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2201 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002202
Felipe Lemef0823852016-06-08 13:43:08 -07002203 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002204 // Must clear identity because getUidPolicy() is restricted to system.
2205 final long token = Binder.clearCallingIdentity();
2206 final int policy;
2207 try {
2208 policy = getUidPolicy(uid);
2209 } finally {
2210 Binder.restoreCallingIdentity(token);
2211 }
2212 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2213 // App is blacklisted.
2214 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2215 }
Felipe Leme1b103232016-01-22 09:44:57 -08002216 if (!mRestrictBackground) {
2217 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2218 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002219 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002220 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2221 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2222 }
2223 }
2224
2225 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002226 public boolean getRestrictBackground() {
2227 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2228
Felipe Lemef0823852016-06-08 13:43:08 -07002229 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002230 return mRestrictBackground;
2231 }
2232 }
2233
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002234 @Override
2235 public void setDeviceIdleMode(boolean enabled) {
2236 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2237
Felipe Lemef0823852016-06-08 13:43:08 -07002238 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002239 if (mDeviceIdleMode != enabled) {
2240 mDeviceIdleMode = enabled;
2241 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002242 // Device idle change means we need to rebuild rules for all
2243 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002244 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002245 }
2246 if (enabled) {
2247 EventLogTags.writeDeviceIdleOnPhase("net");
2248 } else {
2249 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002250 }
2251 }
2252 }
2253 }
2254
Felipe Lemef0823852016-06-08 13:43:08 -07002255 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002256 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2257 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002258 if (policy.template.matches(ident)) {
2259 return policy;
2260 }
2261 }
2262 return null;
2263 }
2264
2265 @Override
2266 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2267 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2268
2269 // only returns usage summary, so we don't require caller to have
2270 // READ_NETWORK_USAGE_HISTORY.
2271 final long token = Binder.clearCallingIdentity();
2272 try {
2273 return getNetworkQuotaInfoUnchecked(state);
2274 } finally {
2275 Binder.restoreCallingIdentity(token);
2276 }
2277 }
2278
2279 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2280 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2281
2282 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002283 synchronized (mNetworkPoliciesSecondLock) {
2284 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002285 }
2286
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002287 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002288 // missing policy means we can't derive useful quota info
2289 return null;
2290 }
2291
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002292 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002293
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002294 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002295 final long start = computeLastCycleBoundary(currentTime, policy);
2296 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002297 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002298
2299 // report soft and hard limits under policy
2300 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2301 : NetworkQuotaInfo.NO_LIMIT;
2302 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2303 : NetworkQuotaInfo.NO_LIMIT;
2304
2305 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2306 }
2307
Jeff Sharkey46645002011-07-27 21:11:21 -07002308 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002309 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002310 if (state.networkInfo == null) {
2311 return false;
2312 }
2313
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002314 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2315
2316 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002317 synchronized (mNetworkPoliciesSecondLock) {
2318 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002319 }
2320
2321 if (policy != null) {
2322 return policy.metered;
2323 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002324 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002325 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002326 return true;
2327 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002328 return false;
2329 }
2330 }
2331
2332 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002333 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002334 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002335
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002336 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2337
Dianne Hackborn497175b2014-07-01 12:56:08 -07002338 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002339 for (String arg : args) {
2340 argSet.add(arg);
2341 }
2342
Felipe Lemef0823852016-06-08 13:43:08 -07002343 synchronized (mUidRulesFirstLock) {
2344 synchronized (mNetworkPoliciesSecondLock) {
2345 if (argSet.contains("--unsnooze")) {
2346 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2347 mNetworkPolicy.valueAt(i).clearSnooze();
2348 }
2349
2350 normalizePoliciesNL();
2351 updateNetworkEnabledNL();
2352 updateNetworkRulesNL();
2353 updateNotificationsNL();
2354 writePolicyAL();
2355
2356 fout.println("Cleared snooze timestamps");
2357 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002358 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002359
Felipe Lemef0823852016-06-08 13:43:08 -07002360 fout.print("System ready: "); fout.println(mSystemReady);
2361 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2362 fout.print("Restrict power: "); fout.println(mRestrictPower);
2363 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2364 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002365 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002366 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2367 fout.println(mNetworkPolicy.valueAt(i).toString());
2368 }
2369 fout.decreaseIndent();
2370
2371 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2372
2373 fout.println("Policy for UIDs:");
2374 fout.increaseIndent();
2375 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002376 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002377 final int uid = mUidPolicy.keyAt(i);
2378 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002379 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002380 fout.print(uid);
2381 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002382 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002383 fout.println();
2384 }
2385 fout.decreaseIndent();
2386
2387 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2388 if (size > 0) {
2389 fout.println("Power save whitelist (except idle) app ids:");
2390 fout.increaseIndent();
2391 for (int i = 0; i < size; i++) {
2392 fout.print("UID=");
2393 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2394 fout.print(": ");
2395 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2396 fout.println();
2397 }
2398 fout.decreaseIndent();
2399 }
2400
2401 size = mPowerSaveWhitelistAppIds.size();
2402 if (size > 0) {
2403 fout.println("Power save whitelist app ids:");
2404 fout.increaseIndent();
2405 for (int i = 0; i < size; i++) {
2406 fout.print("UID=");
2407 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2408 fout.print(": ");
2409 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2410 fout.println();
2411 }
2412 fout.decreaseIndent();
2413 }
2414
Felipe Leme46b451f2016-08-19 08:46:17 -07002415 final int[] restrictBackgroundWhitelistUids =
2416 getRestrictBackgroundWhitelistedUids();
2417 size = restrictBackgroundWhitelistUids.length;
Felipe Lemef0823852016-06-08 13:43:08 -07002418 if (size > 0) {
2419 fout.println("Restrict background whitelist uids:");
2420 fout.increaseIndent();
2421 for (int i = 0; i < size; i++) {
2422 fout.print("UID=");
Felipe Leme46b451f2016-08-19 08:46:17 -07002423 fout.print(restrictBackgroundWhitelistUids[i]);
Felipe Lemef0823852016-06-08 13:43:08 -07002424 fout.println();
2425 }
2426 fout.decreaseIndent();
2427 }
2428
2429 size = mDefaultRestrictBackgroundWhitelistUids.size();
2430 if (size > 0) {
2431 fout.println("Default restrict background whitelist uids:");
2432 fout.increaseIndent();
2433 for (int i = 0; i < size; i++) {
2434 fout.print("UID=");
2435 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2436 fout.println();
2437 }
2438 fout.decreaseIndent();
2439 }
2440
2441 size = mRestrictBackgroundWhitelistRevokedUids.size();
2442 if (size > 0) {
2443 fout.println("Default restrict background whitelist uids revoked by users:");
2444 fout.increaseIndent();
2445 for (int i = 0; i < size; i++) {
2446 fout.print("UID=");
2447 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2448 fout.println();
2449 }
2450 fout.decreaseIndent();
2451 }
2452
2453 final SparseBooleanArray knownUids = new SparseBooleanArray();
2454 collectKeys(mUidState, knownUids);
2455 collectKeys(mUidRules, knownUids);
2456
2457 fout.println("Status for all known UIDs:");
2458 fout.increaseIndent();
2459 size = knownUids.size();
2460 for (int i = 0; i < size; i++) {
2461 final int uid = knownUids.keyAt(i);
2462 fout.print("UID=");
2463 fout.print(uid);
2464
2465 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2466 fout.print(" state=");
2467 fout.print(state);
2468 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2469 fout.print(" (fg)");
2470 } else {
2471 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2472 ? " (fg svc)" : " (bg)");
2473 }
2474
2475 final int uidRules = mUidRules.get(uid, RULE_NONE);
2476 fout.print(" rules=");
2477 fout.print(uidRulesToString(uidRules));
2478 fout.println();
2479 }
2480 fout.decreaseIndent();
2481
2482 fout.println("Status for just UIDs with rules:");
2483 fout.increaseIndent();
2484 size = mUidRules.size();
2485 for (int i = 0; i < size; i++) {
2486 final int uid = mUidRules.keyAt(i);
2487 fout.print("UID=");
2488 fout.print(uid);
2489 final int uidRules = mUidRules.get(uid, RULE_NONE);
2490 fout.print(" rules=");
2491 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002492 fout.println();
2493 }
2494 fout.decreaseIndent();
2495 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002496 }
2497 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002498
2499 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002500 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2501 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002502 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002503 this, in, out, err, args, resultReceiver);
2504 }
2505
2506 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002507 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002508 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2509
Felipe Lemef0823852016-06-08 13:43:08 -07002510 synchronized (mUidRulesFirstLock) {
2511 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002512 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002513 }
2514
Felipe Lemef0823852016-06-08 13:43:08 -07002515 private boolean isUidForegroundUL(int uid) {
2516 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002517 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2518 }
2519
Felipe Lemef0823852016-06-08 13:43:08 -07002520 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002521 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002522 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002523 }
2524
Felipe Lemef0823852016-06-08 13:43:08 -07002525 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002526 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2527 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2528 }
2529
Felipe Lemef0823852016-06-08 13:43:08 -07002530 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002531 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002532 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002533 }
2534
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002535 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002536 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002537 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2538 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002539 */
Felipe Lemef0823852016-06-08 13:43:08 -07002540 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002541 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2542 if (oldUidState != uidState) {
2543 // state changed, push updated rules
2544 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002545 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002546 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2547 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002548 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002549 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002550 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002551 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002552 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002553 }
2554 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002555 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002556 }
Felipe Lemef0823852016-06-08 13:43:08 -07002557 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002558 }
Felipe Lemef0823852016-06-08 13:43:08 -07002559 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002560 }
2561 }
2562
Felipe Lemef0823852016-06-08 13:43:08 -07002563 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002564 final int index = mUidState.indexOfKey(uid);
2565 if (index >= 0) {
2566 final int oldUidState = mUidState.valueAt(index);
2567 mUidState.removeAt(index);
2568 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002569 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002570 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002571 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002572 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002573 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002574 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002575 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002576 }
Felipe Lemef0823852016-06-08 13:43:08 -07002577 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002578 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002579 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002580 }
2581 }
2582
Felipe Lemef28983d2016-03-25 12:18:23 -07002583 // adjust stats accounting based on foreground status
2584 private void updateNetworkStats(int uid, boolean uidForeground) {
2585 try {
2586 mNetworkStats.setUidForeground(uid, uidForeground);
2587 } catch (RemoteException e) {
2588 // ignored; service lives in system_server
2589 }
2590 }
2591
Felipe Lemef0823852016-06-08 13:43:08 -07002592 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002593 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002594 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002595 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002596 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002597 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002598 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002599 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002600 }
2601 }
2602
Felipe Leme011b98f2016-02-10 17:28:31 -08002603 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002604 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2605 }
2606
Felipe Lemef0823852016-06-08 13:43:08 -07002607 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002608 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2609 }
2610
Felipe Lemef0823852016-06-08 13:43:08 -07002611 void updateRulesForPowerSaveUL() {
2612 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002613 mUidFirewallPowerSaveRules);
2614 }
2615
Felipe Lemef0823852016-06-08 13:43:08 -07002616 void updateRuleForRestrictPowerUL(int uid) {
2617 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002618 }
2619
Felipe Lemef0823852016-06-08 13:43:08 -07002620 void updateRulesForDeviceIdleUL() {
2621 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002622 mUidFirewallDozableRules);
2623 }
2624
Felipe Lemef0823852016-06-08 13:43:08 -07002625 void updateRuleForDeviceIdleUL(int uid) {
2626 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002627 }
2628
Felipe Lemef28983d2016-03-25 12:18:23 -07002629 // NOTE: since both fw_dozable and fw_powersave uses the same map
2630 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002631 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002632 SparseIntArray rules) {
2633 if (enabled) {
2634 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002635 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002636 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002637 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002638 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002639 for (int ui = users.size() - 1; ui >= 0; ui--) {
2640 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002641 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002642 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2643 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2644 int uid = UserHandle.getUid(user.id, appId);
2645 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2646 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002647 }
2648 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2649 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2650 int uid = UserHandle.getUid(user.id, appId);
2651 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2652 }
2653 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002654 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002655 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002656 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2657 }
2658 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002659 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002660 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002661
Felipe Lemef0823852016-06-08 13:43:08 -07002662 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002663 }
2664
Felipe Lemef0823852016-06-08 13:43:08 -07002665 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002666 final int appId = UserHandle.getAppId(uid);
2667 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2668 }
2669
Felipe Lemef28983d2016-03-25 12:18:23 -07002670 // NOTE: since both fw_dozable and fw_powersave uses the same map
2671 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002672 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002673 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002674 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002675 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2676 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002677 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002678 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002679 }
2680 }
2681 }
2682
Felipe Lemef0823852016-06-08 13:43:08 -07002683 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002684 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2685 uidRules.clear();
2686
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002687 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002688 final List<UserInfo> users = mUserManager.getUsers();
2689 for (int ui = users.size() - 1; ui >= 0; ui--) {
2690 UserInfo user = users.get(ui);
2691 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2692 for (int uid : idleUids) {
2693 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002694 // quick check: if this uid doesn't have INTERNET permission, it
2695 // doesn't have network access anyway, so it is a waste to mess
2696 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002697 if (hasInternetPermissions(uid)) {
2698 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002699 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002700 }
2701 }
2702 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002703
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002704 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2705 }
2706
Felipe Lemef0823852016-06-08 13:43:08 -07002707 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002708 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002709
2710 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002711 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002712 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002713 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2714 } else {
2715 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2716 }
2717 }
2718
Felipe Lemef0823852016-06-08 13:43:08 -07002719 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002720 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002721 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002722 }
2723
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002724 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002725 * Update rules that might be changed by {@link #mRestrictBackground},
2726 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002727 */
Felipe Lemef0823852016-06-08 13:43:08 -07002728 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002729 long start;
2730 if (LOGD) start = System.currentTimeMillis();
2731
Felipe Lemef0823852016-06-08 13:43:08 -07002732 updateRulesForRestrictPowerUL();
2733 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002734
2735 // If the set of restricted networks may have changed, re-evaluate those.
2736 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002737 normalizePoliciesNL();
2738 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002739 }
2740 if (LOGD) {
2741 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002742 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002743 + delta + "ms");
2744 }
2745 }
2746
Felipe Lemef0823852016-06-08 13:43:08 -07002747 private void updateRulesForRestrictPowerUL() {
2748 updateRulesForDeviceIdleUL();
2749 updateRulesForAppIdleUL();
2750 updateRulesForPowerSaveUL();
2751 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002752 }
2753
Felipe Lemef0823852016-06-08 13:43:08 -07002754 private void updateRulesForRestrictBackgroundUL() {
2755 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002756 }
2757
2758 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2759 private static final int TYPE_RESTRICT_POWER = 2;
2760 @Retention(RetentionPolicy.SOURCE)
2761 @IntDef(flag = false, value = {
2762 TYPE_RESTRICT_BACKGROUND,
2763 TYPE_RESTRICT_POWER,
2764 })
2765 public @interface RestrictType {
2766 }
2767
2768 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002769 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002770 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002771
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002772 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002773 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002774 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002775 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2776 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2777 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002778
Felipe Leme03e689d2016-03-02 16:17:38 -08002779 final int usersSize = users.size();
2780 final int appsSize = apps.size();
2781 for (int i = 0; i < usersSize; i++) {
2782 final UserInfo user = users.get(i);
2783 for (int j = 0; j < appsSize; j++) {
2784 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002785 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002786 switch (type) {
2787 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002788 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002789 break;
2790 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002791 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002792 break;
2793 default:
2794 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2795 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002796 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002797 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002798 }
2799
Felipe Lemef0823852016-06-08 13:43:08 -07002800 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002801 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002802 for (int i = 0; i < users.size(); i++) {
2803 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002804 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002805 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002806 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002807 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002808 updateRuleForAppIdleUL(uid);
2809 updateRuleForDeviceIdleUL(uid);
2810 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002811 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002812 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002813 }
2814 }
2815 }
2816
Felipe Leme70c57c22016-03-29 10:45:13 -07002817 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2818 // methods below could be merged into a isUidValidForRules() method.
2819 private boolean isUidValidForBlacklistRules(int uid) {
2820 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002821 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002822 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002823 return true;
2824 }
2825
2826 return false;
2827 }
2828
Felipe Leme70c57c22016-03-29 10:45:13 -07002829 private boolean isUidValidForWhitelistRules(int uid) {
2830 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2831 }
2832
Amith Yamasani15e472352015-04-24 19:06:07 -07002833 private boolean isUidIdle(int uid) {
2834 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2835 final int userId = UserHandle.getUserId(uid);
2836
songjinshi0655edd2016-05-18 19:55:32 +08002837 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002838 for (String packageName : packages) {
2839 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2840 return false;
2841 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002842 }
2843 }
2844 return true;
2845 }
2846
2847 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002848 * Checks if an uid has INTERNET permissions.
2849 * <p>
2850 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002851 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002852 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002853 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002854 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002855 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002856 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002857 }
2858 } catch (RemoteException e) {
2859 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002860 return true;
2861 }
2862
2863 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002864 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002865 *
Felipe Leme781ba142016-05-09 16:24:48 -07002866 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002867 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002868 * <li>Doze mode
2869 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002870 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002871 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002872 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002873 *
2874 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002875 */
Felipe Lemef0823852016-06-08 13:43:08 -07002876 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002877 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002878 updateRuleForDeviceIdleUL(uid);
2879 updateRuleForAppIdleUL(uid);
2880 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002881
2882 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002883 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002884
2885 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002886 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002887 }
2888
Felipe Leme70c57c22016-03-29 10:45:13 -07002889 /**
2890 * Applies network rules to bandwidth controllers based on process state and user-defined
2891 * restrictions (blacklist / whitelist).
2892 *
2893 * <p>
2894 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2895 * networks:
2896 * <ul>
2897 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2898 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2899 * also blacklisted.
2900 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2901 * no UIDs other those whitelisted will have access.
2902 * <ul>
2903 *
2904 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2905 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2906 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2907 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002908 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002909 * {@link INetworkManagementService}, but this method should also be called in events (like
2910 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2911 * following rules should also be applied:
2912 *
2913 * <ul>
2914 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2915 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2916 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2917 * {@code bw_penalty_box}.
2918 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2919 * </ul>
2920 *
2921 * <p>For optimization, the rules are only applied on user apps that have internet access
2922 * permission, since there is no need to change the {@code iptables} rule if the app does not
2923 * have permission to use the internet.
2924 *
2925 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002926 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002927 */
Felipe Lemef0823852016-06-08 13:43:08 -07002928 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2929 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002930 }
2931
2932 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002933 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002934 * app is removed - it ignores the UID validity check.
2935 */
Felipe Lemef0823852016-06-08 13:43:08 -07002936 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002937 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2938 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2939 return;
2940 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002941
Dianne Hackborn497175b2014-07-01 12:56:08 -07002942 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002943 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002944 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002945
Felipe Leme781ba142016-05-09 16:24:48 -07002946 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002947 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002948 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2949 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002950
Felipe Leme70c57c22016-03-29 10:45:13 -07002951 // First step: define the new rule based on user restrictions and foreground state.
2952 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002953 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2954 newRule = RULE_TEMPORARY_ALLOW_METERED;
2955 } else if (isWhitelisted) {
2956 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002957 }
2958 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002959 if (isBlacklisted) {
2960 newRule = RULE_REJECT_METERED;
2961 } else if (mRestrictBackground && isWhitelisted) {
2962 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002963 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002964 }
Felipe Leme781ba142016-05-09 16:24:48 -07002965 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002966
Felipe Lemef28983d2016-03-25 12:18:23 -07002967 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002968 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002969 + ": isForeground=" +isForeground
2970 + ", isBlacklisted=" + isBlacklisted
2971 + ", isWhitelisted=" + isWhitelisted
2972 + ", oldRule=" + uidRulesToString(oldRule)
2973 + ", newRule=" + uidRulesToString(newRule)
2974 + ", newUidRules=" + uidRulesToString(newUidRules)
2975 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002976 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002977
Felipe Leme46c4fc32016-05-04 09:21:43 -07002978 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002979 mUidRules.delete(uid);
2980 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002981 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002982 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002983
Felipe Leme70c57c22016-03-29 10:45:13 -07002984 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002985 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002986 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002987 // Temporarily whitelist foreground app, removing from blacklist if necessary
2988 // (since bw_penalty_box prevails over bw_happy_box).
2989
2990 setMeteredNetworkWhitelist(uid, true);
2991 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2992 // but ideally it should be just:
2993 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002994 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002995 setMeteredNetworkBlacklist(uid, false);
2996 }
Felipe Leme781ba142016-05-09 16:24:48 -07002997 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002998 // Remove temporary whitelist from app that is not on foreground anymore.
2999
3000 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3001 // but ideally they should be just:
3002 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3003 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003004 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003005 setMeteredNetworkWhitelist(uid, false);
3006 }
Felipe Leme781ba142016-05-09 16:24:48 -07003007 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003008 setMeteredNetworkBlacklist(uid, true);
3009 }
Felipe Leme781ba142016-05-09 16:24:48 -07003010 } else if ((newRule & RULE_REJECT_METERED) != 0
3011 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003012 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003013 setMeteredNetworkBlacklist(uid, isBlacklisted);
3014 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003015 // Since blacklist prevails over whitelist, we need to handle the special case
3016 // where app is whitelisted and blacklisted at the same time (although such
3017 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003018 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003019 }
Felipe Leme781ba142016-05-09 16:24:48 -07003020 } else if ((newRule & RULE_ALLOW_METERED) != 0
3021 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003022 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003023 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003024 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003025 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003026 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3027 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003028 + ", whitelisted=" + isWhitelisted
3029 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003030 + ", newRule=" + uidRulesToString(newUidRules)
3031 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003032 }
Felipe Leme781ba142016-05-09 16:24:48 -07003033
3034 // Dispatch changed rule to existing listeners.
3035 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3036 }
3037 }
3038
3039 /**
3040 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3041 * listeners in case of change.
3042 * <p>
3043 * There are 3 power-related rules that affects whether an app has background access on
3044 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3045 * restriction, it's added to the equivalent firewall chain:
3046 * <ul>
3047 * <li>App is idle: {@code fw_standby} firewall chain.
3048 * <li>Device is idle: {@code fw_dozable} firewall chain.
3049 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3050 * </ul>
3051 * <p>
3052 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3053 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3054 * <p>
3055 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3056 */
Felipe Lemef0823852016-06-08 13:43:08 -07003057 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003058 if (!isUidValidForBlacklistRules(uid)) {
3059 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3060 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003061 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003062
Felipe Leme781ba142016-05-09 16:24:48 -07003063 final boolean isIdle = isUidIdle(uid);
3064 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Leme781ba142016-05-09 16:24:48 -07003065 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003066 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003067
Felipe Lemef0823852016-06-08 13:43:08 -07003068 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003069 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3070 int newRule = RULE_NONE;
3071
3072 // First step: define the new rule based on user restrictions and foreground state.
3073
3074 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3075 // by considering the foreground and non-foreground states.
3076 if (isForeground) {
3077 if (restrictMode) {
3078 newRule = RULE_ALLOW_ALL;
3079 }
3080 } else if (restrictMode) {
3081 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3082 }
3083
3084 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3085
3086 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003087 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003088 + ", isIdle: " + isIdle
3089 + ", mRestrictPower: " + mRestrictPower
3090 + ", mDeviceIdleMode: " + mDeviceIdleMode
3091 + ", isForeground=" + isForeground
3092 + ", isWhitelisted=" + isWhitelisted
3093 + ", oldRule=" + uidRulesToString(oldRule)
3094 + ", newRule=" + uidRulesToString(newRule)
3095 + ", newUidRules=" + uidRulesToString(newUidRules)
3096 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3097 }
3098
3099 if (newUidRules == RULE_NONE) {
3100 mUidRules.delete(uid);
3101 } else {
3102 mUidRules.put(uid, newUidRules);
3103 }
3104
3105 // Second step: notify listeners if state changed.
3106 if (newRule != oldRule) {
3107 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003108 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003109 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003110 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3111 } else {
3112 // All scenarios should have been covered above
3113 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3114 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003115 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003116 + ", newRule=" + uidRulesToString(newUidRules)
3117 + ", oldRule=" + uidRulesToString(oldUidRules));
3118 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003119 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003120 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003121 }
3122
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003123 private class AppIdleStateChangeListener
3124 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3125
3126 @Override
3127 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3128 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003129 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3130 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003131 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003132 synchronized (mUidRulesFirstLock) {
3133 updateRuleForAppIdleUL(uid);
3134 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003135 }
3136 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003137 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003138 }
3139
3140 @Override
3141 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003142 synchronized (mUidRulesFirstLock) {
3143 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003144 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003145 }
3146 }
3147
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003148 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3149 if (listener != null) {
3150 try {
3151 listener.onUidRulesChanged(uid, uidRules);
3152 } catch (RemoteException ignored) {
3153 }
3154 }
3155 }
3156
3157 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3158 String[] meteredIfaces) {
3159 if (listener != null) {
3160 try {
3161 listener.onMeteredIfacesChanged(meteredIfaces);
3162 } catch (RemoteException ignored) {
3163 }
3164 }
3165 }
3166
3167 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3168 boolean restrictBackground) {
3169 if (listener != null) {
3170 try {
3171 listener.onRestrictBackgroundChanged(restrictBackground);
3172 } catch (RemoteException ignored) {
3173 }
3174 }
3175 }
3176
3177 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3178 int uid, boolean whitelisted) {
3179 if (listener != null) {
3180 try {
3181 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3182 } catch (RemoteException ignored) {
3183 }
3184 }
3185 }
3186
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003187 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3188 int uid, boolean blacklisted) {
3189 if (listener != null) {
3190 try {
3191 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3192 } catch (RemoteException ignored) {
3193 }
3194 }
3195 }
3196
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003197 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003198 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003199 public boolean handleMessage(Message msg) {
3200 switch (msg.what) {
3201 case MSG_RULES_CHANGED: {
3202 final int uid = msg.arg1;
3203 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003204 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003205 final int length = mListeners.beginBroadcast();
3206 for (int i = 0; i < length; i++) {
3207 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003208 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003209 }
3210 mListeners.finishBroadcast();
3211 return true;
3212 }
3213 case MSG_METERED_IFACES_CHANGED: {
3214 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003215 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003216 final int length = mListeners.beginBroadcast();
3217 for (int i = 0; i < length; i++) {
3218 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003219 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003220 }
3221 mListeners.finishBroadcast();
3222 return true;
3223 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003224 case MSG_LIMIT_REACHED: {
3225 final String iface = (String) msg.obj;
3226
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003227 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003228 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003229 if (mMeteredIfaces.contains(iface)) {
3230 try {
3231 // force stats update to make sure we have
3232 // numbers that caused alert to trigger.
3233 mNetworkStats.forceUpdate();
3234 } catch (RemoteException e) {
3235 // ignored; service lives in system_server
3236 }
3237
Felipe Lemef0823852016-06-08 13:43:08 -07003238 updateNetworkEnabledNL();
3239 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003240 }
3241 }
3242 return true;
3243 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003244 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3245 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003246 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003247 final int length = mListeners.beginBroadcast();
3248 for (int i = 0; i < length; i++) {
3249 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003250 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003251 }
3252 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003253 final Intent intent =
3254 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3255 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3256 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3257 return true;
3258 }
3259 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003260 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3261 // - when an app is whitelisted
3262 // - when an app is blacklisted
3263 //
3264 // Whether the internal listeners (INetworkPolicyListener implementations) or
3265 // app broadcast receivers are notified depend on the following rules:
3266 //
3267 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3268 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3269 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003270 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003271 final boolean changed = msg.arg2 == 1;
3272 final Boolean whitelisted = (Boolean) msg.obj;
3273
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003274 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003275 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003276 final boolean whitelistedBool = whitelisted.booleanValue();
3277 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3278 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003279 final int length = mListeners.beginBroadcast();
3280 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003281 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003282 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3283 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003284 }
3285 mListeners.finishBroadcast();
3286 }
Felipe Leme9778f762016-01-27 14:46:39 -08003287 final PackageManager pm = mContext.getPackageManager();
3288 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003289 if (changed && packages != null) {
3290 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003291 final int userId = UserHandle.getUserId(uid);
3292 for (String packageName : packages) {
3293 final Intent intent = new Intent(
3294 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3295 intent.setPackage(packageName);
3296 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3297 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3298 }
Felipe Leme9778f762016-01-27 14:46:39 -08003299 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003300 return true;
3301 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003302 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3303 final int uid = msg.arg1;
3304 final boolean blacklisted = msg.arg2 == 1;
3305
3306 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3307 blacklisted);
3308 final int length = mListeners.beginBroadcast();
3309 for (int i = 0; i < length; i++) {
3310 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3311 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3312 blacklisted);
3313 }
3314 mListeners.finishBroadcast();
3315 return true;
3316 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003317 case MSG_ADVISE_PERSIST_THRESHOLD: {
3318 final long lowestRule = (Long) msg.obj;
3319 try {
3320 // make sure stats are recorded frequently enough; we aim
3321 // for 2MB threshold for 2GB/month rules.
3322 final long persistThreshold = lowestRule / 1000;
3323 mNetworkStats.advisePersistThreshold(persistThreshold);
3324 } catch (RemoteException e) {
3325 // ignored; service lives in system_server
3326 }
3327 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003328 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003329 case MSG_UPDATE_INTERFACE_QUOTA: {
3330 removeInterfaceQuota((String) msg.obj);
3331 // int params need to be stitched back into a long
3332 setInterfaceQuota((String) msg.obj,
3333 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3334 return true;
3335 }
3336 case MSG_REMOVE_INTERFACE_QUOTA: {
3337 removeInterfaceQuota((String) msg.obj);
3338 return true;
3339 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003340 default: {
3341 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003342 }
3343 }
3344 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003345 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003346
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003347 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003348 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003349 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003350 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003351 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003352 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003353 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003354 }
3355 }
3356
3357 private void removeInterfaceQuota(String iface) {
3358 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003359 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003360 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003361 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003362 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003363 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003364 }
3365 }
3366
Felipe Leme70c57c22016-03-29 10:45:13 -07003367 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3368 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003369 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003370 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003371 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003372 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3373 } catch (RemoteException e) {
3374 // ignored; service lives in system_server
3375 }
3376 }
3377
3378 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3379 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3380 try {
3381 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3382 } catch (IllegalStateException e) {
3383 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003384 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003385 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003386 }
3387 }
3388
Amith Yamasani15e472352015-04-24 19:06:07 -07003389 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003390 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3391 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3392 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003393 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003394 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003395 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003396 int size = uidRules.size();
3397 int[] uids = new int[size];
3398 int[] rules = new int[size];
3399 for(int index = size - 1; index >= 0; --index) {
3400 uids[index] = uidRules.keyAt(index);
3401 rules[index] = uidRules.valueAt(index);
3402 }
3403 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003404 } catch (IllegalStateException e) {
3405 Log.wtf(TAG, "problem setting firewall uid rules", e);
3406 } catch (RemoteException e) {
3407 // ignored; service lives in system_server
3408 }
3409 }
3410
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003411 /**
3412 * Add or remove a uid to the firewall blacklist for all network ifaces.
3413 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003414 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003415 if (chain == FIREWALL_CHAIN_DOZABLE) {
3416 mUidFirewallDozableRules.put(uid, rule);
3417 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3418 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003419 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3420 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003421 }
3422
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003423 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003424 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003425 } catch (IllegalStateException e) {
3426 Log.wtf(TAG, "problem setting firewall uid rules", e);
3427 } catch (RemoteException e) {
3428 // ignored; service lives in system_server
3429 }
3430 }
3431
3432 /**
3433 * Add or remove a uid to the firewall blacklist for all network ifaces.
3434 */
Felipe Lemef0823852016-06-08 13:43:08 -07003435 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003436 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3437 mFirewallChainStates.get(chain) == enable) {
3438 // All is the same, nothing to do.
3439 return;
3440 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003441 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003442 try {
3443 mNetworkManager.setFirewallChainEnabled(chain, enable);
3444 } catch (IllegalStateException e) {
3445 Log.wtf(TAG, "problem enable firewall chain", e);
3446 } catch (RemoteException e) {
3447 // ignored; service lives in system_server
3448 }
3449 }
3450
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003451 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3452 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003453 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003454 } catch (RuntimeException e) {
3455 Slog.w(TAG, "problem reading network stats: " + e);
3456 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003457 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003458 // ignored; service lives in system_server
3459 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003460 }
3461 }
3462
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003463 private boolean isBandwidthControlEnabled() {
3464 final long token = Binder.clearCallingIdentity();
3465 try {
3466 return mNetworkManager.isBandwidthControlEnabled();
3467 } catch (RemoteException e) {
3468 // ignored; service lives in system_server
3469 return false;
3470 } finally {
3471 Binder.restoreCallingIdentity(token);
3472 }
3473 }
3474
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003475 /**
3476 * Try refreshing {@link #mTime} when stale.
3477 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003478 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003479 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003480 mTime.forceRefresh();
3481 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003482 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003483
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003484 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003485 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3486 }
3487
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003488 private static Intent buildAllowBackgroundDataIntent() {
3489 return new Intent(ACTION_ALLOW_BACKGROUND);
3490 }
3491
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003492 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3493 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3494 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3495 return intent;
3496 }
3497
Wei Liu546cb772016-07-21 16:19:01 -07003498 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003499 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003500 intent.setComponent(ComponentName.unflattenFromString(
3501 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003502 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3503 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3504 return intent;
3505 }
3506
Wei Liu546cb772016-07-21 16:19:01 -07003507 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003508 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003509 intent.setComponent(ComponentName.unflattenFromString(
3510 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003511 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3512 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3513 return intent;
3514 }
3515
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003516 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003517 public void addIdleHandler(IdleHandler handler) {
3518 mHandler.getLooper().getQueue().addIdleHandler(handler);
3519 }
3520
Jeff Sharkey1b861272011-05-22 00:34:52 -07003521 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3522 final int size = source.size();
3523 for (int i = 0; i < size; i++) {
3524 target.put(source.keyAt(i), true);
3525 }
3526 }
3527
Stuart Scottf1fb3972015-04-02 18:00:02 -07003528 @Override
3529 public void factoryReset(String subscriber) {
3530 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3531
Stuart Scotte3e314d2015-04-20 14:07:45 -07003532 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3533 return;
3534 }
3535
Stuart Scottf1fb3972015-04-02 18:00:02 -07003536 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003537 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003538 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3539 for (NetworkPolicy policy : policies) {
3540 if (policy.template.equals(template)) {
3541 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3542 policy.inferred = false;
3543 policy.clearSnooze();
3544 }
3545 }
3546 setNetworkPolicies(policies);
3547
3548 // Turn restrict background data off
3549 setRestrictBackground(false);
3550
Stuart Scotte3e314d2015-04-20 14:07:45 -07003551 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3552 // Remove app's "restrict background data" flag
3553 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3554 setUidPolicy(uid, POLICY_NONE);
3555 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003556 }
3557 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003558
3559 private class MyPackageMonitor extends PackageMonitor {
3560
3561 @Override
3562 public void onPackageRemoved(String packageName, int uid) {
3563 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003564 synchronized (mUidRulesFirstLock) {
3565 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3566 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003567 }
3568 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003569 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003570
3571 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3572
3573 @Override
3574 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003575 synchronized (mUidRulesFirstLock) {
3576 boolean changed = removeUserStateUL(userId, false);
3577 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003578 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003579 synchronized (mNetworkPoliciesSecondLock) {
3580 writePolicyAL();
3581 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003582 }
3583 }
3584 }
3585 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003586}