blob: a39d5c8cdcc7b5bac3327fd13eeba3fa1d3f0d7a [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
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700285 private static final int MSG_RULES_CHANGED = 1;
286 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800287 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800288 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700289 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
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,
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700415 NtpTrustedTime.getInstance(context), getSystemDir(), false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700416 }
417
418 private static File getSystemDir() {
419 return new File(Environment.getDataDirectory(), "system");
420 }
421
422 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700423 INetworkStatsService networkStats, INetworkManagementService networkManagement,
424 TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700425 mContext = checkNotNull(context, "missing context");
426 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700427 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700428 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700429 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700430 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700431 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700432 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800433 mIPm = AppGlobals.getPackageManager();
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700434
Amith Yamasani450a16b2013-09-18 16:28:50 -0700435 HandlerThread thread = new HandlerThread(TAG);
436 thread.start();
437 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700438
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700439 mSuppressDefaultPolicy = suppressDefaultPolicy;
440
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700441 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700442
443 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800444
445 mPackageMonitor = new MyPackageMonitor();
Felipe Lemed17fda42016-04-29 11:12:45 -0700446
447 // Expose private service for system components to use.
448 LocalServices.addService(NetworkPolicyManagerInternal.class,
449 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700450 }
451
452 public void bindConnectivityManager(IConnectivityManager connManager) {
453 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700454 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700455
Jeff Sharkey497e4432011-06-14 17:27:29 -0700456 public void bindNotificationManager(INotificationManager notifManager) {
457 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
458 }
459
Felipe Lemef0823852016-06-08 13:43:08 -0700460 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700461 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700462 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
463 mPowerSaveWhitelistExceptIdleAppIds.clear();
464 if (whitelist != null) {
465 for (int uid : whitelist) {
466 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
467 }
468 }
469 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700470 mPowerSaveWhitelistAppIds.clear();
471 if (whitelist != null) {
472 for (int uid : whitelist) {
473 mPowerSaveWhitelistAppIds.put(uid, true);
474 }
475 }
476 } catch (RemoteException e) {
477 }
478 }
479
Felipe Lemea9505cc2016-02-26 10:28:41 -0800480 /**
481 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
482 * revoke the whitelist.
483 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700484 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800485 */
Felipe Lemef0823852016-06-08 13:43:08 -0700486 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800487 final List<UserInfo> users = mUserManager.getUsers();
488 final int numberUsers = users.size();
489
Felipe Lemea110eec2016-04-29 09:58:06 -0700490 boolean changed = false;
491 for (int i = 0; i < numberUsers; i++) {
492 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700493 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700494 }
495 return changed;
496 }
497
Felipe Lemef0823852016-06-08 13:43:08 -0700498 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700499 final SystemConfig sysConfig = SystemConfig.getInstance();
500 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800501 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
502 boolean changed = false;
503 for (int i = 0; i < allowDataUsage.size(); i++) {
504 final String pkg = allowDataUsage.valueAt(i);
505 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700506 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
507 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800508 final ApplicationInfo app;
509 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700510 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800511 } catch (PackageManager.NameNotFoundException e) {
512 // Should not happen
513 Slog.wtf(TAG, "No ApplicationInfo for package " + pkg);
514 continue;
515 }
516 if (!app.isPrivilegedApp()) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700517 Slog.wtf(TAG, "pm.getApplicationInfoAsUser() returned non-privileged app: " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800518 continue;
519 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700520 final int uid = UserHandle.getUid(userId, app.uid);
521 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
522 if (LOGD)
523 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
524 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800525 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700526 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
527 Slog.i(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
528 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700529 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700530 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800531 }
532 }
533 return changed;
534 }
535
Felipe Lemef0823852016-06-08 13:43:08 -0700536 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700537 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700538 // Clear the states of the current whitelist
539 final int N = mPowerSaveTempWhitelistAppIds.size();
540 for (int i = 0; i < N; i++) {
541 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
542 }
543 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700544 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700545 if (whitelist != null) {
546 for (int uid : whitelist) {
547 mPowerSaveTempWhitelistAppIds.put(uid, true);
548 }
549 }
550 } catch (RemoteException e) {
551 }
552 }
553
Amith Yamasani06f08062015-06-12 13:23:33 -0700554 /**
555 * Remove unnecessary entries in the temp whitelist
556 */
Felipe Lemef0823852016-06-08 13:43:08 -0700557 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700558 final int N = mPowerSaveTempWhitelistAppIds.size();
559 for (int i = N - 1; i >= 0; i--) {
560 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
561 mPowerSaveTempWhitelistAppIds.removeAt(i);
562 }
563 }
564 }
565
Jeff Sharkeya4620792011-05-20 15:29:23 -0700566 public void systemReady() {
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700567 if (!isBandwidthControlEnabled()) {
568 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
569 return;
570 }
571
Amith Yamasani15e472352015-04-24 19:06:07 -0700572 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
573
Felipe Lemeb85a6372016-01-14 16:16:16 -0800574 mPackageMonitor.register(mContext, mHandler.getLooper(), UserHandle.ALL, true);
575
Felipe Lemef0823852016-06-08 13:43:08 -0700576 synchronized (mUidRulesFirstLock) {
577 synchronized (mNetworkPoliciesSecondLock) {
578 updatePowerSaveWhitelistUL();
579 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
580 mPowerManagerInternal.registerLowPowerModeObserver(
581 new PowerManagerInternal.LowPowerModeListener() {
582 @Override
583 public void onLowPowerModeChanged(boolean enabled) {
584 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
585 synchronized (mUidRulesFirstLock) {
586 if (mRestrictPower != enabled) {
587 mRestrictPower = enabled;
588 updateRulesForRestrictPowerUL();
589 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700590 }
591 }
Felipe Lemef0823852016-06-08 13:43:08 -0700592 });
593 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
594
595 mSystemReady = true;
596
597 // read policy from disk
598 readPolicyAL();
599
600 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
601 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700602 }
Felipe Lemed31a97f2016-05-06 14:53:50 -0700603
Felipe Lemef0823852016-06-08 13:43:08 -0700604 setRestrictBackgroundUL(mRestrictBackground);
605 updateRulesForGlobalChangeAL(false);
606 updateNotificationsNL();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800607 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700608 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700609
Jeff Sharkeya4620792011-05-20 15:29:23 -0700610 try {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700611 mActivityManager.registerUidObserver(mUidObserver,
612 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700613 mNetworkManager.registerObserver(mAlertObserver);
614 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700615 // ignored; both services live in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700616 }
617
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700618 // listen for changes to power save whitelist
619 final IntentFilter whitelistFilter = new IntentFilter(
620 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
621 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
622
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700623 DeviceIdleController.LocalService deviceIdleService
624 = LocalServices.getService(DeviceIdleController.LocalService.class);
625 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
626
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700627 // watch for network interfaces to be claimed
Erik Klinef851d6d2015-04-20 16:03:48 +0900628 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700629 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
630
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700631 // listen for package changes to update policy
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700632 final IntentFilter packageFilter = new IntentFilter();
633 packageFilter.addAction(ACTION_PACKAGE_ADDED);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700634 packageFilter.addDataScheme("package");
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700635 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700636
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700637 // listen for UID changes to update policy
638 mContext.registerReceiver(
639 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
640
641 // listen for user changes to update policy
642 final IntentFilter userFilter = new IntentFilter();
643 userFilter.addAction(ACTION_USER_ADDED);
644 userFilter.addAction(ACTION_USER_REMOVED);
645 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
646
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700647 // listen for stats update events
Jeff Sharkey497e4432011-06-14 17:27:29 -0700648 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
649 mContext.registerReceiver(
650 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
651
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700652 // listen for restrict background changes from notifications
653 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
654 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
655
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800656 // listen for snooze warning from notifications
657 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
658 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
659 MANAGE_NETWORK_POLICY, mHandler);
660
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700661 // listen for configured wifi networks to be removed
662 final IntentFilter wifiConfigFilter = new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700663 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700664
665 // listen for wifi state changes to catch metered hint
666 final IntentFilter wifiStateFilter = new IntentFilter(
667 WifiManager.NETWORK_STATE_CHANGED_ACTION);
Vinit Deshpande92d141f2014-09-10 18:05:10 -0700668 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700669
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700670 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Amith Yamasani15e472352015-04-24 19:06:07 -0700671
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700672 }
673
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700674 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700675 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700676 synchronized (mUidRulesFirstLock) {
677 updateUidStateUL(uid, procState);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700678 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700679 }
680
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700681 @Override public void onUidGone(int uid) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700682 synchronized (mUidRulesFirstLock) {
683 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700684 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700685 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700686
687 @Override public void onUidActive(int uid) throws RemoteException {
688 }
689
690 @Override public void onUidIdle(int uid) throws RemoteException {
691 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700692 };
693
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700694 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700695 @Override
696 public void onReceive(Context context, Intent intent) {
697 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700698 synchronized (mUidRulesFirstLock) {
699 updatePowerSaveWhitelistUL();
700 updateRulesForRestrictPowerUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700701 }
702 }
703 };
704
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700705 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
706 @Override
707 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700708 synchronized (mUidRulesFirstLock) {
709 updatePowerSaveTempWhitelistUL();
710 updateRulesForTempWhitelistChangeUL();
711 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700712 }
713 }
714 };
715
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700716 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700717 @Override
718 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700719 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700720
721 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700722 final int uid = intent.getIntExtra(EXTRA_UID, -1);
723 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700724
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700725 if (ACTION_PACKAGE_ADDED.equals(action)) {
726 // update rules for UID, since it might be subject to
727 // global background data policy
728 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700729 synchronized (mUidRulesFirstLock) {
730 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700731 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700732 }
733 }
734 };
735
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700736 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700737 @Override
738 public void onReceive(Context context, Intent intent) {
739 // on background handler thread, and UID_REMOVED is protected
740
741 final int uid = intent.getIntExtra(EXTRA_UID, -1);
742 if (uid == -1) return;
743
744 // remove any policy and update rules to clean up
745 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700746 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700747 mUidPolicy.delete(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700748 updateRestrictionRulesForUidUL(uid);
749 synchronized (mNetworkPoliciesSecondLock) {
750 writePolicyAL();
751 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700752 }
753 }
754 };
755
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700756 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700757 @Override
758 public void onReceive(Context context, Intent intent) {
759 // on background handler thread, and USER_ADDED and USER_REMOVED
760 // broadcasts are protected
761
762 final String action = intent.getAction();
763 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
764 if (userId == -1) return;
765
Amith Yamasani15e472352015-04-24 19:06:07 -0700766 switch (action) {
767 case ACTION_USER_REMOVED:
768 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700769 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800770 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700771 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700772 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700773 if (action == ACTION_USER_ADDED) {
774 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700775 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700776 }
777 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700778 synchronized (mNetworkPoliciesSecondLock) {
779 updateRulesForGlobalChangeAL(true);
780 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700781 }
782 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700783 }
784 }
785 };
786
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700787 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700788 * Receiver that watches for {@link INetworkStatsService} updates, which we
789 * use to check against {@link NetworkPolicy#warningBytes}.
790 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700791 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700792 @Override
793 public void onReceive(Context context, Intent intent) {
794 // on background handler thread, and verified
795 // READ_NETWORK_USAGE_HISTORY permission above.
796
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800797 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700798 synchronized (mNetworkPoliciesSecondLock) {
799 updateNetworkEnabledNL();
800 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700801 }
802 }
803 };
804
805 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700806 * Receiver that watches for {@link Notification} control of
807 * {@link #mRestrictBackground}.
808 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700809 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700810 @Override
811 public void onReceive(Context context, Intent intent) {
812 // on background handler thread, and verified MANAGE_NETWORK_POLICY
813 // permission above.
814
815 setRestrictBackground(false);
816 }
817 };
818
819 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800820 * Receiver that watches for {@link Notification} control of
821 * {@link NetworkPolicy#lastWarningSnooze}.
822 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700823 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800824 @Override
825 public void onReceive(Context context, Intent intent) {
826 // on background handler thread, and verified MANAGE_NETWORK_POLICY
827 // permission above.
828
829 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
830 performSnooze(template, TYPE_WARNING);
831 }
832 };
833
834 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700835 * Receiver that watches for {@link WifiConfiguration} to be changed.
836 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700837 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700838 @Override
839 public void onReceive(Context context, Intent intent) {
840 // on background handler thread, and verified CONNECTIVITY_INTERNAL
841 // permission above.
842
843 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
844 if (reason == CHANGE_REASON_REMOVED) {
845 final WifiConfiguration config = intent.getParcelableExtra(
846 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700847 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800848 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700849 synchronized (mUidRulesFirstLock) {
850 synchronized (mNetworkPoliciesSecondLock) {
851 if (mNetworkPolicy.containsKey(template)) {
852 mNetworkPolicy.remove(template);
853 writePolicyAL();
854 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700855 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700856 }
857 }
858 }
859 }
860 };
861
862 /**
863 * Receiver that watches {@link WifiInfo} state changes to infer metered
864 * state. Ignores hints when policy is user-defined.
865 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700866 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700867 @Override
868 public void onReceive(Context context, Intent intent) {
869 // on background handler thread, and verified CONNECTIVITY_INTERNAL
870 // permission above.
871
872 // ignore when not connected
873 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
874 if (!netInfo.isConnected()) return;
875
876 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
877 final boolean meteredHint = info.getMeteredHint();
878
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800879 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700880 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700881 NetworkPolicy policy = mNetworkPolicy.get(template);
882 if (policy == null && meteredHint) {
883 // policy doesn't exist, and AP is hinting that it's
884 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800885 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700886 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700887
888 } else if (policy != null && policy.inferred) {
889 // policy exists, and was inferred: update its current
890 // metered state.
891 policy.metered = meteredHint;
892
893 // since this is inferred for each wifi session, just update
894 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700895 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700896 }
897 }
898 }
899 };
900
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800901 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
902 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
903 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
904 metered, true);
905 }
906
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700907 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700908 * Observer that watches for {@link INetworkManagementService} alerts.
909 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700910 final private INetworkManagementEventObserver mAlertObserver
911 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700912 @Override
913 public void limitReached(String limitName, String iface) {
914 // only someone like NMS should be calling us
915 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
916
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800917 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
918 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700919 }
920 }
921 };
922
923 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700924 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
925 * to show visible notifications as needed.
926 */
Felipe Lemef0823852016-06-08 13:43:08 -0700927 void updateNotificationsNL() {
928 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700929
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700930 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700931 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700932 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700933
934 // TODO: when switching to kernel notifications, compute next future
935 // cycle boundary to recompute notifications.
936
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700937 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800938 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700939 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
940 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700941 // ignore policies that aren't relevant to user
942 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700943 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700944
Jeff Sharkey497e4432011-06-14 17:27:29 -0700945 final long start = computeLastCycleBoundary(currentTime, policy);
946 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700947 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700948
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700949 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800950 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700951 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
952 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700953 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700954 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700955 }
956
Jeff Sharkey497e4432011-06-14 17:27:29 -0700957 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700958 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700959
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800960 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700961 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700962 }
963 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700964 }
965
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700966 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -0700967 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
968 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700969 if (!mActiveNotifs.contains(tag)) {
970 cancelNotification(tag);
971 }
972 }
973 }
974
975 /**
976 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700977 * current device state, such as when
978 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
979 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700980 */
981 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -0800982 if (template.isMatchRuleMobile()) {
983 final TelephonyManager tele = TelephonyManager.from(mContext);
984 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700985
Jeff Sharkey32566012014-12-02 18:30:14 -0800986 // Mobile template is relevant when any active subscriber matches
987 final int[] subIds = sub.getActiveSubscriptionIdList();
988 for (int subId : subIds) {
989 final String subscriberId = tele.getSubscriberId(subId);
990 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -0700991 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -0800992 if (template.matches(probeIdent)) {
993 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -0700994 }
Jeff Sharkey32566012014-12-02 18:30:14 -0800995 }
996 return false;
997 } else {
998 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001000 }
1001
1002 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001003 * Notify that given {@link NetworkTemplate} is over
1004 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1005 */
Felipe Lemef0823852016-06-08 13:43:08 -07001006 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001007 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001008 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001009 mOverLimitNotified.add(template);
1010 }
1011 }
1012
Felipe Lemef0823852016-06-08 13:43:08 -07001013 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001014 mOverLimitNotified.remove(template);
1015 }
1016
1017 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001018 * Build unique tag that identifies an active {@link NetworkPolicy}
1019 * notification of a specific type, like {@link #TYPE_LIMIT}.
1020 */
1021 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001022 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023 }
1024
1025 /**
1026 * Show notification for combined {@link NetworkPolicy} and specific type,
1027 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1028 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001029 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001030 final String tag = buildNotificationTag(policy, type);
1031 final Notification.Builder builder = new Notification.Builder(mContext);
1032 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001033 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001034 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001035 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036
1037 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001038 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 switch (type) {
1040 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001041 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001042 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001044 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045 builder.setTicker(title);
1046 builder.setContentTitle(title);
1047 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001048 builder.setDefaults(Notification.DEFAULT_ALL);
1049 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001050
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001051 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1052 builder.setDeleteIntent(PendingIntent.getBroadcast(
1053 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1054
Wei Liu546cb772016-07-21 16:19:01 -07001055 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001056 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001057 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1058
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059 break;
1060 }
1061 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001062 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001063
1064 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001065 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001066 switch (policy.template.getMatchRule()) {
1067 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001069 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001070 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001073 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001074 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076 case MATCH_WIFI:
1077 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001078 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001079 break;
1080 default:
1081 title = null;
1082 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083 }
1084
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001085 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001086 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087 builder.setTicker(title);
1088 builder.setContentTitle(title);
1089 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001090
Wei Liu546cb772016-07-21 16:19:01 -07001091 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001092 builder.setContentIntent(PendingIntent.getActivity(
1093 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1094 break;
1095 }
1096 case TYPE_LIMIT_SNOOZED: {
1097 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001098 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001099 Formatter.formatFileSize(mContext, overBytes));
1100
1101 final CharSequence title;
1102 switch (policy.template.getMatchRule()) {
1103 case MATCH_MOBILE_3G_LOWER:
1104 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1105 break;
1106 case MATCH_MOBILE_4G:
1107 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1108 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001109 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1111 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001112 case MATCH_WIFI:
1113 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1114 break;
1115 default:
1116 title = null;
1117 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 }
1119
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001120 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001121 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001122 builder.setTicker(title);
1123 builder.setContentTitle(title);
1124 builder.setContentText(body);
1125
Wei Liu546cb772016-07-21 16:19:01 -07001126 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001127 builder.setContentIntent(PendingIntent.getActivity(
1128 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001129 break;
1130 }
1131 }
1132
1133 // TODO: move to NotificationManager once we can mock it
1134 try {
1135 final String packageName = mContext.getPackageName();
1136 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001137 if(!TextUtils.isEmpty(body)) {
1138 builder.setStyle(new Notification.BigTextStyle()
1139 .bigText(body));
1140 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001142 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001143 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001144 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001146 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001147 }
1148 }
1149
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001150 private void cancelNotification(String tag) {
1151 // TODO: move to NotificationManager once we can mock it
1152 try {
1153 final String packageName = mContext.getPackageName();
1154 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001155 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001156 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001157 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001158 }
1159 }
1160
1161 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001162 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001163 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001164 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001165 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001166 @Override
1167 public void onReceive(Context context, Intent intent) {
1168 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1169 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001170
1171 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001172 synchronized (mNetworkPoliciesSecondLock) {
1173 ensureActiveMobilePolicyNL();
1174 normalizePoliciesNL();
1175 updateNetworkEnabledNL();
1176 updateNetworkRulesNL();
1177 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001178 }
1179 }
1180 };
1181
1182 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 * Proactively control network data connections when they exceed
1184 * {@link NetworkPolicy#limitBytes}.
1185 */
Felipe Lemef0823852016-06-08 13:43:08 -07001186 void updateNetworkEnabledNL() {
1187 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001188
1189 // TODO: reset any policy-disabled networks when any policy is removed
1190 // completely, which is currently rare case.
1191
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001192 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001193 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1194 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001195 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001196 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001197 setNetworkTemplateEnabled(policy.template, true);
1198 continue;
1199 }
1200
1201 final long start = computeLastCycleBoundary(currentTime, policy);
1202 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001203 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001204
1205 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001206 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1207 && policy.lastLimitSnooze < start;
1208 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001209
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001210 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001211 }
1212 }
1213
1214 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001215 * Proactively disable networks that match the given
1216 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001217 */
1218 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 // TODO: reach into ConnectivityManager to proactively disable bringing
1220 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001221
1222 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1223 // If mobile data usage hits the limit or if the user resumes the data, we need to
1224 // notify telephony.
1225 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1226 final TelephonyManager tm = TelephonyManager.from(mContext);
1227
1228 final int[] subIds = sm.getActiveSubscriptionIdList();
1229 for (int subId : subIds) {
1230 final String subscriberId = tm.getSubscriberId(subId);
1231 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1232 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1233 // Template is matched when subscriber id matches.
1234 if (template.matches(probeIdent)) {
1235 tm.setPolicyDataEnabled(enabled, subId);
1236 }
1237 }
1238 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001239 }
1240
1241 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001242 * Examine all connected {@link NetworkState}, looking for
1243 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1244 * remaining quota based on usage cycle and historical stats.
1245 */
Felipe Lemef0823852016-06-08 13:43:08 -07001246 void updateNetworkRulesNL() {
1247 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001248
1249 final NetworkState[] states;
1250 try {
1251 states = mConnManager.getAllNetworkState();
1252 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001253 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001254 return;
1255 }
1256
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001257 // First, generate identities of all connected networks so we can
1258 // quickly compare them against all defined policies below.
1259 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001260 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001261 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001262 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001263 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001264
1265 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001266 if (baseIface != null) {
1267 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001268 }
1269
1270 // Stacked interfaces are considered to have same identity as
1271 // their parent network.
1272 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1273 for (LinkProperties stackedLink : stackedLinks) {
1274 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001275 if (stackedIface != null) {
1276 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001277 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001278 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001279 }
1280 }
1281
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001282 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001283 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001285 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001286 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001287
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001288 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001289 for (int j = connIdents.size() - 1; j >= 0; j--) {
1290 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1291 if (policy.template.matches(ident.second)) {
1292 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001293 }
1294 }
1295
1296 if (ifaceList.size() > 0) {
1297 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001298 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001299 }
1300 }
1301
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001302 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001303 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001304
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001305 // apply each policy that we found ifaces for; compute remaining data
1306 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001307 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001308 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1309 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1310 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001311
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001312 final long start;
1313 final long totalBytes;
1314 if (policy.hasCycle()) {
1315 start = computeLastCycleBoundary(currentTime, policy);
1316 totalBytes = getTotalBytes(policy.template, start, currentTime);
1317 } else {
1318 start = Long.MAX_VALUE;
1319 totalBytes = 0;
1320 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001321
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001323 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001324 }
1325
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001326 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001327 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001328 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001329 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001330 if (!hasLimit) {
1331 // metered network, but no policy limit; we still need to
1332 // restrict apps, so push really high quota.
1333 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001334 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001335 // snoozing past quota, but we still need to restrict apps,
1336 // so push really high quota.
1337 quotaBytes = Long.MAX_VALUE;
1338 } else {
1339 // remaining "quota" bytes are based on total usage in
1340 // current cycle. kernel doesn't like 0-byte rules, so we
1341 // set 1-byte quota and disable the radio later.
1342 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1343 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001344
1345 if (ifaces.length > 1) {
1346 // TODO: switch to shared quota once NMS supports
1347 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001348 }
1349
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001350 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001351 // long quotaBytes split up into two ints to fit in message
1352 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1353 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1354 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001355 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001356 }
1357 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001358
1359 // keep track of lowest warning or limit of active policies
1360 if (hasWarning && policy.warningBytes < lowestRule) {
1361 lowestRule = policy.warningBytes;
1362 }
1363 if (hasLimit && policy.limitBytes < lowestRule) {
1364 lowestRule = policy.limitBytes;
1365 }
1366 }
1367
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001368 for (int i = connIfaces.size()-1; i >= 0; i--) {
1369 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001370 // long quotaBytes split up into two ints to fit in message
1371 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1372 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1373 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001374 newMeteredIfaces.add(iface);
1375 }
1376
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001377 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001379 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001380 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1381 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001382 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001383 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1384 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001385 }
1386 }
1387 mMeteredIfaces = newMeteredIfaces;
1388
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001389 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001390 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001391 }
1392
1393 /**
1394 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1395 * have at least a default mobile policy defined.
1396 */
Felipe Lemef0823852016-06-08 13:43:08 -07001397 private void ensureActiveMobilePolicyNL() {
1398 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001399 if (mSuppressDefaultPolicy) return;
1400
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001401 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001402 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001403
Jeff Sharkey32566012014-12-02 18:30:14 -08001404 final int[] subIds = sub.getActiveSubscriptionIdList();
1405 for (int subId : subIds) {
1406 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001407 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001408 }
1409 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001410
Felipe Lemef0823852016-06-08 13:43:08 -07001411 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001412 // Poke around to see if we already have a policy
1413 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001414 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001415 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1416 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1417 if (template.matches(probeIdent)) {
1418 if (LOGD) {
1419 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1420 + NetworkIdentity.scrubSubscriberId(subscriberId));
1421 }
1422 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001423 }
1424 }
1425
Jeff Sharkey32566012014-12-02 18:30:14 -08001426 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1427 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001428
Jeff Sharkey32566012014-12-02 18:30:14 -08001429 // Build default mobile policy, and assume usage cycle starts today
1430 final long warningBytes = mContext.getResources().getInteger(
1431 com.android.internal.R.integer.config_networkPolicyDefaultWarning) * MB_IN_BYTES;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001432
Jeff Sharkey32566012014-12-02 18:30:14 -08001433 final Time time = new Time();
1434 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001435
Jeff Sharkey32566012014-12-02 18:30:14 -08001436 final int cycleDay = time.monthDay;
1437 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001438
Jeff Sharkey32566012014-12-02 18:30:14 -08001439 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1440 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1441 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001442 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001443 }
1444
Felipe Lemef0823852016-06-08 13:43:08 -07001445 private void readPolicyAL() {
1446 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001447
1448 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001449 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001450 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001451
1452 FileInputStream fis = null;
1453 try {
1454 fis = mPolicyFile.openRead();
1455 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001456 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001457
Felipe Leme46b451f2016-08-19 08:46:17 -07001458 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1459 // to skip UIDs that were explicitly blacklisted.
1460 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1461
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001462 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001463 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001464 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001465 while ((type = in.next()) != END_DOCUMENT) {
1466 final String tag = in.getName();
1467 if (type == START_TAG) {
1468 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001469 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001470 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001471 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1472 mRestrictBackground = readBooleanAttribute(
1473 in, ATTR_RESTRICT_BACKGROUND);
1474 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001475 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001476 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001477 if (mRestrictBackground != oldValue) {
1478 // Some early services may have read the default value,
1479 // so notify them that it's changed
1480 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1481 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1482 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001483
1484 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1485 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1486 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001487 final String networkId;
1488 if (version >= VERSION_ADDED_NETWORK_ID) {
1489 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1490 } else {
1491 networkId = null;
1492 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001494 final String cycleTimezone;
1495 if (version >= VERSION_ADDED_TIMEZONE) {
1496 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1497 } else {
1498 cycleTimezone = Time.TIMEZONE_UTC;
1499 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001500 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1501 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001502 final long lastLimitSnooze;
1503 if (version >= VERSION_SPLIT_SNOOZE) {
1504 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1505 } else if (version >= VERSION_ADDED_SNOOZE) {
1506 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001507 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001508 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001509 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001510 final boolean metered;
1511 if (version >= VERSION_ADDED_METERED) {
1512 metered = readBooleanAttribute(in, ATTR_METERED);
1513 } else {
1514 switch (networkTemplate) {
1515 case MATCH_MOBILE_3G_LOWER:
1516 case MATCH_MOBILE_4G:
1517 case MATCH_MOBILE_ALL:
1518 metered = true;
1519 break;
1520 default:
1521 metered = false;
1522 }
1523 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001524 final long lastWarningSnooze;
1525 if (version >= VERSION_SPLIT_SNOOZE) {
1526 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1527 } else {
1528 lastWarningSnooze = SNOOZE_NEVER;
1529 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001530 final boolean inferred;
1531 if (version >= VERSION_ADDED_INFERRED) {
1532 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1533 } else {
1534 inferred = false;
1535 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001536
Jeff Sharkey32566012014-12-02 18:30:14 -08001537 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1538 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001539 if (template.isPersistable()) {
1540 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1541 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1542 lastLimitSnooze, metered, inferred));
1543 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001545 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001546 final int uid = readIntAttribute(in, ATTR_UID);
1547 final int policy = readIntAttribute(in, ATTR_POLICY);
1548
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001549 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001550 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001551 } else {
1552 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1553 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001554 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001555 final int appId = readIntAttribute(in, ATTR_APP_ID);
1556 final int policy = readIntAttribute(in, ATTR_POLICY);
1557
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001558 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001559 // app policy is deprecated so this is only used in pre system user split.
1560 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001561 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001562 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001563 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001564 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001565 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001566 } else if (TAG_WHITELIST.equals(tag)) {
1567 insideWhitelist = true;
1568 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1569 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001570 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001571 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1572 final int uid = readIntAttribute(in, ATTR_UID);
1573 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001575 } else if (type == END_TAG) {
1576 if (TAG_WHITELIST.equals(tag)) {
1577 insideWhitelist = false;
1578 }
1579
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580 }
1581 }
1582
Felipe Leme46b451f2016-08-19 08:46:17 -07001583 final int size = whitelistedRestrictBackground.size();
1584 for (int i = 0; i < size; i++) {
1585 final int uid = whitelistedRestrictBackground.keyAt(i);
1586 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1587 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1588 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1589 + " because its policy is " + uidPoliciesToString(policy));
1590 continue;
1591 }
1592 if (UserHandle.isApp(uid)) {
1593 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1594 if (LOGV)
1595 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1596 setUidPolicyUncheckedUL(uid, newPolicy, false);
1597 } else {
1598 Slog.w(TAG, "unable to update policy on UID " + uid);
1599 }
1600 }
1601
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001602 } catch (FileNotFoundException e) {
1603 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001604 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001606 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001607 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001608 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001609 } finally {
1610 IoUtils.closeQuietly(fis);
1611 }
1612 }
1613
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001614 /**
1615 * Upgrade legacy background data flags, notifying listeners of one last
1616 * change to always-true.
1617 */
Felipe Lemef0823852016-06-08 13:43:08 -07001618 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001619 mRestrictBackground = Settings.Secure.getInt(
1620 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1621
1622 // kick off one last broadcast if restricted
1623 if (mRestrictBackground) {
1624 final Intent broadcast = new Intent(
1625 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001626 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001627 }
1628 }
1629
Felipe Lemef0823852016-06-08 13:43:08 -07001630 void writePolicyAL() {
1631 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001632
1633 FileOutputStream fos = null;
1634 try {
1635 fos = mPolicyFile.startWrite();
1636
1637 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001638 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639 out.startDocument(null, true);
1640
1641 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001642 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001643 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001644
1645 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001646 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1647 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001648 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001649 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001650
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001652 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1653 final String subscriberId = template.getSubscriberId();
1654 if (subscriberId != null) {
1655 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001657 final String networkId = template.getNetworkId();
1658 if (networkId != null) {
1659 out.attribute(null, ATTR_NETWORK_ID, networkId);
1660 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001661 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001662 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001663 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1664 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001665 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1666 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001667 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001668 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001669 out.endTag(null, TAG_NETWORK_POLICY);
1670 }
1671
1672 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001673 for (int i = 0; i < mUidPolicy.size(); i++) {
1674 final int uid = mUidPolicy.keyAt(i);
1675 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001676
Jeff Sharkey497e4432011-06-14 17:27:29 -07001677 // skip writing empty policies
1678 if (policy == POLICY_NONE) continue;
1679
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001680 out.startTag(null, TAG_UID_POLICY);
1681 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001682 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001683 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001684 }
1685
1686 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001687
1688 // write all whitelists
1689 out.startTag(null, TAG_WHITELIST);
1690
Felipe Lemea9505cc2016-02-26 10:28:41 -08001691 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001692 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001693 for (int i = 0; i < size; i++) {
1694 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1695 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1696 writeIntAttribute(out, ATTR_UID, uid);
1697 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1698 }
1699
Felipe Lemeb85a6372016-01-14 16:16:16 -08001700 out.endTag(null, TAG_WHITELIST);
1701
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001702 out.endDocument();
1703
1704 mPolicyFile.finishWrite(fos);
1705 } catch (IOException e) {
1706 if (fos != null) {
1707 mPolicyFile.failWrite(fos);
1708 }
1709 }
1710 }
1711
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001712 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001713 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001714 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001715
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001716 if (!UserHandle.isApp(uid)) {
1717 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001718 }
Felipe Lemef0823852016-06-08 13:43:08 -07001719 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001720 final long token = Binder.clearCallingIdentity();
1721 try {
1722 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1723 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001724 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001725 }
1726 } finally {
1727 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001728 }
1729 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001730 }
1731
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001732 @Override
1733 public void addUidPolicy(int uid, int policy) {
1734 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001735
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001736 if (!UserHandle.isApp(uid)) {
1737 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1738 }
1739
Felipe Lemef0823852016-06-08 13:43:08 -07001740 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001741 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1742 policy |= oldPolicy;
1743 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001744 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001745 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001746 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001747 }
1748
1749 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001750 public void removeUidPolicy(int uid, int policy) {
1751 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1752
1753 if (!UserHandle.isApp(uid)) {
1754 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1755 }
1756
Felipe Lemef0823852016-06-08 13:43:08 -07001757 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001758 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1759 policy = oldPolicy & ~policy;
1760 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001761 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001762 }
1763 }
1764 }
1765
Felipe Lemef0823852016-06-08 13:43:08 -07001766 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1767 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001768
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001769 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1770 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED, uid,
1771 isBlacklisted ? 1 : 0).sendToTarget();
1772
1773 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
Felipe Leme923845f2016-03-02 13:42:48 -08001774 // Checks if app was added or removed to the blacklist.
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001775 if ((oldPolicy == POLICY_NONE && isBlacklisted)
1776 || (wasBlacklisted && policy == POLICY_NONE)) {
Felipe Leme019fcd22016-04-19 10:24:39 -07001777 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, 1, null)
Felipe Leme923845f2016-03-02 13:42:48 -08001778 .sendToTarget();
1779 }
1780 }
1781
Felipe Lemef0823852016-06-08 13:43:08 -07001782 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001783 mUidPolicy.put(uid, policy);
1784
1785 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001786 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001787 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001788 synchronized (mNetworkPoliciesSecondLock) {
1789 writePolicyAL();
1790 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001791 }
1792 }
1793
1794 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001795 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001796 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1797
Felipe Lemef0823852016-06-08 13:43:08 -07001798 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001799 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001800 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001801 }
1802
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001803 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001804 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001805 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1806
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001807 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001808 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001809 for (int i = 0; i < mUidPolicy.size(); i++) {
1810 final int uid = mUidPolicy.keyAt(i);
1811 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001812 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1813 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001814 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001815 }
1816 }
1817 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001818 return uids;
1819 }
1820
1821 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001822 * Removes any persistable state associated with given {@link UserHandle}, persisting
1823 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001824 */
Felipe Lemef0823852016-06-08 13:43:08 -07001825 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001826
Felipe Lemef0823852016-06-08 13:43:08 -07001827 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001828 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001829
Felipe Lemea110eec2016-04-29 09:58:06 -07001830 // Remove entries from revoked default restricted background UID whitelist
1831 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1832 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1833 if (UserHandle.getUserId(uid) == userId) {
1834 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001835 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001836 }
1837 }
1838
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001839 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001840 int[] uids = new int[0];
1841 for (int i = 0; i < mUidPolicy.size(); i++) {
1842 final int uid = mUidPolicy.keyAt(i);
1843 if (UserHandle.getUserId(uid) == userId) {
1844 uids = appendInt(uids, uid);
1845 }
1846 }
1847
1848 if (uids.length > 0) {
1849 for (int uid : uids) {
1850 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001851 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001852 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001853 }
Felipe Lemef0823852016-06-08 13:43:08 -07001854 synchronized (mNetworkPoliciesSecondLock) {
1855 updateRulesForGlobalChangeAL(true);
1856 if (writePolicy && changed) {
1857 writePolicyAL();
1858 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001859 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001860 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001861 }
1862
1863 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001864 public void setConnectivityListener(INetworkPolicyListener listener) {
1865 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1866 if (mConnectivityListener != null) {
1867 throw new IllegalStateException("Connectivity listener already registered");
1868 }
1869 mConnectivityListener = listener;
1870 }
1871
1872 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001873 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001874 // TODO: create permission for observing network policy
1875 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001876 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001877 }
1878
1879 @Override
1880 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001881 // TODO: create permission for observing network policy
1882 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001883 mListeners.unregister(listener);
1884 }
1885
Jeff Sharkey1b861272011-05-22 00:34:52 -07001886 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001887 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001888 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1889
Felipe Leme6a05eee2016-02-19 14:43:51 -08001890 final long token = Binder.clearCallingIdentity();
1891 try {
1892 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001893 synchronized (mUidRulesFirstLock) {
1894 synchronized (mNetworkPoliciesSecondLock) {
1895 normalizePoliciesNL(policies);
1896 updateNetworkEnabledNL();
1897 updateNetworkRulesNL();
1898 updateNotificationsNL();
1899 writePolicyAL();
1900 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001901 }
1902 } finally {
1903 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001904 }
1905 }
1906
Felipe Lemef0823852016-06-08 13:43:08 -07001907 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001908 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001909 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1910 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001911 }
1912
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001913 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001914 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001915 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001916 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001917 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1918 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1919 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001920 } catch (SecurityException e) {
1921 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001922
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001923 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1924 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1925 return new NetworkPolicy[0];
1926 }
Svet Ganov16a16892015-04-16 10:32:04 -07001927 }
1928
Felipe Lemef0823852016-06-08 13:43:08 -07001929 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001930 final int size = mNetworkPolicy.size();
1931 final NetworkPolicy[] policies = new NetworkPolicy[size];
1932 for (int i = 0; i < size; i++) {
1933 policies[i] = mNetworkPolicy.valueAt(i);
1934 }
1935 return policies;
1936 }
1937 }
1938
Felipe Lemef0823852016-06-08 13:43:08 -07001939 private void normalizePoliciesNL() {
1940 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08001941 }
1942
Felipe Lemef0823852016-06-08 13:43:08 -07001943 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001944 final TelephonyManager tele = TelephonyManager.from(mContext);
1945 final String[] merged = tele.getMergedSubscriberIds();
1946
1947 mNetworkPolicy.clear();
1948 for (NetworkPolicy policy : policies) {
1949 // When two normalized templates conflict, prefer the most
1950 // restrictive policy
1951 policy.template = NetworkTemplate.normalize(policy.template, merged);
1952 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
1953 if (existing == null || existing.compareTo(policy) > 0) {
1954 if (existing != null) {
1955 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
1956 }
1957 mNetworkPolicy.put(policy.template, policy);
1958 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001959 }
1960 }
1961
1962 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001963 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001964 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07001965
1966 final long token = Binder.clearCallingIdentity();
1967 try {
1968 performSnooze(template, TYPE_LIMIT);
1969 } finally {
1970 Binder.restoreCallingIdentity(token);
1971 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001972 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001973
Dianne Hackborn497175b2014-07-01 12:56:08 -07001974 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001975 maybeRefreshTrustedTime();
1976 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07001977 synchronized (mUidRulesFirstLock) {
1978 synchronized (mNetworkPoliciesSecondLock) {
1979 // find and snooze local policy that matches
1980 final NetworkPolicy policy = mNetworkPolicy.get(template);
1981 if (policy == null) {
1982 throw new IllegalArgumentException("unable to find policy for " + template);
1983 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001984
Felipe Lemef0823852016-06-08 13:43:08 -07001985 switch (type) {
1986 case TYPE_WARNING:
1987 policy.lastWarningSnooze = currentTime;
1988 break;
1989 case TYPE_LIMIT:
1990 policy.lastLimitSnooze = currentTime;
1991 break;
1992 default:
1993 throw new IllegalArgumentException("unexpected type");
1994 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001995
Felipe Lemef0823852016-06-08 13:43:08 -07001996 normalizePoliciesNL();
1997 updateNetworkEnabledNL();
1998 updateNetworkRulesNL();
1999 updateNotificationsNL();
2000 writePolicyAL();
2001 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002002 }
2003 }
2004
2005 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002006 public void onTetheringChanged(String iface, boolean tethering) {
2007 // No need to enforce permission because setRestrictBackground() will do it.
2008 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002009 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002010 if (mRestrictBackground && tethering) {
2011 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2012 setRestrictBackground(false);
2013 }
2014 }
2015 }
2016
2017 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002018 public void setRestrictBackground(boolean restrictBackground) {
2019 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002020 final long token = Binder.clearCallingIdentity();
2021 try {
2022 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002023 synchronized (mUidRulesFirstLock) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002024 if (restrictBackground == mRestrictBackground) {
2025 // Ideally, UI should never allow this scenario...
2026 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2027 return;
2028 }
Felipe Lemef0823852016-06-08 13:43:08 -07002029 setRestrictBackgroundUL(restrictBackground);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002030 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002031
Felipe Leme6a05eee2016-02-19 14:43:51 -08002032 } finally {
2033 Binder.restoreCallingIdentity(token);
Jeff Sharkey46645002011-07-27 21:11:21 -07002034 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08002035
2036 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2037 .sendToTarget();
Jeff Sharkey46645002011-07-27 21:11:21 -07002038 }
2039
Felipe Lemef0823852016-06-08 13:43:08 -07002040 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002041 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002042 final boolean oldRestrictBackground = mRestrictBackground;
2043 mRestrictBackground = restrictBackground;
2044 // Must whitelist foreground apps before turning data saver mode on.
2045 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2046 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Lemef0823852016-06-08 13:43:08 -07002047 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Leme70c57c22016-03-29 10:45:13 -07002048 try {
2049 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2050 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2051 mRestrictBackground = oldRestrictBackground;
2052 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002053 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002054 return;
2055 }
2056 } catch (RemoteException e) {
2057 // ignored; service lives in system_server
2058 }
Felipe Lemef0823852016-06-08 13:43:08 -07002059 synchronized (mNetworkPoliciesSecondLock) {
2060 updateNotificationsNL();
2061 writePolicyAL();
2062 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002063 }
2064
Felipe Leme46b451f2016-08-19 08:46:17 -07002065 /**
2066 * @deprecated - should use {@link #setUidPolicy(int, int)} directly.
2067 */
Jeff Sharkey46645002011-07-27 21:11:21 -07002068 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002069 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002070 public void addRestrictBackgroundWhitelistedUid(int uid) {
2071 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme70c57c22016-03-29 10:45:13 -07002072 final boolean oldStatus;
Felipe Leme01e05e72016-03-31 10:09:24 -07002073 final boolean needFirewallRules;
Felipe Lemef0823852016-06-08 13:43:08 -07002074 int changed;
2075 synchronized (mUidRulesFirstLock) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002076 final int oldUidPolicy = mUidPolicy.get(uid, POLICY_NONE);
2077 oldStatus = (oldUidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme47585ba2016-02-09 16:56:32 -08002078 if (oldStatus) {
2079 if (LOGD) Slog.d(TAG, "uid " + uid + " is already whitelisted");
2080 return;
2081 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002082 needFirewallRules = isUidValidForWhitelistRules(uid);
Felipe Leme47585ba2016-02-09 16:56:32 -08002083 Slog.i(TAG, "adding uid " + uid + " to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -07002084 setUidPolicyUncheckedUL(uid, oldUidPolicy, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea9505cc2016-02-26 10:28:41 -08002085 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2086 && mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2087 if (LOGD) Slog.d(TAG, "Removing uid " + uid
2088 + " from revoked restrict background whitelist");
2089 mRestrictBackgroundWhitelistRevokedUids.delete(uid);
2090 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002091 if (needFirewallRules) {
2092 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002093 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme01e05e72016-03-31 10:09:24 -07002094 }
2095 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002096 synchronized (mNetworkPoliciesSecondLock) {
2097 writePolicyAL();
2098 }
2099 changed = (mRestrictBackground && !oldStatus && needFirewallRules) ? 1 : 0;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002100 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002101 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed,
2102 Boolean.TRUE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002103 }
2104
Felipe Leme46b451f2016-08-19 08:46:17 -07002105 /**
2106 * @deprecated - should use {@link #setUidPolicy(int, int)} directly.
2107 */
Felipe Lemeb85a6372016-01-14 16:16:16 -08002108 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002109 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002110 public void removeRestrictBackgroundWhitelistedUid(int uid) {
2111 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme47585ba2016-02-09 16:56:32 -08002112 final boolean changed;
Felipe Lemef0823852016-06-08 13:43:08 -07002113 synchronized (mUidRulesFirstLock) {
2114 changed = removeRestrictBackgroundWhitelistedUidUL(uid, false, true);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002115 }
Felipe Leme019fcd22016-04-19 10:24:39 -07002116 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED, uid, changed ? 1 : 0,
2117 Boolean.FALSE).sendToTarget();
Felipe Lemeb85a6372016-01-14 16:16:16 -08002118 }
2119
Felipe Leme70c57c22016-03-29 10:45:13 -07002120 /**
2121 * Removes a uid from the restricted background whitelist, returning whether its current
2122 * {@link ConnectivityManager.RestrictBackgroundStatus} changed.
2123 */
Felipe Lemef0823852016-06-08 13:43:08 -07002124 private boolean removeRestrictBackgroundWhitelistedUidUL(int uid, boolean uidDeleted,
Felipe Leme70c57c22016-03-29 10:45:13 -07002125 boolean updateNow) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002126 final boolean oldStatus =
2127 (mUidPolicy.get(uid, POLICY_NONE) & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme46c4fc32016-05-04 09:21:43 -07002128 if (!oldStatus && !uidDeleted) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002129 if (LOGD) Slog.d(TAG, "uid " + uid + " was not whitelisted before");
2130 return false;
2131 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002132 final boolean needFirewallRules = uidDeleted || isUidValidForWhitelistRules(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002133 if (oldStatus) {
2134 Slog.i(TAG, "removing uid " + uid + " from restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -07002135 mUidPolicy.delete(uid);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002136 }
Felipe Lemea9505cc2016-02-26 10:28:41 -08002137 if (mDefaultRestrictBackgroundWhitelistUids.get(uid)
2138 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2139 if (LOGD) Slog.d(TAG, "Adding uid " + uid
2140 + " to revoked restrict background whitelist");
2141 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2142 }
Felipe Leme01e05e72016-03-31 10:09:24 -07002143 if (needFirewallRules) {
2144 // Only update firewall rules if necessary...
Felipe Lemef0823852016-06-08 13:43:08 -07002145 updateRulesForDataUsageRestrictionsUL(uid, uidDeleted);
Felipe Leme01e05e72016-03-31 10:09:24 -07002146 }
Felipe Leme3f52cd52016-02-03 13:36:30 -08002147 if (updateNow) {
Felipe Leme01e05e72016-03-31 10:09:24 -07002148 // ...but always persists the whitelist request.
Felipe Lemef0823852016-06-08 13:43:08 -07002149 synchronized (mNetworkPoliciesSecondLock) {
2150 writePolicyAL();
2151 }
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002152 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002153 // Status only changes if Data Saver is turned on (otherwise it is DISABLED, even if the
2154 // app was whitelisted before).
Felipe Leme01e05e72016-03-31 10:09:24 -07002155 return mRestrictBackground && needFirewallRules;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002156 }
2157
Felipe Leme46b451f2016-08-19 08:46:17 -07002158 /**
2159 * @deprecated - should use {@link #getUidsWithPolicy(int)} instead, but first need to change
2160 * that method to use logical OR (|).
2161 */
Felipe Lemeb85a6372016-01-14 16:16:16 -08002162 @Override
Felipe Leme46b451f2016-08-19 08:46:17 -07002163 @Deprecated
Felipe Lemeb85a6372016-01-14 16:16:16 -08002164 public int[] getRestrictBackgroundWhitelistedUids() {
2165 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme46b451f2016-08-19 08:46:17 -07002166 int[] whitelist = null;
Felipe Lemef0823852016-06-08 13:43:08 -07002167 synchronized (mUidRulesFirstLock) {
Felipe Leme46b451f2016-08-19 08:46:17 -07002168 // First calculate size
2169 int size = 0;
2170 int policySize = mUidPolicy.size();
2171 for (int i = 0; i < policySize; i++) {
2172 if ((mUidPolicy.valueAt(i) & POLICY_ALLOW_METERED_BACKGROUND) != 0) {
2173 size ++;
2174 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002175 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002176 whitelist = new int[size];
2177 // Then populate it.
2178 if (size > 0) {
2179 int index = 0;
2180 for (int i = 0; i < policySize; i++) {
2181 final int uid = mUidPolicy.keyAt(i);
2182 if ((mUidPolicy.valueAt(i) & POLICY_ALLOW_METERED_BACKGROUND) != 0) {
2183 whitelist[index++] = uid;
2184 }
2185 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002186 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08002187 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002188 if (LOGV) {
2189 Slog.v(TAG, "getRestrictBackgroundWhitelistedUids(): "
2190 + Arrays.toString(whitelist));
2191 }
2192 return whitelist;
Felipe Lemeb85a6372016-01-14 16:16:16 -08002193 }
2194
2195 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002196 public int getRestrictBackgroundByCaller() {
2197 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2198 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002199
Felipe Lemef0823852016-06-08 13:43:08 -07002200 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002201 // Must clear identity because getUidPolicy() is restricted to system.
2202 final long token = Binder.clearCallingIdentity();
2203 final int policy;
2204 try {
2205 policy = getUidPolicy(uid);
2206 } finally {
2207 Binder.restoreCallingIdentity(token);
2208 }
2209 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2210 // App is blacklisted.
2211 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2212 }
Felipe Leme1b103232016-01-22 09:44:57 -08002213 if (!mRestrictBackground) {
2214 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2215 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002216 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002217 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2218 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2219 }
2220 }
2221
2222 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002223 public boolean getRestrictBackground() {
2224 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2225
Felipe Lemef0823852016-06-08 13:43:08 -07002226 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002227 return mRestrictBackground;
2228 }
2229 }
2230
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002231 @Override
2232 public void setDeviceIdleMode(boolean enabled) {
2233 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2234
Felipe Lemef0823852016-06-08 13:43:08 -07002235 synchronized (mUidRulesFirstLock) {
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002236 if (mDeviceIdleMode != enabled) {
2237 mDeviceIdleMode = enabled;
2238 if (mSystemReady) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002239 // Device idle change means we need to rebuild rules for all
2240 // known apps, so do a global refresh.
Felipe Lemef0823852016-06-08 13:43:08 -07002241 updateRulesForRestrictPowerUL();
Dianne Hackborn3b16cf42015-07-01 15:05:04 -07002242 }
2243 if (enabled) {
2244 EventLogTags.writeDeviceIdleOnPhase("net");
2245 } else {
2246 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002247 }
2248 }
2249 }
2250 }
2251
Felipe Lemef0823852016-06-08 13:43:08 -07002252 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002253 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2254 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002255 if (policy.template.matches(ident)) {
2256 return policy;
2257 }
2258 }
2259 return null;
2260 }
2261
2262 @Override
2263 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2264 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2265
2266 // only returns usage summary, so we don't require caller to have
2267 // READ_NETWORK_USAGE_HISTORY.
2268 final long token = Binder.clearCallingIdentity();
2269 try {
2270 return getNetworkQuotaInfoUnchecked(state);
2271 } finally {
2272 Binder.restoreCallingIdentity(token);
2273 }
2274 }
2275
2276 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2277 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2278
2279 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002280 synchronized (mNetworkPoliciesSecondLock) {
2281 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002282 }
2283
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002284 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002285 // missing policy means we can't derive useful quota info
2286 return null;
2287 }
2288
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002289 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002290
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002291 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002292 final long start = computeLastCycleBoundary(currentTime, policy);
2293 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002294 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002295
2296 // report soft and hard limits under policy
2297 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2298 : NetworkQuotaInfo.NO_LIMIT;
2299 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2300 : NetworkQuotaInfo.NO_LIMIT;
2301
2302 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2303 }
2304
Jeff Sharkey46645002011-07-27 21:11:21 -07002305 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002306 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002307 if (state.networkInfo == null) {
2308 return false;
2309 }
2310
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002311 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2312
2313 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002314 synchronized (mNetworkPoliciesSecondLock) {
2315 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002316 }
2317
2318 if (policy != null) {
2319 return policy.metered;
2320 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002321 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002322 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002323 return true;
2324 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002325 return false;
2326 }
2327 }
2328
2329 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002330 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002331 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002332
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002333 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2334
Dianne Hackborn497175b2014-07-01 12:56:08 -07002335 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002336 for (String arg : args) {
2337 argSet.add(arg);
2338 }
2339
Felipe Lemef0823852016-06-08 13:43:08 -07002340 synchronized (mUidRulesFirstLock) {
2341 synchronized (mNetworkPoliciesSecondLock) {
2342 if (argSet.contains("--unsnooze")) {
2343 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2344 mNetworkPolicy.valueAt(i).clearSnooze();
2345 }
2346
2347 normalizePoliciesNL();
2348 updateNetworkEnabledNL();
2349 updateNetworkRulesNL();
2350 updateNotificationsNL();
2351 writePolicyAL();
2352
2353 fout.println("Cleared snooze timestamps");
2354 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002355 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002356
Felipe Lemef0823852016-06-08 13:43:08 -07002357 fout.print("System ready: "); fout.println(mSystemReady);
2358 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2359 fout.print("Restrict power: "); fout.println(mRestrictPower);
2360 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2361 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002362 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002363 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2364 fout.println(mNetworkPolicy.valueAt(i).toString());
2365 }
2366 fout.decreaseIndent();
2367
2368 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2369
2370 fout.println("Policy for UIDs:");
2371 fout.increaseIndent();
2372 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002373 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002374 final int uid = mUidPolicy.keyAt(i);
2375 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002376 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002377 fout.print(uid);
2378 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002379 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002380 fout.println();
2381 }
2382 fout.decreaseIndent();
2383
2384 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2385 if (size > 0) {
2386 fout.println("Power save whitelist (except idle) app ids:");
2387 fout.increaseIndent();
2388 for (int i = 0; i < size; i++) {
2389 fout.print("UID=");
2390 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2391 fout.print(": ");
2392 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2393 fout.println();
2394 }
2395 fout.decreaseIndent();
2396 }
2397
2398 size = mPowerSaveWhitelistAppIds.size();
2399 if (size > 0) {
2400 fout.println("Power save whitelist app ids:");
2401 fout.increaseIndent();
2402 for (int i = 0; i < size; i++) {
2403 fout.print("UID=");
2404 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2405 fout.print(": ");
2406 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2407 fout.println();
2408 }
2409 fout.decreaseIndent();
2410 }
2411
Felipe Leme46b451f2016-08-19 08:46:17 -07002412 final int[] restrictBackgroundWhitelistUids =
2413 getRestrictBackgroundWhitelistedUids();
2414 size = restrictBackgroundWhitelistUids.length;
Felipe Lemef0823852016-06-08 13:43:08 -07002415 if (size > 0) {
2416 fout.println("Restrict background whitelist uids:");
2417 fout.increaseIndent();
2418 for (int i = 0; i < size; i++) {
2419 fout.print("UID=");
Felipe Leme46b451f2016-08-19 08:46:17 -07002420 fout.print(restrictBackgroundWhitelistUids[i]);
Felipe Lemef0823852016-06-08 13:43:08 -07002421 fout.println();
2422 }
2423 fout.decreaseIndent();
2424 }
2425
2426 size = mDefaultRestrictBackgroundWhitelistUids.size();
2427 if (size > 0) {
2428 fout.println("Default restrict background whitelist uids:");
2429 fout.increaseIndent();
2430 for (int i = 0; i < size; i++) {
2431 fout.print("UID=");
2432 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2433 fout.println();
2434 }
2435 fout.decreaseIndent();
2436 }
2437
2438 size = mRestrictBackgroundWhitelistRevokedUids.size();
2439 if (size > 0) {
2440 fout.println("Default restrict background whitelist uids revoked by users:");
2441 fout.increaseIndent();
2442 for (int i = 0; i < size; i++) {
2443 fout.print("UID=");
2444 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2445 fout.println();
2446 }
2447 fout.decreaseIndent();
2448 }
2449
2450 final SparseBooleanArray knownUids = new SparseBooleanArray();
2451 collectKeys(mUidState, knownUids);
2452 collectKeys(mUidRules, knownUids);
2453
2454 fout.println("Status for all known UIDs:");
2455 fout.increaseIndent();
2456 size = knownUids.size();
2457 for (int i = 0; i < size; i++) {
2458 final int uid = knownUids.keyAt(i);
2459 fout.print("UID=");
2460 fout.print(uid);
2461
2462 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2463 fout.print(" state=");
2464 fout.print(state);
2465 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2466 fout.print(" (fg)");
2467 } else {
2468 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2469 ? " (fg svc)" : " (bg)");
2470 }
2471
2472 final int uidRules = mUidRules.get(uid, RULE_NONE);
2473 fout.print(" rules=");
2474 fout.print(uidRulesToString(uidRules));
2475 fout.println();
2476 }
2477 fout.decreaseIndent();
2478
2479 fout.println("Status for just UIDs with rules:");
2480 fout.increaseIndent();
2481 size = mUidRules.size();
2482 for (int i = 0; i < size; i++) {
2483 final int uid = mUidRules.keyAt(i);
2484 fout.print("UID=");
2485 fout.print(uid);
2486 final int uidRules = mUidRules.get(uid, RULE_NONE);
2487 fout.print(" rules=");
2488 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002489 fout.println();
2490 }
2491 fout.decreaseIndent();
2492 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002493 }
2494 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002495
2496 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002497 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
2498 String[] args, ResultReceiver resultReceiver) throws RemoteException {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002499 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Felipe Leme50a235e2016-01-15 18:37:06 -08002500 this, in, out, err, args, resultReceiver);
2501 }
2502
2503 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002504 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002505 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2506
Felipe Lemef0823852016-06-08 13:43:08 -07002507 synchronized (mUidRulesFirstLock) {
2508 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002509 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002510 }
2511
Felipe Lemef0823852016-06-08 13:43:08 -07002512 private boolean isUidForegroundUL(int uid) {
2513 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002514 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2515 }
2516
Felipe Lemef0823852016-06-08 13:43:08 -07002517 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002518 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002519 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002520 }
2521
Felipe Lemef0823852016-06-08 13:43:08 -07002522 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002523 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2524 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2525 }
2526
Felipe Lemef0823852016-06-08 13:43:08 -07002527 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002528 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002529 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002530 }
2531
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002532 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002533 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002534 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2535 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002536 */
Felipe Lemef0823852016-06-08 13:43:08 -07002537 private void updateUidStateUL(int uid, int uidState) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002538 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2539 if (oldUidState != uidState) {
2540 // state changed, push updated rules
2541 mUidState.put(uid, uidState);
Felipe Lemef0823852016-06-08 13:43:08 -07002542 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
Felipe Leme011b98f2016-02-10 17:28:31 -08002543 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2544 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Felipe Leme781ba142016-05-09 16:24:48 -07002545 if (isUidIdle(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07002546 updateRuleForAppIdleUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002547 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002548 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002549 updateRuleForDeviceIdleUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002550 }
2551 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002552 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002553 }
Felipe Lemef0823852016-06-08 13:43:08 -07002554 updateRulesForPowerRestrictionsUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002555 }
Felipe Lemef0823852016-06-08 13:43:08 -07002556 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002557 }
2558 }
2559
Felipe Lemef0823852016-06-08 13:43:08 -07002560 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002561 final int index = mUidState.indexOfKey(uid);
2562 if (index >= 0) {
2563 final int oldUidState = mUidState.valueAt(index);
2564 mUidState.removeAt(index);
2565 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002566 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002567 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002568 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002569 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002570 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002571 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002572 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002573 }
Felipe Lemef0823852016-06-08 13:43:08 -07002574 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002575 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002576 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002577 }
2578 }
2579
Felipe Lemef28983d2016-03-25 12:18:23 -07002580 // adjust stats accounting based on foreground status
2581 private void updateNetworkStats(int uid, boolean uidForeground) {
2582 try {
2583 mNetworkStats.setUidForeground(uid, uidForeground);
2584 } catch (RemoteException e) {
2585 // ignored; service lives in system_server
2586 }
2587 }
2588
Felipe Lemef0823852016-06-08 13:43:08 -07002589 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002590 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002591 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002592 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002593 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002594 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002595 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002596 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002597 }
2598 }
2599
Felipe Leme011b98f2016-02-10 17:28:31 -08002600 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002601 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2602 }
2603
Felipe Lemef0823852016-06-08 13:43:08 -07002604 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002605 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2606 }
2607
Felipe Lemef0823852016-06-08 13:43:08 -07002608 void updateRulesForPowerSaveUL() {
2609 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002610 mUidFirewallPowerSaveRules);
2611 }
2612
Felipe Lemef0823852016-06-08 13:43:08 -07002613 void updateRuleForRestrictPowerUL(int uid) {
2614 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002615 }
2616
Felipe Lemef0823852016-06-08 13:43:08 -07002617 void updateRulesForDeviceIdleUL() {
2618 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
Felipe Leme011b98f2016-02-10 17:28:31 -08002619 mUidFirewallDozableRules);
2620 }
2621
Felipe Lemef0823852016-06-08 13:43:08 -07002622 void updateRuleForDeviceIdleUL(int uid) {
2623 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002624 }
2625
Felipe Lemef28983d2016-03-25 12:18:23 -07002626 // NOTE: since both fw_dozable and fw_powersave uses the same map
2627 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002628 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002629 SparseIntArray rules) {
2630 if (enabled) {
2631 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002632 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002633 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002634 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002635 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002636 for (int ui = users.size() - 1; ui >= 0; ui--) {
2637 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002638 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002639 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2640 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2641 int uid = UserHandle.getUid(user.id, appId);
2642 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2643 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002644 }
2645 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2646 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2647 int uid = UserHandle.getUid(user.id, appId);
2648 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2649 }
2650 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002651 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002652 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002653 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2654 }
2655 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002656 setUidFirewallRules(chain, uidRules);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002657 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002658
Felipe Lemef0823852016-06-08 13:43:08 -07002659 enableFirewallChainUL(chain, enabled);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002660 }
2661
Felipe Lemef0823852016-06-08 13:43:08 -07002662 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002663 final int appId = UserHandle.getAppId(uid);
2664 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2665 }
2666
Felipe Lemef28983d2016-03-25 12:18:23 -07002667 // NOTE: since both fw_dozable and fw_powersave uses the same map
2668 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002669 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002670 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002671 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002672 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2673 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002674 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002675 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002676 }
2677 }
2678 }
2679
Felipe Lemef0823852016-06-08 13:43:08 -07002680 void updateRulesForAppIdleUL() {
Jeff Sharkeydc988062015-09-14 10:09:47 -07002681 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2682 uidRules.clear();
2683
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002684 // Fully update the app idle firewall chain.
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002685 final List<UserInfo> users = mUserManager.getUsers();
2686 for (int ui = users.size() - 1; ui >= 0; ui--) {
2687 UserInfo user = users.get(ui);
2688 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2689 for (int uid : idleUids) {
2690 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002691 // quick check: if this uid doesn't have INTERNET permission, it
2692 // doesn't have network access anyway, so it is a waste to mess
2693 // with it here.
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002694 if (hasInternetPermissions(uid)) {
2695 uidRules.put(uid, FIREWALL_RULE_DENY);
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002696 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002697 }
2698 }
2699 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002700
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002701 setUidFirewallRules(FIREWALL_CHAIN_STANDBY, uidRules);
2702 }
2703
Felipe Lemef0823852016-06-08 13:43:08 -07002704 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002705 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002706
2707 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002708 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002709 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002710 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2711 } else {
2712 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2713 }
2714 }
2715
Felipe Lemef0823852016-06-08 13:43:08 -07002716 void updateRulesForAppIdleParoleUL() {
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002717 boolean enableChain = !mUsageStats.isAppIdleParoleOn();
Felipe Lemef0823852016-06-08 13:43:08 -07002718 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002719 }
2720
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002721 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002722 * Update rules that might be changed by {@link #mRestrictBackground},
2723 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002724 */
Felipe Lemef0823852016-06-08 13:43:08 -07002725 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002726 long start;
2727 if (LOGD) start = System.currentTimeMillis();
2728
Felipe Lemef0823852016-06-08 13:43:08 -07002729 updateRulesForRestrictPowerUL();
2730 updateRulesForRestrictBackgroundUL();
Felipe Leme76010a32016-03-17 13:03:11 -07002731
2732 // If the set of restricted networks may have changed, re-evaluate those.
2733 if (restrictedNetworksChanged) {
Felipe Lemef0823852016-06-08 13:43:08 -07002734 normalizePoliciesNL();
2735 updateNetworkRulesNL();
Felipe Leme76010a32016-03-17 13:03:11 -07002736 }
2737 if (LOGD) {
2738 final long delta = System.currentTimeMillis() - start;
Felipe Lemef0823852016-06-08 13:43:08 -07002739 Slog.d(TAG, "updateRulesForGlobalChangeAL(" + restrictedNetworksChanged + ") took "
Felipe Leme76010a32016-03-17 13:03:11 -07002740 + delta + "ms");
2741 }
2742 }
2743
Felipe Lemef0823852016-06-08 13:43:08 -07002744 private void updateRulesForRestrictPowerUL() {
2745 updateRulesForDeviceIdleUL();
2746 updateRulesForAppIdleUL();
2747 updateRulesForPowerSaveUL();
2748 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
Felipe Lemef3e40642016-06-07 17:28:08 -07002749 }
2750
Felipe Lemef0823852016-06-08 13:43:08 -07002751 private void updateRulesForRestrictBackgroundUL() {
2752 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
Felipe Lemef3e40642016-06-07 17:28:08 -07002753 }
2754
2755 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2756 private static final int TYPE_RESTRICT_POWER = 2;
2757 @Retention(RetentionPolicy.SOURCE)
2758 @IntDef(flag = false, value = {
2759 TYPE_RESTRICT_BACKGROUND,
2760 TYPE_RESTRICT_POWER,
2761 })
2762 public @interface RestrictType {
2763 }
2764
2765 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002766 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme76010a32016-03-17 13:03:11 -07002767 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002768
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002769 // update rules for all installed applications
Stuart Scotte3e314d2015-04-20 14:07:45 -07002770 final List<UserInfo> users = mUserManager.getUsers();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002771 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Jeff Sharkey8a372a02016-03-16 16:25:45 -06002772 PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.MATCH_DISABLED_COMPONENTS
2773 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2774 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002775
Felipe Leme03e689d2016-03-02 16:17:38 -08002776 final int usersSize = users.size();
2777 final int appsSize = apps.size();
2778 for (int i = 0; i < usersSize; i++) {
2779 final UserInfo user = users.get(i);
2780 for (int j = 0; j < appsSize; j++) {
2781 final ApplicationInfo app = apps.get(j);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002782 final int uid = UserHandle.getUid(user.id, app.uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002783 switch (type) {
2784 case TYPE_RESTRICT_BACKGROUND:
Felipe Lemef0823852016-06-08 13:43:08 -07002785 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002786 break;
2787 case TYPE_RESTRICT_POWER:
Felipe Lemef0823852016-06-08 13:43:08 -07002788 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef3e40642016-06-07 17:28:08 -07002789 break;
2790 default:
2791 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2792 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002793 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002794 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002795 }
2796
Felipe Lemef0823852016-06-08 13:43:08 -07002797 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002798 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002799 for (int i = 0; i < users.size(); i++) {
2800 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002801 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002802 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002803 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002804 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002805 updateRuleForAppIdleUL(uid);
2806 updateRuleForDeviceIdleUL(uid);
2807 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002808 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002809 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002810 }
2811 }
2812 }
2813
Felipe Leme70c57c22016-03-29 10:45:13 -07002814 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2815 // methods below could be merged into a isUidValidForRules() method.
2816 private boolean isUidValidForBlacklistRules(int uid) {
2817 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002818 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002819 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002820 return true;
2821 }
2822
2823 return false;
2824 }
2825
Felipe Leme70c57c22016-03-29 10:45:13 -07002826 private boolean isUidValidForWhitelistRules(int uid) {
2827 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2828 }
2829
Amith Yamasani15e472352015-04-24 19:06:07 -07002830 private boolean isUidIdle(int uid) {
2831 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2832 final int userId = UserHandle.getUserId(uid);
2833
songjinshi0655edd2016-05-18 19:55:32 +08002834 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002835 for (String packageName : packages) {
2836 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2837 return false;
2838 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002839 }
2840 }
2841 return true;
2842 }
2843
2844 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002845 * Checks if an uid has INTERNET permissions.
2846 * <p>
2847 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002848 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002849 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002850 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002851 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002852 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002853 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002854 }
2855 } catch (RemoteException e) {
2856 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002857 return true;
2858 }
2859
2860 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002861 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002862 *
Felipe Leme781ba142016-05-09 16:24:48 -07002863 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002864 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002865 * <li>Doze mode
2866 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002867 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002868 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002869 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002870 *
2871 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002872 */
Felipe Lemef0823852016-06-08 13:43:08 -07002873 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002874 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002875 updateRuleForDeviceIdleUL(uid);
2876 updateRuleForAppIdleUL(uid);
2877 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002878
2879 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002880 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002881
2882 // Update firewall and internal rules for Data Saver Mode.
Felipe Lemef0823852016-06-08 13:43:08 -07002883 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002884 }
2885
Felipe Leme70c57c22016-03-29 10:45:13 -07002886 /**
2887 * Applies network rules to bandwidth controllers based on process state and user-defined
2888 * restrictions (blacklist / whitelist).
2889 *
2890 * <p>
2891 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2892 * networks:
2893 * <ul>
2894 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2895 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2896 * also blacklisted.
2897 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2898 * no UIDs other those whitelisted will have access.
2899 * <ul>
2900 *
2901 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2902 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2903 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2904 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002905 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002906 * {@link INetworkManagementService}, but this method should also be called in events (like
2907 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2908 * following rules should also be applied:
2909 *
2910 * <ul>
2911 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2912 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2913 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2914 * {@code bw_penalty_box}.
2915 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2916 * </ul>
2917 *
2918 * <p>For optimization, the rules are only applied on user apps that have internet access
2919 * permission, since there is no need to change the {@code iptables} rule if the app does not
2920 * have permission to use the internet.
2921 *
2922 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002923 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002924 */
Felipe Lemef0823852016-06-08 13:43:08 -07002925 private void updateRulesForDataUsageRestrictionsUL(int uid) {
2926 updateRulesForDataUsageRestrictionsUL(uid, false);
Felipe Leme70c57c22016-03-29 10:45:13 -07002927 }
2928
2929 /**
Felipe Lemef0823852016-06-08 13:43:08 -07002930 * Overloaded version of {@link #updateRulesForDataUsageRestrictionsUL(int)} called when an
Felipe Leme70c57c22016-03-29 10:45:13 -07002931 * app is removed - it ignores the UID validity check.
2932 */
Felipe Lemef0823852016-06-08 13:43:08 -07002933 private void updateRulesForDataUsageRestrictionsUL(int uid, boolean uidDeleted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002934 if (!uidDeleted && !isUidValidForWhitelistRules(uid)) {
2935 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2936 return;
2937 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002938
Dianne Hackborn497175b2014-07-01 12:56:08 -07002939 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002940 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002941 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002942
Felipe Leme781ba142016-05-09 16:24:48 -07002943 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002944 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002945 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2946 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002947
Felipe Leme70c57c22016-03-29 10:45:13 -07002948 // First step: define the new rule based on user restrictions and foreground state.
2949 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002950 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2951 newRule = RULE_TEMPORARY_ALLOW_METERED;
2952 } else if (isWhitelisted) {
2953 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002954 }
2955 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002956 if (isBlacklisted) {
2957 newRule = RULE_REJECT_METERED;
2958 } else if (mRestrictBackground && isWhitelisted) {
2959 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002960 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002961 }
Felipe Leme781ba142016-05-09 16:24:48 -07002962 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002963
Felipe Lemef28983d2016-03-25 12:18:23 -07002964 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002965 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002966 + ": isForeground=" +isForeground
2967 + ", isBlacklisted=" + isBlacklisted
2968 + ", isWhitelisted=" + isWhitelisted
2969 + ", oldRule=" + uidRulesToString(oldRule)
2970 + ", newRule=" + uidRulesToString(newRule)
2971 + ", newUidRules=" + uidRulesToString(newUidRules)
2972 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002973 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002974
Felipe Leme46c4fc32016-05-04 09:21:43 -07002975 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002976 mUidRules.delete(uid);
2977 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002978 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002979 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002980
Felipe Leme70c57c22016-03-29 10:45:13 -07002981 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002982 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002983 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002984 // Temporarily whitelist foreground app, removing from blacklist if necessary
2985 // (since bw_penalty_box prevails over bw_happy_box).
2986
2987 setMeteredNetworkWhitelist(uid, true);
2988 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2989 // but ideally it should be just:
2990 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002991 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002992 setMeteredNetworkBlacklist(uid, false);
2993 }
Felipe Leme781ba142016-05-09 16:24:48 -07002994 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002995 // Remove temporary whitelist from app that is not on foreground anymore.
2996
2997 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2998 // but ideally they should be just:
2999 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3000 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003001 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003002 setMeteredNetworkWhitelist(uid, false);
3003 }
Felipe Leme781ba142016-05-09 16:24:48 -07003004 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003005 setMeteredNetworkBlacklist(uid, true);
3006 }
Felipe Leme781ba142016-05-09 16:24:48 -07003007 } else if ((newRule & RULE_REJECT_METERED) != 0
3008 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003009 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003010 setMeteredNetworkBlacklist(uid, isBlacklisted);
3011 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003012 // Since blacklist prevails over whitelist, we need to handle the special case
3013 // where app is whitelisted and blacklisted at the same time (although such
3014 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003015 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003016 }
Felipe Leme781ba142016-05-09 16:24:48 -07003017 } else if ((newRule & RULE_ALLOW_METERED) != 0
3018 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003019 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003020 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003021 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003022 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003023 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3024 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003025 + ", whitelisted=" + isWhitelisted
3026 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003027 + ", newRule=" + uidRulesToString(newUidRules)
3028 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003029 }
Felipe Leme781ba142016-05-09 16:24:48 -07003030
3031 // Dispatch changed rule to existing listeners.
3032 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3033 }
3034 }
3035
3036 /**
3037 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3038 * listeners in case of change.
3039 * <p>
3040 * There are 3 power-related rules that affects whether an app has background access on
3041 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3042 * restriction, it's added to the equivalent firewall chain:
3043 * <ul>
3044 * <li>App is idle: {@code fw_standby} firewall chain.
3045 * <li>Device is idle: {@code fw_dozable} firewall chain.
3046 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3047 * </ul>
3048 * <p>
3049 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3050 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3051 * <p>
3052 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3053 */
Felipe Lemef0823852016-06-08 13:43:08 -07003054 private void updateRulesForPowerRestrictionsUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003055 if (!isUidValidForBlacklistRules(uid)) {
3056 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
3057 return;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003058 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003059
Felipe Leme781ba142016-05-09 16:24:48 -07003060 final boolean isIdle = isUidIdle(uid);
3061 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Leme781ba142016-05-09 16:24:48 -07003062 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003063 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003064
Felipe Lemef0823852016-06-08 13:43:08 -07003065 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003066 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3067 int newRule = RULE_NONE;
3068
3069 // First step: define the new rule based on user restrictions and foreground state.
3070
3071 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3072 // by considering the foreground and non-foreground states.
3073 if (isForeground) {
3074 if (restrictMode) {
3075 newRule = RULE_ALLOW_ALL;
3076 }
3077 } else if (restrictMode) {
3078 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3079 }
3080
3081 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3082
3083 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003084 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003085 + ", isIdle: " + isIdle
3086 + ", mRestrictPower: " + mRestrictPower
3087 + ", mDeviceIdleMode: " + mDeviceIdleMode
3088 + ", isForeground=" + isForeground
3089 + ", isWhitelisted=" + isWhitelisted
3090 + ", oldRule=" + uidRulesToString(oldRule)
3091 + ", newRule=" + uidRulesToString(newRule)
3092 + ", newUidRules=" + uidRulesToString(newUidRules)
3093 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3094 }
3095
3096 if (newUidRules == RULE_NONE) {
3097 mUidRules.delete(uid);
3098 } else {
3099 mUidRules.put(uid, newUidRules);
3100 }
3101
3102 // Second step: notify listeners if state changed.
3103 if (newRule != oldRule) {
3104 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003105 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003106 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003107 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3108 } else {
3109 // All scenarios should have been covered above
3110 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3111 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003112 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003113 + ", newRule=" + uidRulesToString(newUidRules)
3114 + ", oldRule=" + uidRulesToString(oldUidRules));
3115 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003116 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003117 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003118 }
3119
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003120 private class AppIdleStateChangeListener
3121 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3122
3123 @Override
3124 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3125 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003126 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3127 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003128 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003129 synchronized (mUidRulesFirstLock) {
3130 updateRuleForAppIdleUL(uid);
3131 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003132 }
3133 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003134 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003135 }
3136
3137 @Override
3138 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003139 synchronized (mUidRulesFirstLock) {
3140 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003141 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003142 }
3143 }
3144
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003145 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3146 if (listener != null) {
3147 try {
3148 listener.onUidRulesChanged(uid, uidRules);
3149 } catch (RemoteException ignored) {
3150 }
3151 }
3152 }
3153
3154 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3155 String[] meteredIfaces) {
3156 if (listener != null) {
3157 try {
3158 listener.onMeteredIfacesChanged(meteredIfaces);
3159 } catch (RemoteException ignored) {
3160 }
3161 }
3162 }
3163
3164 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3165 boolean restrictBackground) {
3166 if (listener != null) {
3167 try {
3168 listener.onRestrictBackgroundChanged(restrictBackground);
3169 } catch (RemoteException ignored) {
3170 }
3171 }
3172 }
3173
3174 private void dispatchRestrictBackgroundWhitelistChanged(INetworkPolicyListener listener,
3175 int uid, boolean whitelisted) {
3176 if (listener != null) {
3177 try {
3178 listener.onRestrictBackgroundWhitelistChanged(uid, whitelisted);
3179 } catch (RemoteException ignored) {
3180 }
3181 }
3182 }
3183
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003184 private void dispatchRestrictBackgroundBlacklistChanged(INetworkPolicyListener listener,
3185 int uid, boolean blacklisted) {
3186 if (listener != null) {
3187 try {
3188 listener.onRestrictBackgroundBlacklistChanged(uid, blacklisted);
3189 } catch (RemoteException ignored) {
3190 }
3191 }
3192 }
3193
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003194 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003195 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003196 public boolean handleMessage(Message msg) {
3197 switch (msg.what) {
3198 case MSG_RULES_CHANGED: {
3199 final int uid = msg.arg1;
3200 final int uidRules = msg.arg2;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003201 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003202 final int length = mListeners.beginBroadcast();
3203 for (int i = 0; i < length; i++) {
3204 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003205 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003206 }
3207 mListeners.finishBroadcast();
3208 return true;
3209 }
3210 case MSG_METERED_IFACES_CHANGED: {
3211 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003212 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003213 final int length = mListeners.beginBroadcast();
3214 for (int i = 0; i < length; i++) {
3215 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003216 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003217 }
3218 mListeners.finishBroadcast();
3219 return true;
3220 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003221 case MSG_LIMIT_REACHED: {
3222 final String iface = (String) msg.obj;
3223
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003224 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003225 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003226 if (mMeteredIfaces.contains(iface)) {
3227 try {
3228 // force stats update to make sure we have
3229 // numbers that caused alert to trigger.
3230 mNetworkStats.forceUpdate();
3231 } catch (RemoteException e) {
3232 // ignored; service lives in system_server
3233 }
3234
Felipe Lemef0823852016-06-08 13:43:08 -07003235 updateNetworkEnabledNL();
3236 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003237 }
3238 }
3239 return true;
3240 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003241 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3242 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003243 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003244 final int length = mListeners.beginBroadcast();
3245 for (int i = 0; i < length; i++) {
3246 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003247 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003248 }
3249 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003250 final Intent intent =
3251 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3252 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3253 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3254 return true;
3255 }
3256 case MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED: {
Felipe Leme019fcd22016-04-19 10:24:39 -07003257 // MSG_RESTRICT_BACKGROUND_WHITELIST_CHANGED can be called in 2 occasions:
3258 // - when an app is whitelisted
3259 // - when an app is blacklisted
3260 //
3261 // Whether the internal listeners (INetworkPolicyListener implementations) or
3262 // app broadcast receivers are notified depend on the following rules:
3263 //
3264 // - App receivers are only notified when the app status changed (msg.arg2 = 1)
3265 // - Listeners are only notified when app was whitelisted (msg.obj is not null),
3266 // since blacklist notifications are handled through MSG_RULES_CHANGED).
Felipe Leme9778f762016-01-27 14:46:39 -08003267 final int uid = msg.arg1;
Felipe Leme019fcd22016-04-19 10:24:39 -07003268 final boolean changed = msg.arg2 == 1;
3269 final Boolean whitelisted = (Boolean) msg.obj;
3270
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003271 // First notify internal listeners...
Felipe Leme019fcd22016-04-19 10:24:39 -07003272 if (whitelisted != null) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003273 final boolean whitelistedBool = whitelisted.booleanValue();
3274 dispatchRestrictBackgroundWhitelistChanged(mConnectivityListener, uid,
3275 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003276 final int length = mListeners.beginBroadcast();
3277 for (int i = 0; i < length; i++) {
Felipe Leme019fcd22016-04-19 10:24:39 -07003278 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003279 dispatchRestrictBackgroundWhitelistChanged(listener, uid,
3280 whitelistedBool);
Felipe Leme019fcd22016-04-19 10:24:39 -07003281 }
3282 mListeners.finishBroadcast();
3283 }
Felipe Leme9778f762016-01-27 14:46:39 -08003284 final PackageManager pm = mContext.getPackageManager();
3285 final String[] packages = pm.getPackagesForUid(uid);
Felipe Leme019fcd22016-04-19 10:24:39 -07003286 if (changed && packages != null) {
3287 // ...then notify apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
Felipe Leme86e5a012016-02-16 16:26:05 -08003288 final int userId = UserHandle.getUserId(uid);
3289 for (String packageName : packages) {
3290 final Intent intent = new Intent(
3291 ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3292 intent.setPackage(packageName);
3293 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3294 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3295 }
Felipe Leme9778f762016-01-27 14:46:39 -08003296 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003297 return true;
3298 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003299 case MSG_RESTRICT_BACKGROUND_BLACKLIST_CHANGED: {
3300 final int uid = msg.arg1;
3301 final boolean blacklisted = msg.arg2 == 1;
3302
3303 dispatchRestrictBackgroundBlacklistChanged(mConnectivityListener, uid,
3304 blacklisted);
3305 final int length = mListeners.beginBroadcast();
3306 for (int i = 0; i < length; i++) {
3307 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3308 dispatchRestrictBackgroundBlacklistChanged(listener, uid,
3309 blacklisted);
3310 }
3311 mListeners.finishBroadcast();
3312 return true;
3313 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003314 case MSG_ADVISE_PERSIST_THRESHOLD: {
3315 final long lowestRule = (Long) msg.obj;
3316 try {
3317 // make sure stats are recorded frequently enough; we aim
3318 // for 2MB threshold for 2GB/month rules.
3319 final long persistThreshold = lowestRule / 1000;
3320 mNetworkStats.advisePersistThreshold(persistThreshold);
3321 } catch (RemoteException e) {
3322 // ignored; service lives in system_server
3323 }
3324 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003325 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003326 case MSG_UPDATE_INTERFACE_QUOTA: {
3327 removeInterfaceQuota((String) msg.obj);
3328 // int params need to be stitched back into a long
3329 setInterfaceQuota((String) msg.obj,
3330 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3331 return true;
3332 }
3333 case MSG_REMOVE_INTERFACE_QUOTA: {
3334 removeInterfaceQuota((String) msg.obj);
3335 return true;
3336 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003337 default: {
3338 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003339 }
3340 }
3341 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003342 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003343
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003344 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003345 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003346 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003347 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003348 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003349 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003350 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003351 }
3352 }
3353
3354 private void removeInterfaceQuota(String iface) {
3355 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003356 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003357 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003358 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003359 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003360 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003361 }
3362 }
3363
Felipe Leme70c57c22016-03-29 10:45:13 -07003364 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3365 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003366 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003367 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003368 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003369 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3370 } catch (RemoteException e) {
3371 // ignored; service lives in system_server
3372 }
3373 }
3374
3375 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3376 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3377 try {
3378 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3379 } catch (IllegalStateException e) {
3380 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003381 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003382 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003383 }
3384 }
3385
Amith Yamasani15e472352015-04-24 19:06:07 -07003386 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003387 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3388 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3389 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003390 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003391 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003392 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003393 int size = uidRules.size();
3394 int[] uids = new int[size];
3395 int[] rules = new int[size];
3396 for(int index = size - 1; index >= 0; --index) {
3397 uids[index] = uidRules.keyAt(index);
3398 rules[index] = uidRules.valueAt(index);
3399 }
3400 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003401 } catch (IllegalStateException e) {
3402 Log.wtf(TAG, "problem setting firewall uid rules", e);
3403 } catch (RemoteException e) {
3404 // ignored; service lives in system_server
3405 }
3406 }
3407
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003408 /**
3409 * Add or remove a uid to the firewall blacklist for all network ifaces.
3410 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003411 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003412 if (chain == FIREWALL_CHAIN_DOZABLE) {
3413 mUidFirewallDozableRules.put(uid, rule);
3414 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3415 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003416 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3417 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003418 }
3419
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003420 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003421 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003422 } catch (IllegalStateException e) {
3423 Log.wtf(TAG, "problem setting firewall uid rules", e);
3424 } catch (RemoteException e) {
3425 // ignored; service lives in system_server
3426 }
3427 }
3428
3429 /**
3430 * Add or remove a uid to the firewall blacklist for all network ifaces.
3431 */
Felipe Lemef0823852016-06-08 13:43:08 -07003432 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003433 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3434 mFirewallChainStates.get(chain) == enable) {
3435 // All is the same, nothing to do.
3436 return;
3437 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003438 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003439 try {
3440 mNetworkManager.setFirewallChainEnabled(chain, enable);
3441 } catch (IllegalStateException e) {
3442 Log.wtf(TAG, "problem enable firewall chain", e);
3443 } catch (RemoteException e) {
3444 // ignored; service lives in system_server
3445 }
3446 }
3447
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003448 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3449 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003450 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003451 } catch (RuntimeException e) {
3452 Slog.w(TAG, "problem reading network stats: " + e);
3453 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003454 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003455 // ignored; service lives in system_server
3456 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003457 }
3458 }
3459
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003460 private boolean isBandwidthControlEnabled() {
3461 final long token = Binder.clearCallingIdentity();
3462 try {
3463 return mNetworkManager.isBandwidthControlEnabled();
3464 } catch (RemoteException e) {
3465 // ignored; service lives in system_server
3466 return false;
3467 } finally {
3468 Binder.restoreCallingIdentity(token);
3469 }
3470 }
3471
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003472 /**
3473 * Try refreshing {@link #mTime} when stale.
3474 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003475 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003476 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003477 mTime.forceRefresh();
3478 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003479 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003480
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003481 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003482 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3483 }
3484
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003485 private static Intent buildAllowBackgroundDataIntent() {
3486 return new Intent(ACTION_ALLOW_BACKGROUND);
3487 }
3488
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003489 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3490 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3491 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3492 return intent;
3493 }
3494
Wei Liu546cb772016-07-21 16:19:01 -07003495 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003496 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003497 intent.setComponent(ComponentName.unflattenFromString(
3498 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003499 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3500 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3501 return intent;
3502 }
3503
Wei Liu546cb772016-07-21 16:19:01 -07003504 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003505 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003506 intent.setComponent(ComponentName.unflattenFromString(
3507 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003508 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3509 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3510 return intent;
3511 }
3512
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003513 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003514 public void addIdleHandler(IdleHandler handler) {
3515 mHandler.getLooper().getQueue().addIdleHandler(handler);
3516 }
3517
Jeff Sharkey1b861272011-05-22 00:34:52 -07003518 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3519 final int size = source.size();
3520 for (int i = 0; i < size; i++) {
3521 target.put(source.keyAt(i), true);
3522 }
3523 }
3524
Stuart Scottf1fb3972015-04-02 18:00:02 -07003525 @Override
3526 public void factoryReset(String subscriber) {
3527 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3528
Stuart Scotte3e314d2015-04-20 14:07:45 -07003529 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3530 return;
3531 }
3532
Stuart Scottf1fb3972015-04-02 18:00:02 -07003533 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003534 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003535 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3536 for (NetworkPolicy policy : policies) {
3537 if (policy.template.equals(template)) {
3538 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3539 policy.inferred = false;
3540 policy.clearSnooze();
3541 }
3542 }
3543 setNetworkPolicies(policies);
3544
3545 // Turn restrict background data off
3546 setRestrictBackground(false);
3547
Stuart Scotte3e314d2015-04-20 14:07:45 -07003548 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3549 // Remove app's "restrict background data" flag
3550 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3551 setUidPolicy(uid, POLICY_NONE);
3552 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003553 }
3554 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003555
3556 private class MyPackageMonitor extends PackageMonitor {
3557
3558 @Override
3559 public void onPackageRemoved(String packageName, int uid) {
3560 if (LOGV) Slog.v(TAG, "onPackageRemoved: " + packageName + " ->" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -07003561 synchronized (mUidRulesFirstLock) {
3562 removeRestrictBackgroundWhitelistedUidUL(uid, true, true);
3563 updateRestrictionRulesForUidUL(uid);
Felipe Lemeb85a6372016-01-14 16:16:16 -08003564 }
3565 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003566 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003567
3568 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3569
3570 @Override
3571 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003572 synchronized (mUidRulesFirstLock) {
3573 boolean changed = removeUserStateUL(userId, false);
3574 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003575 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003576 synchronized (mNetworkPoliciesSecondLock) {
3577 writePolicyAL();
3578 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003579 }
3580 }
3581 }
3582 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003583}