blob: ac3a025a6fc0ebf0cddb263cba63631f90618833 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
56import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070060import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070069import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
70import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
71import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
72import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
73import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
74import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
75import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070076import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080077
Jeff Sharkey854b2b12012-04-13 16:03:40 -070078import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070079import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.readBooleanAttribute;
81import static com.android.internal.util.XmlUtils.readIntAttribute;
82import static com.android.internal.util.XmlUtils.readLongAttribute;
83import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
84import static com.android.internal.util.XmlUtils.writeIntAttribute;
85import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070086import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070087import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060088
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080090import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070092
Dianne Hackborn88e98df2015-03-23 13:29:14 -070093import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070094import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070095import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070096import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070097import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070098import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070099import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700101import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700102import android.app.Notification;
103import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700104import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700106import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700107import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700108import android.content.Intent;
109import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700111import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700112import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700113import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700114import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700115import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700118import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700120import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700121import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700123import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700124import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkPolicy;
Jeff 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;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800142import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700144import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600145import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700147import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700148import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700149import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700150import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700151import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800152import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700153import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400154import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700155import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700156import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700157import android.util.ArrayMap;
158import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700159import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700160import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700161import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700162import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700163import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700164import android.util.SparseBooleanArray;
165import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700166import android.util.TrustedTime;
167import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700168
Jeff Sharkey497e4432011-06-14 17:27:29 -0700169import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700170import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800171import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkey32566012014-12-02 18:30:14 -0800172import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700173import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700174import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700175import com.android.server.DeviceIdleController;
176import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700177import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800178import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600179
180import libcore.io.IoUtils;
181
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700182import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700183
184import org.xmlpull.v1.XmlPullParser;
185import org.xmlpull.v1.XmlPullParserException;
186import org.xmlpull.v1.XmlSerializer;
187
188import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700189import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700190import java.io.FileInputStream;
191import java.io.FileNotFoundException;
192import java.io.FileOutputStream;
193import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700194import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700195import java.lang.annotation.Retention;
196import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100197import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198import java.util.ArrayList;
199import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700200import java.util.List;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800201import java.util.concurrent.CountDownLatch;
202import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700204/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700205 * Service that maintains low-level network policy rules, using
206 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700207 * <p>
208 * Derives active rules by combining a given policy with other system status,
209 * and delivers to listeners, such as {@link ConnectivityManager}, for
210 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700211 *
212 * <p>
213 * This class uses 2-3 locks to synchronize state:
214 * <ul>
215 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
216 * rules).
217 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
218 * as network policies).
219 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
220 * must be held.
221 * </ul>
222 *
223 * <p>
224 * As such, methods that require synchronization have the following prefixes:
225 * <ul>
226 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
227 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
228 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
229 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
230 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700231 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700232public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800233 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700234 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700235 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700236
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700237 private static final int VERSION_INIT = 1;
238 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700239 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800240 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800241 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800242 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700243 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700244 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700245 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700246 private static final int VERSION_SWITCH_UID = 10;
247 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700248
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800249 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700250 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800251 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700252 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800253 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700254 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700255
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700256 private static final String TAG_POLICY_LIST = "policy-list";
257 private static final String TAG_NETWORK_POLICY = "network-policy";
258 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700259 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800260 private static final String TAG_WHITELIST = "whitelist";
261 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800262 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700263
264 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700265 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
267 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700268 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800270 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271 private static final String ATTR_WARNING_BYTES = "warningBytes";
272 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700273 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800274 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
275 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800276 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700277 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700278 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700279 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 private static final String ATTR_POLICY = "policy";
281
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800282 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800283 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800284 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800285 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700286
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
288
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700289 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700290 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800291 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800292 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700293 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700294 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
295 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700296 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700297 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700298 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700299
Jeff Sharkey75279902011-05-24 18:39:45 -0700300 private final Context mContext;
301 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700302 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700303 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700304 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700305 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700306 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700307
308 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700309 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700310 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700311 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700312
Felipe Lemef0823852016-06-08 13:43:08 -0700313 // See main javadoc for instructions on how to use these locks.
314 final Object mUidRulesFirstLock = new Object();
315 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700316
Felipe Lemef0823852016-06-08 13:43:08 -0700317 @GuardedBy("allLocks") volatile boolean mSystemReady;
318
Felipe Lemef0823852016-06-08 13:43:08 -0700319 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
320 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
321 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700322
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700323 private final boolean mSuppressDefaultPolicy;
324
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700325 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800326 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700327 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800328 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700329
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700330 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700331 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700332 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700333 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700334
Felipe Lemef0823852016-06-08 13:43:08 -0700335 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700336 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700337 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700338 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700339 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800340 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700341
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700342 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700343 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700344 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
345
Jeff Sharkey32566012014-12-02 18:30:14 -0800346 /**
347 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700348 * in power save mode, except device idle (doze) still applies.
349 * TODO: An int array might be sufficient
350 */
Felipe Lemef0823852016-06-08 13:43:08 -0700351 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700352 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
353
354 /**
355 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800356 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700357 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800358 */
Felipe Lemef0823852016-06-08 13:43:08 -0700359 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700360 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700361
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700363 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
364
Felipe Lemeb85a6372016-01-14 16:16:16 -0800365 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800366 * UIDs that have been initially white-listed by system to avoid restricted background.
367 */
Felipe Lemef0823852016-06-08 13:43:08 -0700368 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800369 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
370 new SparseBooleanArray();
371
372 /**
373 * UIDs that have been initially white-listed by system to avoid restricted background,
374 * but later revoked by user.
375 */
Felipe Lemef0823852016-06-08 13:43:08 -0700376 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800377 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
378 new SparseBooleanArray();
379
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700380 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700383 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800385 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700386
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700387 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700389 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700390
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700391 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800393 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700394
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600395 /** Higher priority listener before general event dispatch */
396 private INetworkPolicyListener mConnectivityListener;
397
Jeff Sharkey32566012014-12-02 18:30:14 -0800398 private final RemoteCallbackList<INetworkPolicyListener>
399 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700400
Dianne Hackborn497175b2014-07-01 12:56:08 -0700401 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700402
Felipe Lemef0823852016-06-08 13:43:08 -0700403 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700404 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700405
Svet Ganov16a16892015-04-16 10:32:04 -0700406 private final AppOpsManager mAppOps;
407
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800408 private final IPackageManager mIPm;
409
Felipe Lemeb85a6372016-01-14 16:16:16 -0800410
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700411 // TODO: keep whitelist of system-critical services that should never have
412 // rules enforced, such as system, phone, and radio UIDs.
413
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700414 // TODO: migrate notifications to SystemUI
415
Jeff Sharkey75279902011-05-24 18:39:45 -0700416 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700417 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
418 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700419 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
420 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700421 }
422
423 private static File getSystemDir() {
424 return new File(Environment.getDataDirectory(), "system");
425 }
426
427 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700428 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700429 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700430 mContext = checkNotNull(context, "missing context");
431 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700432 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700433 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700434 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700435 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700437 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700438 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439
Amith Yamasani450a16b2013-09-18 16:28:50 -0700440 HandlerThread thread = new HandlerThread(TAG);
441 thread.start();
442 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700444 mSuppressDefaultPolicy = suppressDefaultPolicy;
445
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700446 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700447
448 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800449
Felipe Lemed17fda42016-04-29 11:12:45 -0700450 // Expose private service for system components to use.
451 LocalServices.addService(NetworkPolicyManagerInternal.class,
452 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700453 }
454
455 public void bindConnectivityManager(IConnectivityManager connManager) {
456 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700457 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700458
Jeff Sharkey497e4432011-06-14 17:27:29 -0700459 public void bindNotificationManager(INotificationManager notifManager) {
460 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
461 }
462
Felipe Lemef0823852016-06-08 13:43:08 -0700463 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700464 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700465 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
466 mPowerSaveWhitelistExceptIdleAppIds.clear();
467 if (whitelist != null) {
468 for (int uid : whitelist) {
469 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
470 }
471 }
472 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700473 mPowerSaveWhitelistAppIds.clear();
474 if (whitelist != null) {
475 for (int uid : whitelist) {
476 mPowerSaveWhitelistAppIds.put(uid, true);
477 }
478 }
479 } catch (RemoteException e) {
480 }
481 }
482
Felipe Lemea9505cc2016-02-26 10:28:41 -0800483 /**
484 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
485 * revoke the whitelist.
486 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700487 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800488 */
Felipe Lemef0823852016-06-08 13:43:08 -0700489 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800490 final List<UserInfo> users = mUserManager.getUsers();
491 final int numberUsers = users.size();
492
Felipe Lemea110eec2016-04-29 09:58:06 -0700493 boolean changed = false;
494 for (int i = 0; i < numberUsers; i++) {
495 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700496 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700497 }
498 return changed;
499 }
500
Felipe Lemef0823852016-06-08 13:43:08 -0700501 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700502 final SystemConfig sysConfig = SystemConfig.getInstance();
503 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800504 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
505 boolean changed = false;
506 for (int i = 0; i < allowDataUsage.size(); i++) {
507 final String pkg = allowDataUsage.valueAt(i);
508 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700509 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
510 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800511 final ApplicationInfo app;
512 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700513 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800514 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700515 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
516 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800517 continue;
518 }
519 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700520 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
521 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800522 continue;
523 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700524 final int uid = UserHandle.getUid(userId, app.uid);
525 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
526 if (LOGD)
527 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
528 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800529 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700530 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700531 if (LOGD)
532 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
533 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700534 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700535 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 }
537 }
538 return changed;
539 }
540
Felipe Lemef0823852016-06-08 13:43:08 -0700541 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700542 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700543 // Clear the states of the current whitelist
544 final int N = mPowerSaveTempWhitelistAppIds.size();
545 for (int i = 0; i < N; i++) {
546 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
547 }
548 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700549 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700550 if (whitelist != null) {
551 for (int uid : whitelist) {
552 mPowerSaveTempWhitelistAppIds.put(uid, true);
553 }
554 }
555 } catch (RemoteException e) {
556 }
557 }
558
Amith Yamasani06f08062015-06-12 13:23:33 -0700559 /**
560 * Remove unnecessary entries in the temp whitelist
561 */
Felipe Lemef0823852016-06-08 13:43:08 -0700562 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700563 final int N = mPowerSaveTempWhitelistAppIds.size();
564 for (int i = N - 1; i >= 0; i--) {
565 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
566 mPowerSaveTempWhitelistAppIds.removeAt(i);
567 }
568 }
569 }
570
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800571 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700572 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800573 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700574 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800575 // Boost thread's priority during system server init
576 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700577 if (!isBandwidthControlEnabled()) {
578 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
579 return;
580 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700581
Felipe Leme873a83a2016-09-07 11:34:10 -0700582 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700583
Felipe Leme873a83a2016-09-07 11:34:10 -0700584 synchronized (mUidRulesFirstLock) {
585 synchronized (mNetworkPoliciesSecondLock) {
586 updatePowerSaveWhitelistUL();
587 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
588 mPowerManagerInternal.registerLowPowerModeObserver(
589 new PowerManagerInternal.LowPowerModeListener() {
590 @Override
591 public void onLowPowerModeChanged(boolean enabled) {
592 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
593 synchronized (mUidRulesFirstLock) {
594 if (mRestrictPower != enabled) {
595 mRestrictPower = enabled;
596 updateRulesForRestrictPowerUL();
597 }
Felipe Lemef0823852016-06-08 13:43:08 -0700598 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700599 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700600 });
601 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
602
603 mSystemReady = true;
604
605 // read policy from disk
606 readPolicyAL();
607
608 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
609 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700610 }
Felipe Lemef0823852016-06-08 13:43:08 -0700611
Felipe Leme873a83a2016-09-07 11:34:10 -0700612 setRestrictBackgroundUL(mRestrictBackground);
613 updateRulesForGlobalChangeAL(false);
614 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700615 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800616 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700617
618 try {
619 mActivityManager.registerUidObserver(mUidObserver,
Dianne Hackborn058f1e42016-11-02 17:18:35 -0700620 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800621 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700622 mNetworkManager.registerObserver(mAlertObserver);
623 } catch (RemoteException e) {
624 // ignored; both services live in system_server
625 }
626
627 // listen for changes to power save whitelist
628 final IntentFilter whitelistFilter = new IntentFilter(
629 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
630 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
631
632 DeviceIdleController.LocalService deviceIdleService
633 = LocalServices.getService(DeviceIdleController.LocalService.class);
634 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
635
636 // watch for network interfaces to be claimed
637 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
638 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
639
640 // listen for package changes to update policy
641 final IntentFilter packageFilter = new IntentFilter();
642 packageFilter.addAction(ACTION_PACKAGE_ADDED);
643 packageFilter.addDataScheme("package");
644 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
645
646 // listen for UID changes to update policy
647 mContext.registerReceiver(
648 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
649
650 // listen for user changes to update policy
651 final IntentFilter userFilter = new IntentFilter();
652 userFilter.addAction(ACTION_USER_ADDED);
653 userFilter.addAction(ACTION_USER_REMOVED);
654 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
655
656 // listen for stats update events
657 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
658 mContext.registerReceiver(
659 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
660
661 // listen for restrict background changes from notifications
662 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
663 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
664
665 // listen for snooze warning from notifications
666 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
667 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
668 MANAGE_NETWORK_POLICY, mHandler);
669
670 // listen for configured wifi networks to be removed
671 final IntentFilter wifiConfigFilter =
672 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
673 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
674
675 // listen for wifi state changes to catch metered hint
676 final IntentFilter wifiStateFilter = new IntentFilter(
677 WifiManager.NETWORK_STATE_CHANGED_ACTION);
678 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
679
680 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800681 // tell systemReady() that the service has been initialized
682 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700683 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800684 // Restore the default priority after init is done
685 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700686 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700687 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700688 }
689
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800690 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
691 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
692 mHandler.post(() -> initService(initCompleteSignal));
693 return initCompleteSignal;
694 }
695
696 public void systemReady(CountDownLatch initCompleteSignal) {
697 // wait for initService to complete
698 try {
699 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
700 throw new IllegalStateException("Service " + TAG +" init timeout");
701 }
702 } catch (InterruptedException e) {
703 Thread.currentThread().interrupt();
704 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
705 }
706 }
707
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700708 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700709 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700710 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
711 try {
712 synchronized (mUidRulesFirstLock) {
713 updateUidStateUL(uid, procState);
714 }
715 } finally {
716 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700717 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700718 }
719
Dianne Hackborne07641d2016-11-09 15:07:23 -0800720 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700721 synchronized (mUidRulesFirstLock) {
722 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700723 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700724 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700725
726 @Override public void onUidActive(int uid) throws RemoteException {
727 }
728
Dianne Hackborne07641d2016-11-09 15:07:23 -0800729 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700730 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700731 };
732
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700733 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700734 @Override
735 public void onReceive(Context context, Intent intent) {
736 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700737 synchronized (mUidRulesFirstLock) {
738 updatePowerSaveWhitelistUL();
739 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700740 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700741 }
742 }
743 };
744
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700745 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
746 @Override
747 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700748 synchronized (mUidRulesFirstLock) {
749 updatePowerSaveTempWhitelistUL();
750 updateRulesForTempWhitelistChangeUL();
751 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700752 }
753 }
754 };
755
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700756 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700757 @Override
758 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700759 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700760
761 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700762 final int uid = intent.getIntExtra(EXTRA_UID, -1);
763 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700764
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700765 if (ACTION_PACKAGE_ADDED.equals(action)) {
766 // update rules for UID, since it might be subject to
767 // global background data policy
768 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700769 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700770 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700771 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700772 }
773 }
774 };
775
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700776 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700777 @Override
778 public void onReceive(Context context, Intent intent) {
779 // on background handler thread, and UID_REMOVED is protected
780
781 final int uid = intent.getIntExtra(EXTRA_UID, -1);
782 if (uid == -1) return;
783
784 // remove any policy and update rules to clean up
785 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700786 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700787 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700788 synchronized (mNetworkPoliciesSecondLock) {
789 writePolicyAL();
790 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700791 }
792 }
793 };
794
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700795 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700796 @Override
797 public void onReceive(Context context, Intent intent) {
798 // on background handler thread, and USER_ADDED and USER_REMOVED
799 // broadcasts are protected
800
801 final String action = intent.getAction();
802 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
803 if (userId == -1) return;
804
Amith Yamasani15e472352015-04-24 19:06:07 -0700805 switch (action) {
806 case ACTION_USER_REMOVED:
807 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700808 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800809 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700810 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700811 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700812 if (action == ACTION_USER_ADDED) {
813 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700814 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700815 }
816 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700817 synchronized (mNetworkPoliciesSecondLock) {
818 updateRulesForGlobalChangeAL(true);
819 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700820 }
821 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700822 }
823 }
824 };
825
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700826 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700827 * Receiver that watches for {@link INetworkStatsService} updates, which we
828 * use to check against {@link NetworkPolicy#warningBytes}.
829 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700830 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700831 @Override
832 public void onReceive(Context context, Intent intent) {
833 // on background handler thread, and verified
834 // READ_NETWORK_USAGE_HISTORY permission above.
835
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800836 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700837 synchronized (mNetworkPoliciesSecondLock) {
838 updateNetworkEnabledNL();
839 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700840 }
841 }
842 };
843
844 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700845 * Receiver that watches for {@link Notification} control of
846 * {@link #mRestrictBackground}.
847 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700848 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700849 @Override
850 public void onReceive(Context context, Intent intent) {
851 // on background handler thread, and verified MANAGE_NETWORK_POLICY
852 // permission above.
853
854 setRestrictBackground(false);
855 }
856 };
857
858 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800859 * Receiver that watches for {@link Notification} control of
860 * {@link NetworkPolicy#lastWarningSnooze}.
861 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700862 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800863 @Override
864 public void onReceive(Context context, Intent intent) {
865 // on background handler thread, and verified MANAGE_NETWORK_POLICY
866 // permission above.
867
868 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
869 performSnooze(template, TYPE_WARNING);
870 }
871 };
872
873 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700874 * Receiver that watches for {@link WifiConfiguration} to be changed.
875 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700876 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700877 @Override
878 public void onReceive(Context context, Intent intent) {
879 // on background handler thread, and verified CONNECTIVITY_INTERNAL
880 // permission above.
881
882 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
883 if (reason == CHANGE_REASON_REMOVED) {
884 final WifiConfiguration config = intent.getParcelableExtra(
885 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700886 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800887 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700888 synchronized (mUidRulesFirstLock) {
889 synchronized (mNetworkPoliciesSecondLock) {
890 if (mNetworkPolicy.containsKey(template)) {
891 mNetworkPolicy.remove(template);
892 writePolicyAL();
893 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700894 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700895 }
896 }
897 }
898 }
899 };
900
901 /**
902 * Receiver that watches {@link WifiInfo} state changes to infer metered
903 * state. Ignores hints when policy is user-defined.
904 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700905 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700906 @Override
907 public void onReceive(Context context, Intent intent) {
908 // on background handler thread, and verified CONNECTIVITY_INTERNAL
909 // permission above.
910
911 // ignore when not connected
912 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
913 if (!netInfo.isConnected()) return;
914
915 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
916 final boolean meteredHint = info.getMeteredHint();
917
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800918 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700919 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700920 NetworkPolicy policy = mNetworkPolicy.get(template);
921 if (policy == null && meteredHint) {
922 // policy doesn't exist, and AP is hinting that it's
923 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800924 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700925 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700926
927 } else if (policy != null && policy.inferred) {
928 // policy exists, and was inferred: update its current
929 // metered state.
930 policy.metered = meteredHint;
931
932 // since this is inferred for each wifi session, just update
933 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700934 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700935 }
936 }
937 }
938 };
939
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800940 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
941 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
942 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
943 metered, true);
944 }
945
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700946 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700947 * Observer that watches for {@link INetworkManagementService} alerts.
948 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949 final private INetworkManagementEventObserver mAlertObserver
950 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700951 @Override
952 public void limitReached(String limitName, String iface) {
953 // only someone like NMS should be calling us
954 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
955
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800956 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
957 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700958 }
959 }
960 };
961
962 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700963 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
964 * to show visible notifications as needed.
965 */
Felipe Lemef0823852016-06-08 13:43:08 -0700966 void updateNotificationsNL() {
967 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700968
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700969 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700970 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700971 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700972
973 // TODO: when switching to kernel notifications, compute next future
974 // cycle boundary to recompute notifications.
975
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700976 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800977 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700978 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
979 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700980 // ignore policies that aren't relevant to user
981 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700982 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700983
Jeff Sharkey497e4432011-06-14 17:27:29 -0700984 final long start = computeLastCycleBoundary(currentTime, policy);
985 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700986 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700988 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800989 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700990 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
991 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700992 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700993 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700994 }
995
Jeff Sharkey497e4432011-06-14 17:27:29 -0700996 } else {
Felipe Lemef0823852016-06-08 13:43:08 -0700997 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700998
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800999 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001000 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001 }
1002 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001003 }
1004
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001005 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001006 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
1007 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001008 if (!mActiveNotifs.contains(tag)) {
1009 cancelNotification(tag);
1010 }
1011 }
1012 }
1013
1014 /**
1015 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001016 * current device state, such as when
1017 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1018 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001019 */
1020 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001021 if (template.isMatchRuleMobile()) {
1022 final TelephonyManager tele = TelephonyManager.from(mContext);
1023 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001024
Jeff Sharkey32566012014-12-02 18:30:14 -08001025 // Mobile template is relevant when any active subscriber matches
1026 final int[] subIds = sub.getActiveSubscriptionIdList();
1027 for (int subId : subIds) {
1028 final String subscriberId = tele.getSubscriberId(subId);
1029 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001030 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001031 if (template.matches(probeIdent)) {
1032 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001033 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001034 }
1035 return false;
1036 } else {
1037 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001038 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 }
1040
1041 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 * Notify that given {@link NetworkTemplate} is over
1043 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1044 */
Felipe Lemef0823852016-06-08 13:43:08 -07001045 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001046 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001047 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001048 mOverLimitNotified.add(template);
1049 }
1050 }
1051
Felipe Lemef0823852016-06-08 13:43:08 -07001052 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001053 mOverLimitNotified.remove(template);
1054 }
1055
1056 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057 * Build unique tag that identifies an active {@link NetworkPolicy}
1058 * notification of a specific type, like {@link #TYPE_LIMIT}.
1059 */
1060 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001061 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001062 }
1063
1064 /**
1065 * Show notification for combined {@link NetworkPolicy} and specific type,
1066 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1067 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001069 final String tag = buildNotificationTag(policy, type);
1070 final Notification.Builder builder = new Notification.Builder(mContext);
1071 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001072 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001073 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001074 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075
1076 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001077 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078 switch (type) {
1079 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001080 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001081 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001083 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001084 builder.setTicker(title);
1085 builder.setContentTitle(title);
1086 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001087 builder.setDefaults(Notification.DEFAULT_ALL);
1088 builder.setPriority(Notification.PRIORITY_HIGH);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001089
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001090 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1091 builder.setDeleteIntent(PendingIntent.getBroadcast(
1092 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1093
Wei Liu546cb772016-07-21 16:19:01 -07001094 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001095 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001096 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1097
Jeff Sharkey497e4432011-06-14 17:27:29 -07001098 break;
1099 }
1100 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001101 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001102
1103 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001104 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001105 switch (policy.template.getMatchRule()) {
1106 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001107 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001108 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001109 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001110 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001111 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001112 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001113 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 case MATCH_WIFI:
1116 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001117 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001118 break;
1119 default:
1120 title = null;
1121 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 }
1123
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001124 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001125 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001126 builder.setTicker(title);
1127 builder.setContentTitle(title);
1128 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001129
Wei Liu546cb772016-07-21 16:19:01 -07001130 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131 builder.setContentIntent(PendingIntent.getActivity(
1132 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1133 break;
1134 }
1135 case TYPE_LIMIT_SNOOZED: {
1136 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001137 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001138 Formatter.formatFileSize(mContext, overBytes));
1139
1140 final CharSequence title;
1141 switch (policy.template.getMatchRule()) {
1142 case MATCH_MOBILE_3G_LOWER:
1143 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1144 break;
1145 case MATCH_MOBILE_4G:
1146 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1147 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001148 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1150 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 case MATCH_WIFI:
1152 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1153 break;
1154 default:
1155 title = null;
1156 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001157 }
1158
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001159 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001160 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001161 builder.setTicker(title);
1162 builder.setContentTitle(title);
1163 builder.setContentText(body);
1164
Wei Liu546cb772016-07-21 16:19:01 -07001165 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001166 builder.setContentIntent(PendingIntent.getActivity(
1167 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 break;
1169 }
1170 }
1171
1172 // TODO: move to NotificationManager once we can mock it
1173 try {
1174 final String packageName = mContext.getPackageName();
1175 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001176 if(!TextUtils.isEmpty(body)) {
1177 builder.setStyle(new Notification.BigTextStyle()
1178 .bigText(body));
1179 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001180 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001181 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001182 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001183 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001185 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001186 }
1187 }
1188
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001189 private void cancelNotification(String tag) {
1190 // TODO: move to NotificationManager once we can mock it
1191 try {
1192 final String packageName = mContext.getPackageName();
1193 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001194 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001195 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001196 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001197 }
1198 }
1199
1200 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001201 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001202 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001203 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001204 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 @Override
1206 public void onReceive(Context context, Intent intent) {
1207 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1208 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001209
1210 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001211 synchronized (mNetworkPoliciesSecondLock) {
1212 ensureActiveMobilePolicyNL();
1213 normalizePoliciesNL();
1214 updateNetworkEnabledNL();
1215 updateNetworkRulesNL();
1216 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001217 }
1218 }
1219 };
1220
1221 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001222 * Proactively control network data connections when they exceed
1223 * {@link NetworkPolicy#limitBytes}.
1224 */
Felipe Lemef0823852016-06-08 13:43:08 -07001225 void updateNetworkEnabledNL() {
1226 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001227
1228 // TODO: reset any policy-disabled networks when any policy is removed
1229 // completely, which is currently rare case.
1230
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001231 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001232 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1233 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001234 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001235 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001236 setNetworkTemplateEnabled(policy.template, true);
1237 continue;
1238 }
1239
1240 final long start = computeLastCycleBoundary(currentTime, policy);
1241 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001242 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001243
1244 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001245 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1246 && policy.lastLimitSnooze < start;
1247 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001248
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001249 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001250 }
1251 }
1252
1253 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001254 * Proactively disable networks that match the given
1255 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001256 */
1257 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001258 // TODO: reach into ConnectivityManager to proactively disable bringing
1259 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001260
1261 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1262 // If mobile data usage hits the limit or if the user resumes the data, we need to
1263 // notify telephony.
1264 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1265 final TelephonyManager tm = TelephonyManager.from(mContext);
1266
1267 final int[] subIds = sm.getActiveSubscriptionIdList();
1268 for (int subId : subIds) {
1269 final String subscriberId = tm.getSubscriberId(subId);
1270 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1271 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1272 // Template is matched when subscriber id matches.
1273 if (template.matches(probeIdent)) {
1274 tm.setPolicyDataEnabled(enabled, subId);
1275 }
1276 }
1277 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001278 }
1279
1280 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001281 * Examine all connected {@link NetworkState}, looking for
1282 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1283 * remaining quota based on usage cycle and historical stats.
1284 */
Felipe Lemef0823852016-06-08 13:43:08 -07001285 void updateNetworkRulesNL() {
1286 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001287
1288 final NetworkState[] states;
1289 try {
1290 states = mConnManager.getAllNetworkState();
1291 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001292 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001293 return;
1294 }
1295
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001296 // First, generate identities of all connected networks so we can
1297 // quickly compare them against all defined policies below.
1298 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001299 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001300 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001301 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001303
1304 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001305 if (baseIface != null) {
1306 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001307 }
1308
1309 // Stacked interfaces are considered to have same identity as
1310 // their parent network.
1311 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1312 for (LinkProperties stackedLink : stackedLinks) {
1313 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001314 if (stackedIface != null) {
1315 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001316 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001317 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001318 }
1319 }
1320
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001321 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001322 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001323 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001324 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001325 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001328 for (int j = connIdents.size() - 1; j >= 0; j--) {
1329 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1330 if (policy.template.matches(ident.second)) {
1331 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 }
1333 }
1334
1335 if (ifaceList.size() > 0) {
1336 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001337 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001338 }
1339 }
1340
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001341 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001342 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001343
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001344 // apply each policy that we found ifaces for; compute remaining data
1345 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001346 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001347 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1348 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1349 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001350
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001351 final long start;
1352 final long totalBytes;
1353 if (policy.hasCycle()) {
1354 start = computeLastCycleBoundary(currentTime, policy);
1355 totalBytes = getTotalBytes(policy.template, start, currentTime);
1356 } else {
1357 start = Long.MAX_VALUE;
1358 totalBytes = 0;
1359 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001360
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001361 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001362 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001363 }
1364
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001365 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001366 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001367 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001368 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001369 if (!hasLimit) {
1370 // metered network, but no policy limit; we still need to
1371 // restrict apps, so push really high quota.
1372 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001373 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001374 // snoozing past quota, but we still need to restrict apps,
1375 // so push really high quota.
1376 quotaBytes = Long.MAX_VALUE;
1377 } else {
1378 // remaining "quota" bytes are based on total usage in
1379 // current cycle. kernel doesn't like 0-byte rules, so we
1380 // set 1-byte quota and disable the radio later.
1381 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1382 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001383
1384 if (ifaces.length > 1) {
1385 // TODO: switch to shared quota once NMS supports
1386 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001387 }
1388
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001389 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001390 // long quotaBytes split up into two ints to fit in message
1391 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1392 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1393 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001394 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001395 }
1396 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001397
1398 // keep track of lowest warning or limit of active policies
1399 if (hasWarning && policy.warningBytes < lowestRule) {
1400 lowestRule = policy.warningBytes;
1401 }
1402 if (hasLimit && policy.limitBytes < lowestRule) {
1403 lowestRule = policy.limitBytes;
1404 }
1405 }
1406
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001407 for (int i = connIfaces.size()-1; i >= 0; i--) {
1408 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001409 // long quotaBytes split up into two ints to fit in message
1410 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1411 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1412 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001413 newMeteredIfaces.add(iface);
1414 }
1415
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001416 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001417
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001418 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001419 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1420 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001421 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001422 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1423 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001424 }
1425 }
1426 mMeteredIfaces = newMeteredIfaces;
1427
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001428 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001429 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001430 }
1431
1432 /**
1433 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1434 * have at least a default mobile policy defined.
1435 */
Felipe Lemef0823852016-06-08 13:43:08 -07001436 private void ensureActiveMobilePolicyNL() {
1437 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001438 if (mSuppressDefaultPolicy) return;
1439
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001440 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001441 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001442
Jeff Sharkey32566012014-12-02 18:30:14 -08001443 final int[] subIds = sub.getActiveSubscriptionIdList();
1444 for (int subId : subIds) {
1445 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001446 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001447 }
1448 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001449
Felipe Lemef0823852016-06-08 13:43:08 -07001450 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001451 // Poke around to see if we already have a policy
1452 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001453 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001454 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1455 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1456 if (template.matches(probeIdent)) {
1457 if (LOGD) {
1458 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1459 + NetworkIdentity.scrubSubscriberId(subscriberId));
1460 }
1461 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001462 }
1463 }
1464
Jeff Sharkey32566012014-12-02 18:30:14 -08001465 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1466 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001467
Jeff Sharkey32566012014-12-02 18:30:14 -08001468 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001469 final int dataWarningConfig = mContext.getResources().getInteger(
1470 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1471 final long warningBytes;
1472 if (dataWarningConfig == WARNING_DISABLED) {
1473 warningBytes = WARNING_DISABLED;
1474 } else {
1475 warningBytes = dataWarningConfig * MB_IN_BYTES;
1476 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001477
Jeff Sharkey32566012014-12-02 18:30:14 -08001478 final Time time = new Time();
1479 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001480
Jeff Sharkey32566012014-12-02 18:30:14 -08001481 final int cycleDay = time.monthDay;
1482 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001483
Jeff Sharkey32566012014-12-02 18:30:14 -08001484 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1485 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1486 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001487 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001488 }
1489
Felipe Lemef0823852016-06-08 13:43:08 -07001490 private void readPolicyAL() {
1491 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001492
1493 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001494 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001495 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496
1497 FileInputStream fis = null;
1498 try {
1499 fis = mPolicyFile.openRead();
1500 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001501 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001502
Felipe Leme46b451f2016-08-19 08:46:17 -07001503 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1504 // to skip UIDs that were explicitly blacklisted.
1505 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1506
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001507 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001508 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001509 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 while ((type = in.next()) != END_DOCUMENT) {
1511 final String tag = in.getName();
1512 if (type == START_TAG) {
1513 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001514 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001515 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001516 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1517 mRestrictBackground = readBooleanAttribute(
1518 in, ATTR_RESTRICT_BACKGROUND);
1519 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001520 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001521 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001522 if (mRestrictBackground != oldValue) {
1523 // Some early services may have read the default value,
1524 // so notify them that it's changed
1525 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1526 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1527 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001528
1529 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1530 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1531 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001532 final String networkId;
1533 if (version >= VERSION_ADDED_NETWORK_ID) {
1534 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1535 } else {
1536 networkId = null;
1537 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001538 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001539 final String cycleTimezone;
1540 if (version >= VERSION_ADDED_TIMEZONE) {
1541 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1542 } else {
1543 cycleTimezone = Time.TIMEZONE_UTC;
1544 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1546 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001547 final long lastLimitSnooze;
1548 if (version >= VERSION_SPLIT_SNOOZE) {
1549 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1550 } else if (version >= VERSION_ADDED_SNOOZE) {
1551 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001552 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001553 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001554 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001555 final boolean metered;
1556 if (version >= VERSION_ADDED_METERED) {
1557 metered = readBooleanAttribute(in, ATTR_METERED);
1558 } else {
1559 switch (networkTemplate) {
1560 case MATCH_MOBILE_3G_LOWER:
1561 case MATCH_MOBILE_4G:
1562 case MATCH_MOBILE_ALL:
1563 metered = true;
1564 break;
1565 default:
1566 metered = false;
1567 }
1568 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001569 final long lastWarningSnooze;
1570 if (version >= VERSION_SPLIT_SNOOZE) {
1571 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1572 } else {
1573 lastWarningSnooze = SNOOZE_NEVER;
1574 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001575 final boolean inferred;
1576 if (version >= VERSION_ADDED_INFERRED) {
1577 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1578 } else {
1579 inferred = false;
1580 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581
Jeff Sharkey32566012014-12-02 18:30:14 -08001582 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1583 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001584 if (template.isPersistable()) {
1585 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1586 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1587 lastLimitSnooze, metered, inferred));
1588 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001590 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001591 final int uid = readIntAttribute(in, ATTR_UID);
1592 final int policy = readIntAttribute(in, ATTR_POLICY);
1593
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001594 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001595 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001596 } else {
1597 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1598 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001599 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001600 final int appId = readIntAttribute(in, ATTR_APP_ID);
1601 final int policy = readIntAttribute(in, ATTR_POLICY);
1602
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001603 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001604 // app policy is deprecated so this is only used in pre system user split.
1605 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001606 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001607 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001608 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001609 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001610 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001611 } else if (TAG_WHITELIST.equals(tag)) {
1612 insideWhitelist = true;
1613 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1614 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001615 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001616 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1617 final int uid = readIntAttribute(in, ATTR_UID);
1618 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001620 } else if (type == END_TAG) {
1621 if (TAG_WHITELIST.equals(tag)) {
1622 insideWhitelist = false;
1623 }
1624
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 }
1626 }
1627
Felipe Leme46b451f2016-08-19 08:46:17 -07001628 final int size = whitelistedRestrictBackground.size();
1629 for (int i = 0; i < size; i++) {
1630 final int uid = whitelistedRestrictBackground.keyAt(i);
1631 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1632 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1633 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1634 + " because its policy is " + uidPoliciesToString(policy));
1635 continue;
1636 }
1637 if (UserHandle.isApp(uid)) {
1638 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1639 if (LOGV)
1640 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1641 setUidPolicyUncheckedUL(uid, newPolicy, false);
1642 } else {
1643 Slog.w(TAG, "unable to update policy on UID " + uid);
1644 }
1645 }
1646
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001647 } catch (FileNotFoundException e) {
1648 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001649 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001650 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001651 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001653 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 } finally {
1655 IoUtils.closeQuietly(fis);
1656 }
1657 }
1658
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001659 /**
1660 * Upgrade legacy background data flags, notifying listeners of one last
1661 * change to always-true.
1662 */
Felipe Lemef0823852016-06-08 13:43:08 -07001663 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001664 mRestrictBackground = Settings.Secure.getInt(
1665 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1666
1667 // kick off one last broadcast if restricted
1668 if (mRestrictBackground) {
1669 final Intent broadcast = new Intent(
1670 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001671 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001672 }
1673 }
1674
Felipe Lemef0823852016-06-08 13:43:08 -07001675 void writePolicyAL() {
1676 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001677
1678 FileOutputStream fos = null;
1679 try {
1680 fos = mPolicyFile.startWrite();
1681
1682 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001683 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001684 out.startDocument(null, true);
1685
1686 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001687 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001688 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001689
1690 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001691 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1692 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001693 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001694 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001695
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001696 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001697 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1698 final String subscriberId = template.getSubscriberId();
1699 if (subscriberId != null) {
1700 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001701 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001702 final String networkId = template.getNetworkId();
1703 if (networkId != null) {
1704 out.attribute(null, ATTR_NETWORK_ID, networkId);
1705 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001706 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001707 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001708 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1709 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001710 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1711 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001712 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001713 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001714 out.endTag(null, TAG_NETWORK_POLICY);
1715 }
1716
1717 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001718 for (int i = 0; i < mUidPolicy.size(); i++) {
1719 final int uid = mUidPolicy.keyAt(i);
1720 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001721
Jeff Sharkey497e4432011-06-14 17:27:29 -07001722 // skip writing empty policies
1723 if (policy == POLICY_NONE) continue;
1724
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001725 out.startTag(null, TAG_UID_POLICY);
1726 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001727 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001728 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001729 }
1730
1731 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001732
1733 // write all whitelists
1734 out.startTag(null, TAG_WHITELIST);
1735
Felipe Lemea9505cc2016-02-26 10:28:41 -08001736 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001737 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001738 for (int i = 0; i < size; i++) {
1739 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1740 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1741 writeIntAttribute(out, ATTR_UID, uid);
1742 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1743 }
1744
Felipe Lemeb85a6372016-01-14 16:16:16 -08001745 out.endTag(null, TAG_WHITELIST);
1746
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001747 out.endDocument();
1748
1749 mPolicyFile.finishWrite(fos);
1750 } catch (IOException e) {
1751 if (fos != null) {
1752 mPolicyFile.failWrite(fos);
1753 }
1754 }
1755 }
1756
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001757 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001758 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001759 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001760
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001761 if (!UserHandle.isApp(uid)) {
1762 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001763 }
Felipe Lemef0823852016-06-08 13:43:08 -07001764 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001765 final long token = Binder.clearCallingIdentity();
1766 try {
1767 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1768 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001769 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001770 }
1771 } finally {
1772 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001773 }
1774 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001775 }
1776
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001777 @Override
1778 public void addUidPolicy(int uid, int policy) {
1779 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001780
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001781 if (!UserHandle.isApp(uid)) {
1782 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1783 }
1784
Felipe Lemef0823852016-06-08 13:43:08 -07001785 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001786 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1787 policy |= oldPolicy;
1788 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001789 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001790 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001791 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001792 }
1793
1794 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001795 public void removeUidPolicy(int uid, int policy) {
1796 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1797
1798 if (!UserHandle.isApp(uid)) {
1799 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1800 }
1801
Felipe Lemef0823852016-06-08 13:43:08 -07001802 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001803 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1804 policy = oldPolicy & ~policy;
1805 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001806 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001807 }
1808 }
1809 }
1810
Felipe Lemef0823852016-06-08 13:43:08 -07001811 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1812 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001813
Felipe Leme57e3d312016-08-23 14:42:52 -07001814 final boolean notifyApp;
1815 if (!isUidValidForWhitelistRules(uid)) {
1816 notifyApp = false;
1817 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001818 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1819 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1820 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1821 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001822 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1823 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001824 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1825 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1826 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1827 if (LOGD)
1828 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1829 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1830 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001831 notifyApp = wasBlocked != isBlocked;
1832 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001833 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1834 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001835 }
1836
Felipe Lemef0823852016-06-08 13:43:08 -07001837 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001838 if (policy == POLICY_NONE) {
1839 mUidPolicy.delete(uid);
1840 } else {
1841 mUidPolicy.put(uid, policy);
1842 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001843
1844 // uid policy changed, recompute rules and persist policy.
Felipe Lemef0823852016-06-08 13:43:08 -07001845 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001846 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001847 synchronized (mNetworkPoliciesSecondLock) {
1848 writePolicyAL();
1849 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001850 }
1851 }
1852
1853 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001854 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001855 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1856
Felipe Lemef0823852016-06-08 13:43:08 -07001857 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001858 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001859 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001860 }
1861
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001862 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001863 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001864 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1865
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001866 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001867 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001868 for (int i = 0; i < mUidPolicy.size(); i++) {
1869 final int uid = mUidPolicy.keyAt(i);
1870 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001871 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1872 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001873 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001874 }
1875 }
1876 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001877 return uids;
1878 }
1879
1880 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001881 * Removes any persistable state associated with given {@link UserHandle}, persisting
1882 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001883 */
Felipe Lemef0823852016-06-08 13:43:08 -07001884 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001885
Felipe Lemef0823852016-06-08 13:43:08 -07001886 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001887 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001888
Felipe Lemea110eec2016-04-29 09:58:06 -07001889 // Remove entries from revoked default restricted background UID whitelist
1890 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1891 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1892 if (UserHandle.getUserId(uid) == userId) {
1893 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001894 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001895 }
1896 }
1897
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001898 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001899 int[] uids = new int[0];
1900 for (int i = 0; i < mUidPolicy.size(); i++) {
1901 final int uid = mUidPolicy.keyAt(i);
1902 if (UserHandle.getUserId(uid) == userId) {
1903 uids = appendInt(uids, uid);
1904 }
1905 }
1906
1907 if (uids.length > 0) {
1908 for (int uid : uids) {
1909 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001910 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001911 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001912 }
Felipe Lemef0823852016-06-08 13:43:08 -07001913 synchronized (mNetworkPoliciesSecondLock) {
1914 updateRulesForGlobalChangeAL(true);
1915 if (writePolicy && changed) {
1916 writePolicyAL();
1917 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001918 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001919 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001920 }
1921
1922 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001923 public void setConnectivityListener(INetworkPolicyListener listener) {
1924 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1925 if (mConnectivityListener != null) {
1926 throw new IllegalStateException("Connectivity listener already registered");
1927 }
1928 mConnectivityListener = listener;
1929 }
1930
1931 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001932 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001933 // TODO: create permission for observing network policy
1934 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001935 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001936 }
1937
1938 @Override
1939 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001940 // TODO: create permission for observing network policy
1941 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001942 mListeners.unregister(listener);
1943 }
1944
Jeff Sharkey1b861272011-05-22 00:34:52 -07001945 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001946 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001947 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1948
Felipe Leme6a05eee2016-02-19 14:43:51 -08001949 final long token = Binder.clearCallingIdentity();
1950 try {
1951 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001952 synchronized (mUidRulesFirstLock) {
1953 synchronized (mNetworkPoliciesSecondLock) {
1954 normalizePoliciesNL(policies);
1955 updateNetworkEnabledNL();
1956 updateNetworkRulesNL();
1957 updateNotificationsNL();
1958 writePolicyAL();
1959 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001960 }
1961 } finally {
1962 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001963 }
1964 }
1965
Felipe Lemef0823852016-06-08 13:43:08 -07001966 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001967 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001968 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1969 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001970 }
1971
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001972 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001973 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001974 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001975 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001976 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1977 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1978 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001979 } catch (SecurityException e) {
1980 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001981
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001982 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1983 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1984 return new NetworkPolicy[0];
1985 }
Svet Ganov16a16892015-04-16 10:32:04 -07001986 }
1987
Felipe Lemef0823852016-06-08 13:43:08 -07001988 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001989 final int size = mNetworkPolicy.size();
1990 final NetworkPolicy[] policies = new NetworkPolicy[size];
1991 for (int i = 0; i < size; i++) {
1992 policies[i] = mNetworkPolicy.valueAt(i);
1993 }
1994 return policies;
1995 }
1996 }
1997
Felipe Lemef0823852016-06-08 13:43:08 -07001998 private void normalizePoliciesNL() {
1999 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002000 }
2001
Felipe Lemef0823852016-06-08 13:43:08 -07002002 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002003 final TelephonyManager tele = TelephonyManager.from(mContext);
2004 final String[] merged = tele.getMergedSubscriberIds();
2005
2006 mNetworkPolicy.clear();
2007 for (NetworkPolicy policy : policies) {
2008 // When two normalized templates conflict, prefer the most
2009 // restrictive policy
2010 policy.template = NetworkTemplate.normalize(policy.template, merged);
2011 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2012 if (existing == null || existing.compareTo(policy) > 0) {
2013 if (existing != null) {
2014 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2015 }
2016 mNetworkPolicy.put(policy.template, policy);
2017 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002018 }
2019 }
2020
2021 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002022 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002023 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002024
2025 final long token = Binder.clearCallingIdentity();
2026 try {
2027 performSnooze(template, TYPE_LIMIT);
2028 } finally {
2029 Binder.restoreCallingIdentity(token);
2030 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002031 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002032
Dianne Hackborn497175b2014-07-01 12:56:08 -07002033 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002034 maybeRefreshTrustedTime();
2035 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002036 synchronized (mUidRulesFirstLock) {
2037 synchronized (mNetworkPoliciesSecondLock) {
2038 // find and snooze local policy that matches
2039 final NetworkPolicy policy = mNetworkPolicy.get(template);
2040 if (policy == null) {
2041 throw new IllegalArgumentException("unable to find policy for " + template);
2042 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002043
Felipe Lemef0823852016-06-08 13:43:08 -07002044 switch (type) {
2045 case TYPE_WARNING:
2046 policy.lastWarningSnooze = currentTime;
2047 break;
2048 case TYPE_LIMIT:
2049 policy.lastLimitSnooze = currentTime;
2050 break;
2051 default:
2052 throw new IllegalArgumentException("unexpected type");
2053 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002054
Felipe Lemef0823852016-06-08 13:43:08 -07002055 normalizePoliciesNL();
2056 updateNetworkEnabledNL();
2057 updateNetworkRulesNL();
2058 updateNotificationsNL();
2059 writePolicyAL();
2060 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002061 }
2062 }
2063
2064 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002065 public void onTetheringChanged(String iface, boolean tethering) {
2066 // No need to enforce permission because setRestrictBackground() will do it.
2067 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002068 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002069 if (mRestrictBackground && tethering) {
2070 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2071 setRestrictBackground(false);
2072 }
2073 }
2074 }
2075
2076 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002077 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002078 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002079 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002080 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2081 final long token = Binder.clearCallingIdentity();
2082 try {
2083 maybeRefreshTrustedTime();
2084 synchronized (mUidRulesFirstLock) {
2085 if (restrictBackground == mRestrictBackground) {
2086 // Ideally, UI should never allow this scenario...
2087 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2088 return;
2089 }
2090 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002091 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002092
2093 } finally {
2094 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002095 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002096
Felipe Leme29e72ea2016-09-08 13:26:55 -07002097 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2098 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002099 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002100 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002101 }
2102 }
2103
Felipe Lemef0823852016-06-08 13:43:08 -07002104 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002105 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002106 final boolean oldRestrictBackground = mRestrictBackground;
2107 mRestrictBackground = restrictBackground;
2108 // Must whitelist foreground apps before turning data saver mode on.
2109 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2110 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002111 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002112 try {
2113 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2114 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2115 mRestrictBackground = oldRestrictBackground;
2116 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002117 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002118 return;
2119 }
2120 } catch (RemoteException e) {
2121 // ignored; service lives in system_server
2122 }
Felipe Lemef0823852016-06-08 13:43:08 -07002123 synchronized (mNetworkPoliciesSecondLock) {
2124 updateNotificationsNL();
2125 writePolicyAL();
2126 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002127 }
2128
Felipe Lemeb85a6372016-01-14 16:16:16 -08002129 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002130 public int getRestrictBackgroundByCaller() {
2131 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2132 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002133
Felipe Lemef0823852016-06-08 13:43:08 -07002134 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002135 // Must clear identity because getUidPolicy() is restricted to system.
2136 final long token = Binder.clearCallingIdentity();
2137 final int policy;
2138 try {
2139 policy = getUidPolicy(uid);
2140 } finally {
2141 Binder.restoreCallingIdentity(token);
2142 }
2143 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2144 // App is blacklisted.
2145 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2146 }
Felipe Leme1b103232016-01-22 09:44:57 -08002147 if (!mRestrictBackground) {
2148 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2149 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002150 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002151 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2152 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2153 }
2154 }
2155
2156 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002157 public boolean getRestrictBackground() {
2158 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2159
Felipe Lemef0823852016-06-08 13:43:08 -07002160 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002161 return mRestrictBackground;
2162 }
2163 }
2164
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002165 @Override
2166 public void setDeviceIdleMode(boolean enabled) {
2167 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002168 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2169 try {
2170 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002171 if (mDeviceIdleMode == enabled) {
2172 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002173 }
Felipe Lemeea014392016-09-06 13:59:54 -07002174 mDeviceIdleMode = enabled;
2175 if (mSystemReady) {
2176 // Device idle change means we need to rebuild rules for all
2177 // known apps, so do a global refresh.
2178 updateRulesForRestrictPowerUL();
2179 }
2180 }
2181 if (enabled) {
2182 EventLogTags.writeDeviceIdleOnPhase("net");
2183 } else {
2184 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002185 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002186 } finally {
2187 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002188 }
2189 }
2190
Felipe Lemef0823852016-06-08 13:43:08 -07002191 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002192 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2193 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002194 if (policy.template.matches(ident)) {
2195 return policy;
2196 }
2197 }
2198 return null;
2199 }
2200
2201 @Override
2202 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2203 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2204
2205 // only returns usage summary, so we don't require caller to have
2206 // READ_NETWORK_USAGE_HISTORY.
2207 final long token = Binder.clearCallingIdentity();
2208 try {
2209 return getNetworkQuotaInfoUnchecked(state);
2210 } finally {
2211 Binder.restoreCallingIdentity(token);
2212 }
2213 }
2214
2215 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2216 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2217
2218 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002219 synchronized (mNetworkPoliciesSecondLock) {
2220 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002221 }
2222
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002223 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002224 // missing policy means we can't derive useful quota info
2225 return null;
2226 }
2227
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002228 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002229
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002230 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002231 final long start = computeLastCycleBoundary(currentTime, policy);
2232 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002233 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002234
2235 // report soft and hard limits under policy
2236 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2237 : NetworkQuotaInfo.NO_LIMIT;
2238 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2239 : NetworkQuotaInfo.NO_LIMIT;
2240
2241 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2242 }
2243
Jeff Sharkey46645002011-07-27 21:11:21 -07002244 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002245 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002246 if (state.networkInfo == null) {
2247 return false;
2248 }
2249
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002250 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2251
2252 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002253 synchronized (mNetworkPoliciesSecondLock) {
2254 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002255 }
2256
2257 if (policy != null) {
2258 return policy.metered;
2259 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002260 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002261 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002262 return true;
2263 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002264 return false;
2265 }
2266 }
2267
2268 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002269 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002270 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002271
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002272 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2273
Dianne Hackborn497175b2014-07-01 12:56:08 -07002274 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002275 for (String arg : args) {
2276 argSet.add(arg);
2277 }
2278
Felipe Lemef0823852016-06-08 13:43:08 -07002279 synchronized (mUidRulesFirstLock) {
2280 synchronized (mNetworkPoliciesSecondLock) {
2281 if (argSet.contains("--unsnooze")) {
2282 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2283 mNetworkPolicy.valueAt(i).clearSnooze();
2284 }
2285
2286 normalizePoliciesNL();
2287 updateNetworkEnabledNL();
2288 updateNetworkRulesNL();
2289 updateNotificationsNL();
2290 writePolicyAL();
2291
2292 fout.println("Cleared snooze timestamps");
2293 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002294 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002295
Felipe Lemef0823852016-06-08 13:43:08 -07002296 fout.print("System ready: "); fout.println(mSystemReady);
2297 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2298 fout.print("Restrict power: "); fout.println(mRestrictPower);
2299 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2300 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002301 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002302 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2303 fout.println(mNetworkPolicy.valueAt(i).toString());
2304 }
2305 fout.decreaseIndent();
2306
2307 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2308
2309 fout.println("Policy for UIDs:");
2310 fout.increaseIndent();
2311 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002312 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002313 final int uid = mUidPolicy.keyAt(i);
2314 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002315 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002316 fout.print(uid);
2317 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002318 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002319 fout.println();
2320 }
2321 fout.decreaseIndent();
2322
2323 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2324 if (size > 0) {
2325 fout.println("Power save whitelist (except idle) app ids:");
2326 fout.increaseIndent();
2327 for (int i = 0; i < size; i++) {
2328 fout.print("UID=");
2329 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2330 fout.print(": ");
2331 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2332 fout.println();
2333 }
2334 fout.decreaseIndent();
2335 }
2336
2337 size = mPowerSaveWhitelistAppIds.size();
2338 if (size > 0) {
2339 fout.println("Power save whitelist app ids:");
2340 fout.increaseIndent();
2341 for (int i = 0; i < size; i++) {
2342 fout.print("UID=");
2343 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2344 fout.print(": ");
2345 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2346 fout.println();
2347 }
2348 fout.decreaseIndent();
2349 }
2350
Felipe Lemef0823852016-06-08 13:43:08 -07002351 size = mDefaultRestrictBackgroundWhitelistUids.size();
2352 if (size > 0) {
2353 fout.println("Default restrict background whitelist uids:");
2354 fout.increaseIndent();
2355 for (int i = 0; i < size; i++) {
2356 fout.print("UID=");
2357 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2358 fout.println();
2359 }
2360 fout.decreaseIndent();
2361 }
2362
2363 size = mRestrictBackgroundWhitelistRevokedUids.size();
2364 if (size > 0) {
2365 fout.println("Default restrict background whitelist uids revoked by users:");
2366 fout.increaseIndent();
2367 for (int i = 0; i < size; i++) {
2368 fout.print("UID=");
2369 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2370 fout.println();
2371 }
2372 fout.decreaseIndent();
2373 }
2374
2375 final SparseBooleanArray knownUids = new SparseBooleanArray();
2376 collectKeys(mUidState, knownUids);
2377 collectKeys(mUidRules, knownUids);
2378
2379 fout.println("Status for all known UIDs:");
2380 fout.increaseIndent();
2381 size = knownUids.size();
2382 for (int i = 0; i < size; i++) {
2383 final int uid = knownUids.keyAt(i);
2384 fout.print("UID=");
2385 fout.print(uid);
2386
2387 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2388 fout.print(" state=");
2389 fout.print(state);
2390 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2391 fout.print(" (fg)");
2392 } else {
2393 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2394 ? " (fg svc)" : " (bg)");
2395 }
2396
2397 final int uidRules = mUidRules.get(uid, RULE_NONE);
2398 fout.print(" rules=");
2399 fout.print(uidRulesToString(uidRules));
2400 fout.println();
2401 }
2402 fout.decreaseIndent();
2403
2404 fout.println("Status for just UIDs with rules:");
2405 fout.increaseIndent();
2406 size = mUidRules.size();
2407 for (int i = 0; i < size; i++) {
2408 final int uid = mUidRules.keyAt(i);
2409 fout.print("UID=");
2410 fout.print(uid);
2411 final int uidRules = mUidRules.get(uid, RULE_NONE);
2412 fout.print(" rules=");
2413 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002414 fout.println();
2415 }
2416 fout.decreaseIndent();
2417 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002418 }
2419 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002420
2421 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002422 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002423 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002424 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002425 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002426 }
2427
2428 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002429 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002430 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2431
Felipe Lemef0823852016-06-08 13:43:08 -07002432 synchronized (mUidRulesFirstLock) {
2433 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002434 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002435 }
2436
Felipe Lemef0823852016-06-08 13:43:08 -07002437 private boolean isUidForegroundUL(int uid) {
2438 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002439 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2440 }
2441
Felipe Lemef0823852016-06-08 13:43:08 -07002442 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002443 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Felipe Lemef0823852016-06-08 13:43:08 -07002444 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002445 }
2446
Felipe Lemef0823852016-06-08 13:43:08 -07002447 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002448 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2449 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2450 }
2451
Felipe Lemef0823852016-06-08 13:43:08 -07002452 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002453 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002454 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002455 }
2456
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002457 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002458 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002459 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2460 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002461 */
Felipe Lemef0823852016-06-08 13:43:08 -07002462 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002463 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2464 try {
2465 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2466 if (oldUidState != uidState) {
2467 // state changed, push updated rules
2468 mUidState.put(uid, uidState);
2469 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2470 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2471 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2472 if (isUidIdle(uid)) {
2473 updateRuleForAppIdleUL(uid);
2474 }
2475 if (mDeviceIdleMode) {
2476 updateRuleForDeviceIdleUL(uid);
2477 }
2478 if (mRestrictPower) {
2479 updateRuleForRestrictPowerUL(uid);
2480 }
2481 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002482 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002483 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002484 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002485 } finally {
2486 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002487 }
2488 }
2489
Felipe Lemef0823852016-06-08 13:43:08 -07002490 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002491 final int index = mUidState.indexOfKey(uid);
2492 if (index >= 0) {
2493 final int oldUidState = mUidState.valueAt(index);
2494 mUidState.removeAt(index);
2495 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002496 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002497 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002498 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002499 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002500 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002501 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002502 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002503 }
Felipe Lemef0823852016-06-08 13:43:08 -07002504 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002505 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002506 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002507 }
2508 }
2509
Felipe Lemef28983d2016-03-25 12:18:23 -07002510 // adjust stats accounting based on foreground status
2511 private void updateNetworkStats(int uid, boolean uidForeground) {
2512 try {
2513 mNetworkStats.setUidForeground(uid, uidForeground);
2514 } catch (RemoteException e) {
2515 // ignored; service lives in system_server
2516 }
2517 }
2518
Felipe Lemef0823852016-06-08 13:43:08 -07002519 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
Felipe Lemef28983d2016-03-25 12:18:23 -07002520 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002521 final boolean oldForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002522 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002523 final boolean newForeground =
Felipe Lemef0823852016-06-08 13:43:08 -07002524 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002525 if (oldForeground != newForeground) {
Felipe Lemef0823852016-06-08 13:43:08 -07002526 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002527 }
2528 }
2529
Felipe Leme011b98f2016-02-10 17:28:31 -08002530 static boolean isProcStateAllowedWhileIdleOrPowerSaveMode(int procState) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002531 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2532 }
2533
Felipe Lemef0823852016-06-08 13:43:08 -07002534 static boolean isProcStateAllowedWhileOnRestrictBackground(int procState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002535 return procState <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE;
2536 }
2537
Felipe Lemef0823852016-06-08 13:43:08 -07002538 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002539 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2540 try {
2541 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2542 mUidFirewallPowerSaveRules);
2543 } finally {
2544 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2545 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002546 }
2547
Felipe Lemef0823852016-06-08 13:43:08 -07002548 void updateRuleForRestrictPowerUL(int uid) {
2549 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002550 }
2551
Felipe Lemef0823852016-06-08 13:43:08 -07002552 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002553 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2554 try {
2555 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2556 mUidFirewallDozableRules);
2557 } finally {
2558 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2559 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002560 }
2561
Felipe Lemef0823852016-06-08 13:43:08 -07002562 void updateRuleForDeviceIdleUL(int uid) {
2563 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002564 }
2565
Felipe Lemef28983d2016-03-25 12:18:23 -07002566 // NOTE: since both fw_dozable and fw_powersave uses the same map
2567 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002568 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002569 SparseIntArray rules) {
2570 if (enabled) {
2571 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002572 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002573 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002574 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002575 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002576 for (int ui = users.size() - 1; ui >= 0; ui--) {
2577 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002578 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002579 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2580 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2581 int uid = UserHandle.getUid(user.id, appId);
2582 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2583 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002584 }
2585 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2586 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2587 int uid = UserHandle.getUid(user.id, appId);
2588 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2589 }
2590 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002591 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002592 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002593 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2594 }
2595 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002596 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2597 } else {
2598 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002599 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002600 }
2601
Felipe Lemef0823852016-06-08 13:43:08 -07002602 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002603 final int appId = UserHandle.getAppId(uid);
2604 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2605 }
2606
Felipe Lemef28983d2016-03-25 12:18:23 -07002607 // NOTE: since both fw_dozable and fw_powersave uses the same map
2608 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002609 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002610 if (enabled) {
Felipe Lemef0823852016-06-08 13:43:08 -07002611 if (isWhitelistedBatterySaverUL(uid)
Felipe Leme011b98f2016-02-10 17:28:31 -08002612 || isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.get(uid))) {
2613 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002614 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002615 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002616 }
2617 }
2618 }
2619
Felipe Lemef0823852016-06-08 13:43:08 -07002620 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002621 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2622 try {
2623 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2624 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002625
Felipe Leme873a83a2016-09-07 11:34:10 -07002626 // Fully update the app idle firewall chain.
2627 final List<UserInfo> users = mUserManager.getUsers();
2628 for (int ui = users.size() - 1; ui >= 0; ui--) {
2629 UserInfo user = users.get(ui);
2630 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2631 for (int uid : idleUids) {
2632 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2633 // quick check: if this uid doesn't have INTERNET permission, it
2634 // doesn't have network access anyway, so it is a waste to mess
2635 // with it here.
2636 if (hasInternetPermissions(uid)) {
2637 uidRules.put(uid, FIREWALL_RULE_DENY);
2638 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002639 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002640 }
2641 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002642
Felipe Lemebc853dd2016-09-08 13:26:55 -07002643 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002644 } finally {
2645 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2646 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002647 }
2648
Felipe Lemef0823852016-06-08 13:43:08 -07002649 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002650 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002651
2652 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002653 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002654 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002655 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2656 } else {
2657 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2658 }
2659 }
2660
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002661 /**
2662 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2663 * changed.
2664 */
Felipe Lemef0823852016-06-08 13:43:08 -07002665 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002666 boolean paroled = mUsageStats.isAppIdleParoleOn();
2667 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002668 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002669
2670 int ruleCount = mUidFirewallStandbyRules.size();
2671 for (int i = 0; i < ruleCount; i++) {
2672 int uid = mUidFirewallStandbyRules.keyAt(i);
2673 int oldRules = mUidRules.get(uid);
2674 if (enableChain) {
2675 // Chain wasn't enabled before and the other power-related
2676 // chains are whitelists, so we can clear the
2677 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2678 // the effective rules result in blocking network access.
2679 oldRules &= MASK_METERED_NETWORKS;
2680 } else {
2681 // Skip if it had no restrictions to begin with
2682 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2683 }
2684 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
2685 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002686 }
2687
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002688 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002689 * Update rules that might be changed by {@link #mRestrictBackground},
2690 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002691 */
Felipe Lemef0823852016-06-08 13:43:08 -07002692 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002693 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2694 try {
Felipe Leme09700462016-09-08 09:33:48 -07002695 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002696 updateRulesForRestrictPowerUL();
2697 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002698
Felipe Leme873a83a2016-09-07 11:34:10 -07002699 // If the set of restricted networks may have changed, re-evaluate those.
2700 if (restrictedNetworksChanged) {
2701 normalizePoliciesNL();
2702 updateNetworkRulesNL();
2703 }
2704 } finally {
2705 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002706 }
2707 }
2708
Felipe Leme09700462016-09-08 09:33:48 -07002709 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002710 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002711 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2712 try {
2713 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002714 updateRulesForPowerSaveUL();
2715 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2716 } finally {
2717 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2718 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002719 }
2720
Felipe Lemef0823852016-06-08 13:43:08 -07002721 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002722 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2723 try {
2724 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2725 } finally {
2726 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2727 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002728 }
2729
2730 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2731 private static final int TYPE_RESTRICT_POWER = 2;
2732 @Retention(RetentionPolicy.SOURCE)
2733 @IntDef(flag = false, value = {
2734 TYPE_RESTRICT_BACKGROUND,
2735 TYPE_RESTRICT_POWER,
2736 })
2737 public @interface RestrictType {
2738 }
2739
2740 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002741 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002742 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2743 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2744 }
2745 try {
2746 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002747
Felipe Leme873a83a2016-09-07 11:34:10 -07002748 // update rules for all installed applications
2749 final List<UserInfo> users = mUserManager.getUsers();
2750 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002751 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
Felipe Leme873a83a2016-09-07 11:34:10 -07002752 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2753 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002754
Felipe Leme873a83a2016-09-07 11:34:10 -07002755 final int usersSize = users.size();
2756 final int appsSize = apps.size();
2757 for (int i = 0; i < usersSize; i++) {
2758 final UserInfo user = users.get(i);
2759 for (int j = 0; j < appsSize; j++) {
2760 final ApplicationInfo app = apps.get(j);
2761 final int uid = UserHandle.getUid(user.id, app.uid);
2762 switch (type) {
2763 case TYPE_RESTRICT_BACKGROUND:
2764 updateRulesForDataUsageRestrictionsUL(uid);
2765 break;
2766 case TYPE_RESTRICT_POWER:
2767 updateRulesForPowerRestrictionsUL(uid);
2768 break;
2769 default:
2770 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2771 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002772 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002773 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002774 } finally {
2775 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2776 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2777 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002778 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002779 }
2780
Felipe Lemef0823852016-06-08 13:43:08 -07002781 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002782 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002783 for (int i = 0; i < users.size(); i++) {
2784 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002785 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002786 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002787 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002788 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002789 updateRuleForAppIdleUL(uid);
2790 updateRuleForDeviceIdleUL(uid);
2791 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002792 // Update internal rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002793 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002794 }
2795 }
2796 }
2797
Felipe Leme70c57c22016-03-29 10:45:13 -07002798 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2799 // methods below could be merged into a isUidValidForRules() method.
2800 private boolean isUidValidForBlacklistRules(int uid) {
2801 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002802 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002803 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002804 return true;
2805 }
2806
2807 return false;
2808 }
2809
Felipe Leme70c57c22016-03-29 10:45:13 -07002810 private boolean isUidValidForWhitelistRules(int uid) {
2811 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2812 }
2813
Amith Yamasani15e472352015-04-24 19:06:07 -07002814 private boolean isUidIdle(int uid) {
2815 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2816 final int userId = UserHandle.getUserId(uid);
2817
songjinshi0655edd2016-05-18 19:55:32 +08002818 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002819 for (String packageName : packages) {
2820 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2821 return false;
2822 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002823 }
2824 }
2825 return true;
2826 }
2827
2828 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002829 * Checks if an uid has INTERNET permissions.
2830 * <p>
2831 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002832 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002833 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002834 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002835 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002836 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002837 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002838 }
2839 } catch (RemoteException e) {
2840 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002841 return true;
2842 }
2843
2844 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002845 * Clears all state - internal and external - associated with an UID.
2846 */
2847 private void onUidDeletedUL(int uid) {
2848 // First cleanup in-memory state synchronously...
2849 mUidRules.delete(uid);
2850 mUidPolicy.delete(uid);
2851 mUidFirewallStandbyRules.delete(uid);
2852 mUidFirewallDozableRules.delete(uid);
2853 mUidFirewallPowerSaveRules.delete(uid);
2854 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2855 mPowerSaveWhitelistAppIds.delete(uid);
2856 mPowerSaveTempWhitelistAppIds.delete(uid);
2857
2858 // ...then update iptables asynchronously.
2859 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2860 }
2861
2862 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002863 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002864 *
Felipe Leme781ba142016-05-09 16:24:48 -07002865 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002866 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002867 * <li>Doze mode
2868 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002869 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002870 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002871 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002872 *
2873 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002874 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002875 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002876 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002877 updateRuleForDeviceIdleUL(uid);
2878 updateRuleForAppIdleUL(uid);
2879 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002880
2881 // Update internal state for power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002882 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002883
2884 // Update firewall and internal rules for Data Saver Mode.
Felipe Leme03e95e22016-09-09 09:25:31 -07002885 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002886 }
2887
Felipe Leme70c57c22016-03-29 10:45:13 -07002888 /**
2889 * Applies network rules to bandwidth controllers based on process state and user-defined
2890 * restrictions (blacklist / whitelist).
2891 *
2892 * <p>
2893 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2894 * networks:
2895 * <ul>
2896 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2897 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2898 * also blacklisted.
2899 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2900 * no UIDs other those whitelisted will have access.
2901 * <ul>
2902 *
2903 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2904 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2905 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2906 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002907 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002908 * {@link INetworkManagementService}, but this method should also be called in events (like
2909 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2910 * following rules should also be applied:
2911 *
2912 * <ul>
2913 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2914 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2915 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2916 * {@code bw_penalty_box}.
2917 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2918 * </ul>
2919 *
2920 * <p>For optimization, the rules are only applied on user apps that have internet access
2921 * permission, since there is no need to change the {@code iptables} rule if the app does not
2922 * have permission to use the internet.
2923 *
2924 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002925 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002926 */
Felipe Lemef0823852016-06-08 13:43:08 -07002927 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07002928 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002929 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
2930 return;
2931 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002932
Dianne Hackborn497175b2014-07-01 12:56:08 -07002933 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002934 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002935 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002936
Felipe Leme781ba142016-05-09 16:24:48 -07002937 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002938 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002939 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2940 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002941
Felipe Leme70c57c22016-03-29 10:45:13 -07002942 // First step: define the new rule based on user restrictions and foreground state.
2943 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002944 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2945 newRule = RULE_TEMPORARY_ALLOW_METERED;
2946 } else if (isWhitelisted) {
2947 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002948 }
2949 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002950 if (isBlacklisted) {
2951 newRule = RULE_REJECT_METERED;
2952 } else if (mRestrictBackground && isWhitelisted) {
2953 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002954 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002955 }
Felipe Leme781ba142016-05-09 16:24:48 -07002956 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002957
Felipe Lemef28983d2016-03-25 12:18:23 -07002958 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002959 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002960 + ": isForeground=" +isForeground
2961 + ", isBlacklisted=" + isBlacklisted
2962 + ", isWhitelisted=" + isWhitelisted
2963 + ", oldRule=" + uidRulesToString(oldRule)
2964 + ", newRule=" + uidRulesToString(newRule)
2965 + ", newUidRules=" + uidRulesToString(newUidRules)
2966 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002967 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002968
Felipe Leme46c4fc32016-05-04 09:21:43 -07002969 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002970 mUidRules.delete(uid);
2971 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002972 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002973 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002974
Felipe Leme70c57c22016-03-29 10:45:13 -07002975 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002976 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002977 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002978 // Temporarily whitelist foreground app, removing from blacklist if necessary
2979 // (since bw_penalty_box prevails over bw_happy_box).
2980
2981 setMeteredNetworkWhitelist(uid, true);
2982 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2983 // but ideally it should be just:
2984 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002985 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002986 setMeteredNetworkBlacklist(uid, false);
2987 }
Felipe Leme781ba142016-05-09 16:24:48 -07002988 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002989 // Remove temporary whitelist from app that is not on foreground anymore.
2990
2991 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2992 // but ideally they should be just:
2993 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2994 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002995 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002996 setMeteredNetworkWhitelist(uid, false);
2997 }
Felipe Leme781ba142016-05-09 16:24:48 -07002998 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002999 setMeteredNetworkBlacklist(uid, true);
3000 }
Felipe Leme781ba142016-05-09 16:24:48 -07003001 } else if ((newRule & RULE_REJECT_METERED) != 0
3002 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003003 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003004 setMeteredNetworkBlacklist(uid, isBlacklisted);
3005 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003006 // Since blacklist prevails over whitelist, we need to handle the special case
3007 // where app is whitelisted and blacklisted at the same time (although such
3008 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003009 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003010 }
Felipe Leme781ba142016-05-09 16:24:48 -07003011 } else if ((newRule & RULE_ALLOW_METERED) != 0
3012 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003013 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003014 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003015 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003016 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003017 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3018 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003019 + ", whitelisted=" + isWhitelisted
3020 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003021 + ", newRule=" + uidRulesToString(newUidRules)
3022 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003023 }
Felipe Leme781ba142016-05-09 16:24:48 -07003024
3025 // Dispatch changed rule to existing listeners.
3026 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
3027 }
3028 }
3029
3030 /**
3031 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3032 * listeners in case of change.
3033 * <p>
3034 * There are 3 power-related rules that affects whether an app has background access on
3035 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3036 * restriction, it's added to the equivalent firewall chain:
3037 * <ul>
3038 * <li>App is idle: {@code fw_standby} firewall chain.
3039 * <li>Device is idle: {@code fw_dozable} firewall chain.
3040 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3041 * </ul>
3042 * <p>
3043 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3044 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3045 * <p>
3046 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3047 */
Felipe Lemef0823852016-06-08 13:43:08 -07003048 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003049 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3050
3051 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
3052
3053 if (newUidRules == RULE_NONE) {
3054 mUidRules.delete(uid);
3055 } else {
3056 mUidRules.put(uid, newUidRules);
3057 }
3058 }
3059
3060 /**
3061 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3062 *
3063 * @param uid the uid of the app to update rules for
3064 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3065 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3066 *
3067 * @return the new computed rules for the uid
3068 */
3069 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003070 if (!isUidValidForBlacklistRules(uid)) {
3071 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003072 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003073 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003074
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003075 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003076 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003077 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003078
Felipe Lemef0823852016-06-08 13:43:08 -07003079 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003080 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3081 int newRule = RULE_NONE;
3082
3083 // First step: define the new rule based on user restrictions and foreground state.
3084
3085 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3086 // by considering the foreground and non-foreground states.
3087 if (isForeground) {
3088 if (restrictMode) {
3089 newRule = RULE_ALLOW_ALL;
3090 }
3091 } else if (restrictMode) {
3092 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3093 }
3094
3095 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3096
3097 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003098 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003099 + ", isIdle: " + isIdle
3100 + ", mRestrictPower: " + mRestrictPower
3101 + ", mDeviceIdleMode: " + mDeviceIdleMode
3102 + ", isForeground=" + isForeground
3103 + ", isWhitelisted=" + isWhitelisted
3104 + ", oldRule=" + uidRulesToString(oldRule)
3105 + ", newRule=" + uidRulesToString(newRule)
3106 + ", newUidRules=" + uidRulesToString(newUidRules)
3107 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3108 }
3109
Felipe Leme781ba142016-05-09 16:24:48 -07003110 // Second step: notify listeners if state changed.
3111 if (newRule != oldRule) {
3112 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003113 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003114 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003115 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3116 } else {
3117 // All scenarios should have been covered above
3118 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3119 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003120 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003121 + ", newRule=" + uidRulesToString(newUidRules)
3122 + ", oldRule=" + uidRulesToString(oldUidRules));
3123 }
Felipe Leme46c4fc32016-05-04 09:21:43 -07003124 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003125 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003126
3127 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003128 }
3129
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003130 private class AppIdleStateChangeListener
3131 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3132
3133 @Override
3134 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3135 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003136 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3137 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003138 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003139 synchronized (mUidRulesFirstLock) {
3140 updateRuleForAppIdleUL(uid);
3141 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003142 }
3143 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003144 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003145 }
3146
3147 @Override
3148 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003149 synchronized (mUidRulesFirstLock) {
3150 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003151 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003152 }
3153 }
3154
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003155 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3156 if (listener != null) {
3157 try {
3158 listener.onUidRulesChanged(uid, uidRules);
3159 } catch (RemoteException ignored) {
3160 }
3161 }
3162 }
3163
3164 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3165 String[] meteredIfaces) {
3166 if (listener != null) {
3167 try {
3168 listener.onMeteredIfacesChanged(meteredIfaces);
3169 } catch (RemoteException ignored) {
3170 }
3171 }
3172 }
3173
3174 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3175 boolean restrictBackground) {
3176 if (listener != null) {
3177 try {
3178 listener.onRestrictBackgroundChanged(restrictBackground);
3179 } catch (RemoteException ignored) {
3180 }
3181 }
3182 }
3183
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003184 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3185 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003186 if (listener != null) {
3187 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003188 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003189 } 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 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003256 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003257 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003258 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003259 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003260 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003261 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003262 final int length = mListeners.beginBroadcast();
3263 for (int i = 0; i < length; i++) {
3264 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003265 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003266 }
3267 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003268 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3269 if (notifyApp.booleanValue()) {
3270 broadcastRestrictBackgroundChanged(uid, notifyApp);
3271 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003272 return true;
3273 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003274 case MSG_ADVISE_PERSIST_THRESHOLD: {
3275 final long lowestRule = (Long) msg.obj;
3276 try {
3277 // make sure stats are recorded frequently enough; we aim
3278 // for 2MB threshold for 2GB/month rules.
3279 final long persistThreshold = lowestRule / 1000;
3280 mNetworkStats.advisePersistThreshold(persistThreshold);
3281 } catch (RemoteException e) {
3282 // ignored; service lives in system_server
3283 }
3284 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003285 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003286 case MSG_UPDATE_INTERFACE_QUOTA: {
3287 removeInterfaceQuota((String) msg.obj);
3288 // int params need to be stitched back into a long
3289 setInterfaceQuota((String) msg.obj,
3290 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3291 return true;
3292 }
3293 case MSG_REMOVE_INTERFACE_QUOTA: {
3294 removeInterfaceQuota((String) msg.obj);
3295 return true;
3296 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003297 case MSG_SET_FIREWALL_RULES: {
3298 final int chain = msg.arg1;
3299 final int toggle = msg.arg2;
3300 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3301 if (uidRules != null) {
3302 setUidFirewallRules(chain, uidRules);
3303 }
3304 if (toggle != CHAIN_TOGGLE_NONE) {
3305 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3306 }
3307 return true;
3308 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003309 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3310 resetUidFirewallRules(msg.arg1);
3311 return true;
3312 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003313 default: {
3314 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003315 }
3316 }
3317 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003318
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003319 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003320
Felipe Leme57e3d312016-08-23 14:42:52 -07003321 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3322 final PackageManager pm = mContext.getPackageManager();
3323 final String[] packages = pm.getPackagesForUid(uid);
3324 if (packages != null) {
3325 final int userId = UserHandle.getUserId(uid);
3326 for (String packageName : packages) {
3327 final Intent intent =
3328 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3329 intent.setPackage(packageName);
3330 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3331 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3332 }
3333 }
3334 }
3335
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003336 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003337 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003338 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003339 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003340 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003341 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003342 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003343 }
3344 }
3345
3346 private void removeInterfaceQuota(String iface) {
3347 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003348 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003349 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003350 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003351 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003352 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003353 }
3354 }
3355
Felipe Leme70c57c22016-03-29 10:45:13 -07003356 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3357 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003358 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003359 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003360 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003361 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3362 } catch (RemoteException e) {
3363 // ignored; service lives in system_server
3364 }
3365 }
3366
3367 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3368 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3369 try {
3370 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3371 } catch (IllegalStateException e) {
3372 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003373 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003374 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003375 }
3376 }
3377
Felipe Lemebc853dd2016-09-08 13:26:55 -07003378 private static final int CHAIN_TOGGLE_NONE = 0;
3379 private static final int CHAIN_TOGGLE_ENABLE = 1;
3380 private static final int CHAIN_TOGGLE_DISABLE = 2;
3381 @Retention(RetentionPolicy.SOURCE)
3382 @IntDef(flag = false, value = {
3383 CHAIN_TOGGLE_NONE,
3384 CHAIN_TOGGLE_ENABLE,
3385 CHAIN_TOGGLE_DISABLE
3386 })
3387 public @interface ChainToggleType {
3388 }
3389
3390 /**
3391 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3392 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3393 *
3394 * @param chain firewall chain.
3395 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3396 * @param toggle whether the chain should be enabled, disabled, or not changed.
3397 */
3398 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3399 @ChainToggleType int toggle) {
3400 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3401 }
3402
Amith Yamasani15e472352015-04-24 19:06:07 -07003403 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003404 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3405 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3406 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003407 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003408 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003409 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003410 int size = uidRules.size();
3411 int[] uids = new int[size];
3412 int[] rules = new int[size];
3413 for(int index = size - 1; index >= 0; --index) {
3414 uids[index] = uidRules.keyAt(index);
3415 rules[index] = uidRules.valueAt(index);
3416 }
3417 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003418 } catch (IllegalStateException e) {
3419 Log.wtf(TAG, "problem setting firewall uid rules", e);
3420 } catch (RemoteException e) {
3421 // ignored; service lives in system_server
3422 }
3423 }
3424
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003425 /**
3426 * Add or remove a uid to the firewall blacklist for all network ifaces.
3427 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003428 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003429 if (chain == FIREWALL_CHAIN_DOZABLE) {
3430 mUidFirewallDozableRules.put(uid, rule);
3431 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3432 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003433 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3434 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003435 }
3436
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003437 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003438 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003439 } catch (IllegalStateException e) {
3440 Log.wtf(TAG, "problem setting firewall uid rules", e);
3441 } catch (RemoteException e) {
3442 // ignored; service lives in system_server
3443 }
3444 }
3445
3446 /**
3447 * Add or remove a uid to the firewall blacklist for all network ifaces.
3448 */
Felipe Lemef0823852016-06-08 13:43:08 -07003449 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003450 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3451 mFirewallChainStates.get(chain) == enable) {
3452 // All is the same, nothing to do.
3453 return;
3454 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003455 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003456 try {
3457 mNetworkManager.setFirewallChainEnabled(chain, enable);
3458 } catch (IllegalStateException e) {
3459 Log.wtf(TAG, "problem enable firewall chain", e);
3460 } catch (RemoteException e) {
3461 // ignored; service lives in system_server
3462 }
3463 }
3464
Felipe Leme03e95e22016-09-09 09:25:31 -07003465 /**
3466 * Resets all firewall rules associated with an UID.
3467 */
3468 private void resetUidFirewallRules(int uid) {
3469 try {
3470 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3471 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3472 mNetworkManager
3473 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3474 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3475 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3476 } catch (IllegalStateException e) {
3477 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3478 } catch (RemoteException e) {
3479 // ignored; service lives in system_server
3480 }
3481 }
3482
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003483 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3484 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003485 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003486 } catch (RuntimeException e) {
3487 Slog.w(TAG, "problem reading network stats: " + e);
3488 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003489 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003490 // ignored; service lives in system_server
3491 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003492 }
3493 }
3494
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003495 private boolean isBandwidthControlEnabled() {
3496 final long token = Binder.clearCallingIdentity();
3497 try {
3498 return mNetworkManager.isBandwidthControlEnabled();
3499 } catch (RemoteException e) {
3500 // ignored; service lives in system_server
3501 return false;
3502 } finally {
3503 Binder.restoreCallingIdentity(token);
3504 }
3505 }
3506
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003507 /**
3508 * Try refreshing {@link #mTime} when stale.
3509 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003510 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003511 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003512 mTime.forceRefresh();
3513 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003514 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003515
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003516 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003517 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3518 }
3519
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003520 private static Intent buildAllowBackgroundDataIntent() {
3521 return new Intent(ACTION_ALLOW_BACKGROUND);
3522 }
3523
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003524 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3525 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3526 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3527 return intent;
3528 }
3529
Wei Liu546cb772016-07-21 16:19:01 -07003530 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003531 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003532 intent.setComponent(ComponentName.unflattenFromString(
3533 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003534 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3535 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3536 return intent;
3537 }
3538
Wei Liu546cb772016-07-21 16:19:01 -07003539 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003540 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003541 intent.setComponent(ComponentName.unflattenFromString(
3542 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003543 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3544 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3545 return intent;
3546 }
3547
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003548 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003549 public void addIdleHandler(IdleHandler handler) {
3550 mHandler.getLooper().getQueue().addIdleHandler(handler);
3551 }
3552
Jeff Sharkey1b861272011-05-22 00:34:52 -07003553 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3554 final int size = source.size();
3555 for (int i = 0; i < size; i++) {
3556 target.put(source.keyAt(i), true);
3557 }
3558 }
3559
Stuart Scottf1fb3972015-04-02 18:00:02 -07003560 @Override
3561 public void factoryReset(String subscriber) {
3562 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3563
Stuart Scotte3e314d2015-04-20 14:07:45 -07003564 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3565 return;
3566 }
3567
Stuart Scottf1fb3972015-04-02 18:00:02 -07003568 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003569 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003570 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3571 for (NetworkPolicy policy : policies) {
3572 if (policy.template.equals(template)) {
3573 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3574 policy.inferred = false;
3575 policy.clearSnooze();
3576 }
3577 }
3578 setNetworkPolicies(policies);
3579
3580 // Turn restrict background data off
3581 setRestrictBackground(false);
3582
Stuart Scotte3e314d2015-04-20 14:07:45 -07003583 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3584 // Remove app's "restrict background data" flag
3585 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3586 setUidPolicy(uid, POLICY_NONE);
3587 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003588 }
3589 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003590
Felipe Lemed17fda42016-04-29 11:12:45 -07003591 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3592
3593 @Override
3594 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003595 synchronized (mUidRulesFirstLock) {
3596 boolean changed = removeUserStateUL(userId, false);
3597 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003598 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003599 synchronized (mNetworkPoliciesSecondLock) {
3600 writePolicyAL();
3601 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003602 }
3603 }
3604 }
3605 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003606}