blob: 4e9d838e7c4547d6d9b5115ca9cedefc81cc53f9 [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;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080061import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
62import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Felipe Lemeb146f762016-08-19 09:52:16 -070063import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070064import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
66import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070067import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
68import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070069import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080070import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070071import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
72import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
73import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
74import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
75import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
76import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
77import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070078import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080079
Jeff Sharkey854b2b12012-04-13 16:03:40 -070080import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070081import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070082import static com.android.internal.util.XmlUtils.readBooleanAttribute;
83import static com.android.internal.util.XmlUtils.readIntAttribute;
84import static com.android.internal.util.XmlUtils.readLongAttribute;
85import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
86import static com.android.internal.util.XmlUtils.writeIntAttribute;
87import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070088import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070089import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060090
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080092import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070094
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070096import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070097import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070098import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070099import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700100import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700101import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700102import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700103import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700104import android.app.Notification;
105import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700106import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700108import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700109import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.content.Intent;
111import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700112import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700113import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700114import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700115import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700116import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700117import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700120import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700121import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700122import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700123import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700124import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700126import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700128import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700130import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700131import android.net.wifi.WifiConfiguration;
132import android.net.wifi.WifiInfo;
133import android.net.wifi.WifiManager;
jackqdyulei455e90a2017-02-09 15:29:16 -0800134import android.os.PowerSaveState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700135import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.os.Environment;
137import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700138import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700140import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700141import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700142import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700144import android.os.PowerManagerInternal;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800145import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700146import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700147import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600148import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700149import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700150import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700151import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700152import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700153import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700154import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800155import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700156import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400157import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700158import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700159import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700160import android.util.ArrayMap;
161import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700162import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700163import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700165import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700166import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700167import android.util.SparseBooleanArray;
168import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700169import android.util.TrustedTime;
170import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700171
Jeff Sharkey497e4432011-06-14 17:27:29 -0700172import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700173import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800174import com.android.internal.annotations.VisibleForTesting;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500175import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey32566012014-12-02 18:30:14 -0800176import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700178import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700179import com.android.server.DeviceIdleController;
180import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700181import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800182import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600183
jackqdyulei455e90a2017-02-09 15:29:16 -0800184import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600185import libcore.io.IoUtils;
186
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700187import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188
189import org.xmlpull.v1.XmlPullParser;
190import org.xmlpull.v1.XmlPullParserException;
191import org.xmlpull.v1.XmlSerializer;
192
193import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700194import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195import java.io.FileInputStream;
196import java.io.FileNotFoundException;
197import java.io.FileOutputStream;
198import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700199import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700200import java.lang.annotation.Retention;
201import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100202import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700203import java.util.ArrayList;
204import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700205import java.util.List;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800206import java.util.concurrent.CountDownLatch;
207import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700209/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700210 * Service that maintains low-level network policy rules, using
211 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700212 * <p>
213 * Derives active rules by combining a given policy with other system status,
214 * and delivers to listeners, such as {@link ConnectivityManager}, for
215 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700216 *
217 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000218 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700219 * <ul>
220 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
221 * rules).
222 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
223 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000224 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
225 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700226 * </ul>
227 *
228 * <p>
229 * As such, methods that require synchronization have the following prefixes:
230 * <ul>
231 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
232 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000233 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
234 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700235 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700236 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700237public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800238 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700239 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700240 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700241
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700242 private static final int VERSION_INIT = 1;
243 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700244 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800245 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800246 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800247 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700248 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700249 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700250 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700251 private static final int VERSION_SWITCH_UID = 10;
252 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800254 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700255 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800256 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800258 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700259 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700260
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700261 private static final String TAG_POLICY_LIST = "policy-list";
262 private static final String TAG_NETWORK_POLICY = "network-policy";
263 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700264 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800265 private static final String TAG_WHITELIST = "whitelist";
266 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800267 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
269 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700270 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700271 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
272 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700273 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800275 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276 private static final String ATTR_WARNING_BYTES = "warningBytes";
277 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700278 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800279 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
280 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800281 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700282 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700284 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700285 private static final String ATTR_POLICY = "policy";
286
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800287 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800288 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800289 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800290 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700291
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700292 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
293
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700294 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700295 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800296 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800297 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700298 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700299 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
300 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700301 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700302 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700303 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700304
Jeff Sharkey75279902011-05-24 18:39:45 -0700305 private final Context mContext;
306 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700307 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700308 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700309 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700311 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700312
313 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700314 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700315 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700316 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700317
Felipe Lemef0823852016-06-08 13:43:08 -0700318 // See main javadoc for instructions on how to use these locks.
319 final Object mUidRulesFirstLock = new Object();
320 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700321
Felipe Lemef0823852016-06-08 13:43:08 -0700322 @GuardedBy("allLocks") volatile boolean mSystemReady;
323
Felipe Lemef0823852016-06-08 13:43:08 -0700324 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
325 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
326 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700327
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700328 private final boolean mSuppressDefaultPolicy;
329
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800331 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700332 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800333 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700334
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700335 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700337 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700338 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700339
Felipe Lemef0823852016-06-08 13:43:08 -0700340 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700341 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700342 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700343 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700344 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800345 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700346
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700347 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700348 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700349 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
350
Jeff Sharkey32566012014-12-02 18:30:14 -0800351 /**
352 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700353 * in power save mode, except device idle (doze) still applies.
354 * TODO: An int array might be sufficient
355 */
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700357 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
358
359 /**
360 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800361 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700362 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800363 */
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700365 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700366
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700368 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
369
Felipe Lemeb85a6372016-01-14 16:16:16 -0800370 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800371 * UIDs that have been initially white-listed by system to avoid restricted background.
372 */
Felipe Lemef0823852016-06-08 13:43:08 -0700373 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800374 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
375 new SparseBooleanArray();
376
377 /**
378 * UIDs that have been initially white-listed by system to avoid restricted background,
379 * but later revoked by user.
380 */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800382 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
383 new SparseBooleanArray();
384
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700385 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800387 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700388 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800390 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700391
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700392 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700393 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700394 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700395
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700396 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700397 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800398 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700399
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600400 /** Higher priority listener before general event dispatch */
401 private INetworkPolicyListener mConnectivityListener;
402
Jeff Sharkey32566012014-12-02 18:30:14 -0800403 private final RemoteCallbackList<INetworkPolicyListener>
404 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700405
Dianne Hackborn497175b2014-07-01 12:56:08 -0700406 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407
Felipe Lemef0823852016-06-08 13:43:08 -0700408 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700409 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700410
Svet Ganov16a16892015-04-16 10:32:04 -0700411 private final AppOpsManager mAppOps;
412
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800413 private final IPackageManager mIPm;
414
Felipe Lemeb85a6372016-01-14 16:16:16 -0800415
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700416 // TODO: keep whitelist of system-critical services that should never have
417 // rules enforced, such as system, phone, and radio UIDs.
418
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 // TODO: migrate notifications to SystemUI
420
Jeff Sharkey75279902011-05-24 18:39:45 -0700421 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700422 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
423 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700424 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
425 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700426 }
427
428 private static File getSystemDir() {
429 return new File(Environment.getDataDirectory(), "system");
430 }
431
432 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700433 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700434 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700435 mContext = checkNotNull(context, "missing context");
436 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700437 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700438 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700439 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700440 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700441 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700442 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700443 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700444
Amith Yamasani450a16b2013-09-18 16:28:50 -0700445 HandlerThread thread = new HandlerThread(TAG);
446 thread.start();
447 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700448
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700449 mSuppressDefaultPolicy = suppressDefaultPolicy;
450
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700451 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700452
453 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800454
Felipe Lemed17fda42016-04-29 11:12:45 -0700455 // Expose private service for system components to use.
456 LocalServices.addService(NetworkPolicyManagerInternal.class,
457 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700458 }
459
460 public void bindConnectivityManager(IConnectivityManager connManager) {
461 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700462 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700463
Jeff Sharkey497e4432011-06-14 17:27:29 -0700464 public void bindNotificationManager(INotificationManager notifManager) {
465 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
466 }
467
Felipe Lemef0823852016-06-08 13:43:08 -0700468 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700469 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700470 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
471 mPowerSaveWhitelistExceptIdleAppIds.clear();
472 if (whitelist != null) {
473 for (int uid : whitelist) {
474 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
475 }
476 }
477 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700478 mPowerSaveWhitelistAppIds.clear();
479 if (whitelist != null) {
480 for (int uid : whitelist) {
481 mPowerSaveWhitelistAppIds.put(uid, true);
482 }
483 }
484 } catch (RemoteException e) {
485 }
486 }
487
Felipe Lemea9505cc2016-02-26 10:28:41 -0800488 /**
489 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
490 * revoke the whitelist.
491 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700492 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800493 */
Felipe Lemef0823852016-06-08 13:43:08 -0700494 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800495 final List<UserInfo> users = mUserManager.getUsers();
496 final int numberUsers = users.size();
497
Felipe Lemea110eec2016-04-29 09:58:06 -0700498 boolean changed = false;
499 for (int i = 0; i < numberUsers; i++) {
500 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700501 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700502 }
503 return changed;
504 }
505
Felipe Lemef0823852016-06-08 13:43:08 -0700506 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700507 final SystemConfig sysConfig = SystemConfig.getInstance();
508 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800509 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
510 boolean changed = false;
511 for (int i = 0; i < allowDataUsage.size(); i++) {
512 final String pkg = allowDataUsage.valueAt(i);
513 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700514 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
515 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800516 final ApplicationInfo app;
517 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700518 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800519 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700520 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
521 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800522 continue;
523 }
524 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700525 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
526 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800527 continue;
528 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700529 final int uid = UserHandle.getUid(userId, app.uid);
530 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
531 if (LOGD)
532 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
533 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800534 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700535 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700536 if (LOGD)
537 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
538 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700539 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700540 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800541 }
542 }
543 return changed;
544 }
545
Felipe Lemef0823852016-06-08 13:43:08 -0700546 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700547 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700548 // Clear the states of the current whitelist
549 final int N = mPowerSaveTempWhitelistAppIds.size();
550 for (int i = 0; i < N; i++) {
551 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
552 }
553 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700554 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700555 if (whitelist != null) {
556 for (int uid : whitelist) {
557 mPowerSaveTempWhitelistAppIds.put(uid, true);
558 }
559 }
560 } catch (RemoteException e) {
561 }
562 }
563
Amith Yamasani06f08062015-06-12 13:23:33 -0700564 /**
565 * Remove unnecessary entries in the temp whitelist
566 */
Felipe Lemef0823852016-06-08 13:43:08 -0700567 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700568 final int N = mPowerSaveTempWhitelistAppIds.size();
569 for (int i = N - 1; i >= 0; i--) {
570 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
571 mPowerSaveTempWhitelistAppIds.removeAt(i);
572 }
573 }
574 }
575
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800576 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700577 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800578 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700579 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800580 // Boost thread's priority during system server init
581 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700582 if (!isBandwidthControlEnabled()) {
583 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
584 return;
585 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700586
Felipe Leme873a83a2016-09-07 11:34:10 -0700587 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700588
Felipe Leme873a83a2016-09-07 11:34:10 -0700589 synchronized (mUidRulesFirstLock) {
590 synchronized (mNetworkPoliciesSecondLock) {
591 updatePowerSaveWhitelistUL();
592 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
593 mPowerManagerInternal.registerLowPowerModeObserver(
594 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800595 @Override
596 public int getServiceType() {
597 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700598 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800599
600 @Override
601 public void onLowPowerModeChanged(PowerSaveState result) {
602 final boolean enabled = result.batterySaverEnabled;
603 if (LOGD) Slog.d(TAG,
604 "onLowPowerModeChanged(" + enabled + ")");
605 synchronized (mUidRulesFirstLock) {
606 if (mRestrictPower != enabled) {
607 mRestrictPower = enabled;
608 updateRulesForRestrictPowerUL();
609 }
610 }
611 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700612 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800613 mRestrictPower = mPowerManagerInternal.getLowPowerState(
614 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700615
616 mSystemReady = true;
617
618 // read policy from disk
619 readPolicyAL();
620
621 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
622 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700623 }
Felipe Lemef0823852016-06-08 13:43:08 -0700624
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 setRestrictBackgroundUL(mRestrictBackground);
626 updateRulesForGlobalChangeAL(false);
627 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700628 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800629 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700630
631 try {
632 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000633 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800634 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700635 mNetworkManager.registerObserver(mAlertObserver);
636 } catch (RemoteException e) {
637 // ignored; both services live in system_server
638 }
639
640 // listen for changes to power save whitelist
641 final IntentFilter whitelistFilter = new IntentFilter(
642 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
643 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
644
645 DeviceIdleController.LocalService deviceIdleService
646 = LocalServices.getService(DeviceIdleController.LocalService.class);
647 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
648
649 // watch for network interfaces to be claimed
650 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
651 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
652
653 // listen for package changes to update policy
654 final IntentFilter packageFilter = new IntentFilter();
655 packageFilter.addAction(ACTION_PACKAGE_ADDED);
656 packageFilter.addDataScheme("package");
657 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
658
659 // listen for UID changes to update policy
660 mContext.registerReceiver(
661 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
662
663 // listen for user changes to update policy
664 final IntentFilter userFilter = new IntentFilter();
665 userFilter.addAction(ACTION_USER_ADDED);
666 userFilter.addAction(ACTION_USER_REMOVED);
667 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
668
669 // listen for stats update events
670 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
671 mContext.registerReceiver(
672 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
673
674 // listen for restrict background changes from notifications
675 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
676 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
677
678 // listen for snooze warning from notifications
679 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
680 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
681 MANAGE_NETWORK_POLICY, mHandler);
682
683 // listen for configured wifi networks to be removed
684 final IntentFilter wifiConfigFilter =
685 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
686 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
687
688 // listen for wifi state changes to catch metered hint
689 final IntentFilter wifiStateFilter = new IntentFilter(
690 WifiManager.NETWORK_STATE_CHANGED_ACTION);
691 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
692
693 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800694 // tell systemReady() that the service has been initialized
695 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700696 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800697 // Restore the default priority after init is done
698 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700699 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700700 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700701 }
702
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800703 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
704 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
705 mHandler.post(() -> initService(initCompleteSignal));
706 return initCompleteSignal;
707 }
708
709 public void systemReady(CountDownLatch initCompleteSignal) {
710 // wait for initService to complete
711 try {
712 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
713 throw new IllegalStateException("Service " + TAG +" init timeout");
714 }
715 } catch (InterruptedException e) {
716 Thread.currentThread().interrupt();
717 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
718 }
719 }
720
Sudheer Shankac9d94072017-02-22 22:13:55 +0000721 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
722 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
724 try {
725 synchronized (mUidRulesFirstLock) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000726 updateUidStateUL(uid, procState);
Felipe Leme873a83a2016-09-07 11:34:10 -0700727 }
728 } finally {
729 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700730 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700731 }
732
Dianne Hackborne07641d2016-11-09 15:07:23 -0800733 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700734 synchronized (mUidRulesFirstLock) {
735 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700736 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700737 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700738
739 @Override public void onUidActive(int uid) throws RemoteException {
740 }
741
Dianne Hackborne07641d2016-11-09 15:07:23 -0800742 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700743 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700744 };
745
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700746 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700747 @Override
748 public void onReceive(Context context, Intent intent) {
749 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700750 synchronized (mUidRulesFirstLock) {
751 updatePowerSaveWhitelistUL();
752 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700753 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700754 }
755 }
756 };
757
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700758 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
759 @Override
760 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700761 synchronized (mUidRulesFirstLock) {
762 updatePowerSaveTempWhitelistUL();
763 updateRulesForTempWhitelistChangeUL();
764 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700765 }
766 }
767 };
768
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700769 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700770 @Override
771 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700772 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700773
774 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700775 final int uid = intent.getIntExtra(EXTRA_UID, -1);
776 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700777
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700778 if (ACTION_PACKAGE_ADDED.equals(action)) {
779 // update rules for UID, since it might be subject to
780 // global background data policy
781 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700782 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700783 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700784 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700785 }
786 }
787 };
788
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700789 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700790 @Override
791 public void onReceive(Context context, Intent intent) {
792 // on background handler thread, and UID_REMOVED is protected
793
794 final int uid = intent.getIntExtra(EXTRA_UID, -1);
795 if (uid == -1) return;
796
797 // remove any policy and update rules to clean up
798 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700799 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700800 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700801 synchronized (mNetworkPoliciesSecondLock) {
802 writePolicyAL();
803 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700804 }
805 }
806 };
807
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700808 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700809 @Override
810 public void onReceive(Context context, Intent intent) {
811 // on background handler thread, and USER_ADDED and USER_REMOVED
812 // broadcasts are protected
813
814 final String action = intent.getAction();
815 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
816 if (userId == -1) return;
817
Amith Yamasani15e472352015-04-24 19:06:07 -0700818 switch (action) {
819 case ACTION_USER_REMOVED:
820 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700821 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800822 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700823 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700824 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700825 if (action == ACTION_USER_ADDED) {
826 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700827 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700828 }
829 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700830 synchronized (mNetworkPoliciesSecondLock) {
831 updateRulesForGlobalChangeAL(true);
832 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700833 }
834 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700835 }
836 }
837 };
838
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700839 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700840 * Receiver that watches for {@link INetworkStatsService} updates, which we
841 * use to check against {@link NetworkPolicy#warningBytes}.
842 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700843 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700844 @Override
845 public void onReceive(Context context, Intent intent) {
846 // on background handler thread, and verified
847 // READ_NETWORK_USAGE_HISTORY permission above.
848
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800849 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700850 synchronized (mNetworkPoliciesSecondLock) {
851 updateNetworkEnabledNL();
852 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700853 }
854 }
855 };
856
857 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700858 * Receiver that watches for {@link Notification} control of
859 * {@link #mRestrictBackground}.
860 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700861 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700862 @Override
863 public void onReceive(Context context, Intent intent) {
864 // on background handler thread, and verified MANAGE_NETWORK_POLICY
865 // permission above.
866
867 setRestrictBackground(false);
868 }
869 };
870
871 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800872 * Receiver that watches for {@link Notification} control of
873 * {@link NetworkPolicy#lastWarningSnooze}.
874 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700875 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800876 @Override
877 public void onReceive(Context context, Intent intent) {
878 // on background handler thread, and verified MANAGE_NETWORK_POLICY
879 // permission above.
880
881 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
882 performSnooze(template, TYPE_WARNING);
883 }
884 };
885
886 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700887 * Receiver that watches for {@link WifiConfiguration} to be changed.
888 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700889 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700890 @Override
891 public void onReceive(Context context, Intent intent) {
892 // on background handler thread, and verified CONNECTIVITY_INTERNAL
893 // permission above.
894
895 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
896 if (reason == CHANGE_REASON_REMOVED) {
897 final WifiConfiguration config = intent.getParcelableExtra(
898 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700899 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800900 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700901 synchronized (mUidRulesFirstLock) {
902 synchronized (mNetworkPoliciesSecondLock) {
903 if (mNetworkPolicy.containsKey(template)) {
904 mNetworkPolicy.remove(template);
905 writePolicyAL();
906 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700907 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700908 }
909 }
910 }
911 }
912 };
913
914 /**
915 * Receiver that watches {@link WifiInfo} state changes to infer metered
916 * state. Ignores hints when policy is user-defined.
917 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700918 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700919 @Override
920 public void onReceive(Context context, Intent intent) {
921 // on background handler thread, and verified CONNECTIVITY_INTERNAL
922 // permission above.
923
924 // ignore when not connected
925 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
926 if (!netInfo.isConnected()) return;
927
928 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
929 final boolean meteredHint = info.getMeteredHint();
930
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800931 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700932 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700933 NetworkPolicy policy = mNetworkPolicy.get(template);
934 if (policy == null && meteredHint) {
935 // policy doesn't exist, and AP is hinting that it's
936 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800937 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700938 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700939
940 } else if (policy != null && policy.inferred) {
941 // policy exists, and was inferred: update its current
942 // metered state.
943 policy.metered = meteredHint;
944
945 // since this is inferred for each wifi session, just update
946 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700947 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700948 }
949 }
950 }
951 };
952
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800953 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
954 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
955 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
956 metered, true);
957 }
958
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700959 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700960 * Observer that watches for {@link INetworkManagementService} alerts.
961 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private INetworkManagementEventObserver mAlertObserver
963 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700964 @Override
965 public void limitReached(String limitName, String iface) {
966 // only someone like NMS should be calling us
967 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
968
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800969 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
970 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700971 }
972 }
973 };
974
975 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700976 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
977 * to show visible notifications as needed.
978 */
Felipe Lemef0823852016-06-08 13:43:08 -0700979 void updateNotificationsNL() {
980 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700981
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700982 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700983 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700984 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700985
986 // TODO: when switching to kernel notifications, compute next future
987 // cycle boundary to recompute notifications.
988
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700989 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800990 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700991 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
992 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700993 // ignore policies that aren't relevant to user
994 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700995 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996
Jeff Sharkey497e4432011-06-14 17:27:29 -0700997 final long start = computeLastCycleBoundary(currentTime, policy);
998 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001000
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001001 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001002 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001003 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1004 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001005 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001006 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001007 }
1008
Jeff Sharkey497e4432011-06-14 17:27:29 -07001009 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001010 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001011
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001012 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001013 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001014 }
1015 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001016 }
1017
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001018 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001019 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
1020 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021 if (!mActiveNotifs.contains(tag)) {
1022 cancelNotification(tag);
1023 }
1024 }
1025 }
1026
1027 /**
1028 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001029 * current device state, such as when
1030 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1031 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001032 */
1033 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001034 if (template.isMatchRuleMobile()) {
1035 final TelephonyManager tele = TelephonyManager.from(mContext);
1036 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001037
Jeff Sharkey32566012014-12-02 18:30:14 -08001038 // Mobile template is relevant when any active subscriber matches
1039 final int[] subIds = sub.getActiveSubscriptionIdList();
1040 for (int subId : subIds) {
1041 final String subscriberId = tele.getSubscriberId(subId);
1042 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001043 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001044 if (template.matches(probeIdent)) {
1045 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001046 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001047 }
1048 return false;
1049 } else {
1050 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001051 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001052 }
1053
1054 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001055 * Notify that given {@link NetworkTemplate} is over
1056 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1057 */
Felipe Lemef0823852016-06-08 13:43:08 -07001058 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001059 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001060 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001061 mOverLimitNotified.add(template);
1062 }
1063 }
1064
Felipe Lemef0823852016-06-08 13:43:08 -07001065 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 mOverLimitNotified.remove(template);
1067 }
1068
1069 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001070 * Build unique tag that identifies an active {@link NetworkPolicy}
1071 * notification of a specific type, like {@link #TYPE_LIMIT}.
1072 */
1073 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001074 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 }
1076
1077 /**
1078 * Show notification for combined {@link NetworkPolicy} and specific type,
1079 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1080 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082 final String tag = buildNotificationTag(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001083 final Notification.Builder builder =
1084 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001086 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001087 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001088 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089
1090 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001091 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001092 switch (type) {
1093 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001094 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001095 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001097 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001098 builder.setTicker(title);
1099 builder.setContentTitle(title);
1100 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001101 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001102 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001103
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001104 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1105 builder.setDeleteIntent(PendingIntent.getBroadcast(
1106 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1107
Wei Liu546cb772016-07-21 16:19:01 -07001108 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001109 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001110 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1111
Jeff Sharkey497e4432011-06-14 17:27:29 -07001112 break;
1113 }
1114 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001115 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001116
1117 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001118 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001119 switch (policy.template.getMatchRule()) {
1120 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001121 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001123 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001124 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001125 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001126 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001127 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001128 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 case MATCH_WIFI:
1130 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001131 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001132 break;
1133 default:
1134 title = null;
1135 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001136 }
1137
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001138 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001139 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001140 builder.setTicker(title);
1141 builder.setContentTitle(title);
1142 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001143
Wei Liu546cb772016-07-21 16:19:01 -07001144 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 builder.setContentIntent(PendingIntent.getActivity(
1146 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1147 break;
1148 }
1149 case TYPE_LIMIT_SNOOZED: {
1150 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001151 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 Formatter.formatFileSize(mContext, overBytes));
1153
1154 final CharSequence title;
1155 switch (policy.template.getMatchRule()) {
1156 case MATCH_MOBILE_3G_LOWER:
1157 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1158 break;
1159 case MATCH_MOBILE_4G:
1160 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1161 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001162 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001163 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1164 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001165 case MATCH_WIFI:
1166 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1167 break;
1168 default:
1169 title = null;
1170 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001171 }
1172
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001173 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001174 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001175 builder.setTicker(title);
1176 builder.setContentTitle(title);
1177 builder.setContentText(body);
1178
Wei Liu546cb772016-07-21 16:19:01 -07001179 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001180 builder.setContentIntent(PendingIntent.getActivity(
1181 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001182 break;
1183 }
1184 }
1185
1186 // TODO: move to NotificationManager once we can mock it
1187 try {
1188 final String packageName = mContext.getPackageName();
1189 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001190 if(!TextUtils.isEmpty(body)) {
1191 builder.setStyle(new Notification.BigTextStyle()
1192 .bigText(body));
1193 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001194 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001195 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001196 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001197 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001198 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001199 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001200 }
1201 }
1202
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001203 private void cancelNotification(String tag) {
1204 // TODO: move to NotificationManager once we can mock it
1205 try {
1206 final String packageName = mContext.getPackageName();
1207 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001208 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001209 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001210 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001211 }
1212 }
1213
1214 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001215 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001216 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001217 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001218 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219 @Override
1220 public void onReceive(Context context, Intent intent) {
1221 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1222 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001223
1224 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001225 synchronized (mNetworkPoliciesSecondLock) {
1226 ensureActiveMobilePolicyNL();
1227 normalizePoliciesNL();
1228 updateNetworkEnabledNL();
1229 updateNetworkRulesNL();
1230 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001231 }
1232 }
1233 };
1234
1235 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001236 * Proactively control network data connections when they exceed
1237 * {@link NetworkPolicy#limitBytes}.
1238 */
Felipe Lemef0823852016-06-08 13:43:08 -07001239 void updateNetworkEnabledNL() {
1240 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001241
1242 // TODO: reset any policy-disabled networks when any policy is removed
1243 // completely, which is currently rare case.
1244
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001245 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001246 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1247 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001248 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001249 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001250 setNetworkTemplateEnabled(policy.template, true);
1251 continue;
1252 }
1253
1254 final long start = computeLastCycleBoundary(currentTime, policy);
1255 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001256 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001257
1258 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001259 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1260 && policy.lastLimitSnooze < start;
1261 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001262
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001263 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001264 }
1265 }
1266
1267 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001268 * Proactively disable networks that match the given
1269 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001270 */
1271 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001272 // TODO: reach into ConnectivityManager to proactively disable bringing
1273 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001274
1275 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1276 // If mobile data usage hits the limit or if the user resumes the data, we need to
1277 // notify telephony.
1278 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1279 final TelephonyManager tm = TelephonyManager.from(mContext);
1280
1281 final int[] subIds = sm.getActiveSubscriptionIdList();
1282 for (int subId : subIds) {
1283 final String subscriberId = tm.getSubscriberId(subId);
1284 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1285 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1286 // Template is matched when subscriber id matches.
1287 if (template.matches(probeIdent)) {
1288 tm.setPolicyDataEnabled(enabled, subId);
1289 }
1290 }
1291 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001292 }
1293
1294 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001295 * Examine all connected {@link NetworkState}, looking for
1296 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1297 * remaining quota based on usage cycle and historical stats.
1298 */
Felipe Lemef0823852016-06-08 13:43:08 -07001299 void updateNetworkRulesNL() {
1300 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001301
1302 final NetworkState[] states;
1303 try {
1304 states = mConnManager.getAllNetworkState();
1305 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001306 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001307 return;
1308 }
1309
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001310 // First, generate identities of all connected networks so we can
1311 // quickly compare them against all defined policies below.
1312 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001313 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001314 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001315 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001316 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001317
1318 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001319 if (baseIface != null) {
1320 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001321 }
1322
1323 // Stacked interfaces are considered to have same identity as
1324 // their parent network.
1325 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1326 for (LinkProperties stackedLink : stackedLinks) {
1327 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001328 if (stackedIface != null) {
1329 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001330 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001331 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 }
1333 }
1334
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001335 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001336 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001337 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001338 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001339 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001340
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001341 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001342 for (int j = connIdents.size() - 1; j >= 0; j--) {
1343 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1344 if (policy.template.matches(ident.second)) {
1345 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001346 }
1347 }
1348
1349 if (ifaceList.size() > 0) {
1350 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001351 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001352 }
1353 }
1354
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001355 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001356 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001357
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001358 // apply each policy that we found ifaces for; compute remaining data
1359 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001360 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001361 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1362 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1363 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001364
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001365 final long start;
1366 final long totalBytes;
1367 if (policy.hasCycle()) {
1368 start = computeLastCycleBoundary(currentTime, policy);
1369 totalBytes = getTotalBytes(policy.template, start, currentTime);
1370 } else {
1371 start = Long.MAX_VALUE;
1372 totalBytes = 0;
1373 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001374
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001375 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001376 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001377 }
1378
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001379 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001380 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001381 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001382 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001383 if (!hasLimit) {
1384 // metered network, but no policy limit; we still need to
1385 // restrict apps, so push really high quota.
1386 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001387 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001388 // snoozing past quota, but we still need to restrict apps,
1389 // so push really high quota.
1390 quotaBytes = Long.MAX_VALUE;
1391 } else {
1392 // remaining "quota" bytes are based on total usage in
1393 // current cycle. kernel doesn't like 0-byte rules, so we
1394 // set 1-byte quota and disable the radio later.
1395 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1396 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001397
1398 if (ifaces.length > 1) {
1399 // TODO: switch to shared quota once NMS supports
1400 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001401 }
1402
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001403 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001404 // long quotaBytes split up into two ints to fit in message
1405 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1406 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1407 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001408 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001409 }
1410 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001411
1412 // keep track of lowest warning or limit of active policies
1413 if (hasWarning && policy.warningBytes < lowestRule) {
1414 lowestRule = policy.warningBytes;
1415 }
1416 if (hasLimit && policy.limitBytes < lowestRule) {
1417 lowestRule = policy.limitBytes;
1418 }
1419 }
1420
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001421 for (int i = connIfaces.size()-1; i >= 0; i--) {
1422 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001423 // long quotaBytes split up into two ints to fit in message
1424 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1425 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1426 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001427 newMeteredIfaces.add(iface);
1428 }
1429
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001430 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001431
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001432 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001433 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1434 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001435 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001436 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1437 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001438 }
1439 }
1440 mMeteredIfaces = newMeteredIfaces;
1441
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001442 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001443 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001444 }
1445
1446 /**
1447 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1448 * have at least a default mobile policy defined.
1449 */
Felipe Lemef0823852016-06-08 13:43:08 -07001450 private void ensureActiveMobilePolicyNL() {
1451 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001452 if (mSuppressDefaultPolicy) return;
1453
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001454 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001456
Jeff Sharkey32566012014-12-02 18:30:14 -08001457 final int[] subIds = sub.getActiveSubscriptionIdList();
1458 for (int subId : subIds) {
1459 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001460 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001461 }
1462 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001463
Felipe Lemef0823852016-06-08 13:43:08 -07001464 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001465 // Poke around to see if we already have a policy
1466 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001467 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001468 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1469 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1470 if (template.matches(probeIdent)) {
1471 if (LOGD) {
1472 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1473 + NetworkIdentity.scrubSubscriberId(subscriberId));
1474 }
1475 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001476 }
1477 }
1478
Jeff Sharkey32566012014-12-02 18:30:14 -08001479 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1480 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001481
Jeff Sharkey32566012014-12-02 18:30:14 -08001482 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001483 final int dataWarningConfig = mContext.getResources().getInteger(
1484 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1485 final long warningBytes;
1486 if (dataWarningConfig == WARNING_DISABLED) {
1487 warningBytes = WARNING_DISABLED;
1488 } else {
1489 warningBytes = dataWarningConfig * MB_IN_BYTES;
1490 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001491
Jeff Sharkey32566012014-12-02 18:30:14 -08001492 final Time time = new Time();
1493 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001494
Jeff Sharkey32566012014-12-02 18:30:14 -08001495 final int cycleDay = time.monthDay;
1496 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001497
Jeff Sharkey32566012014-12-02 18:30:14 -08001498 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1499 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1500 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001501 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001502 }
1503
Felipe Lemef0823852016-06-08 13:43:08 -07001504 private void readPolicyAL() {
1505 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506
1507 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001508 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001509 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510
1511 FileInputStream fis = null;
1512 try {
1513 fis = mPolicyFile.openRead();
1514 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001515 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516
Felipe Leme46b451f2016-08-19 08:46:17 -07001517 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1518 // to skip UIDs that were explicitly blacklisted.
1519 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1520
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001521 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001522 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001523 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001524 while ((type = in.next()) != END_DOCUMENT) {
1525 final String tag = in.getName();
1526 if (type == START_TAG) {
1527 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001528 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001529 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001530 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1531 mRestrictBackground = readBooleanAttribute(
1532 in, ATTR_RESTRICT_BACKGROUND);
1533 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001534 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001535 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001536 if (mRestrictBackground != oldValue) {
1537 // Some early services may have read the default value,
1538 // so notify them that it's changed
1539 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1540 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1541 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542
1543 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1544 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1545 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001546 final String networkId;
1547 if (version >= VERSION_ADDED_NETWORK_ID) {
1548 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1549 } else {
1550 networkId = null;
1551 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001552 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001553 final String cycleTimezone;
1554 if (version >= VERSION_ADDED_TIMEZONE) {
1555 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1556 } else {
1557 cycleTimezone = Time.TIMEZONE_UTC;
1558 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001559 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1560 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001561 final long lastLimitSnooze;
1562 if (version >= VERSION_SPLIT_SNOOZE) {
1563 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1564 } else if (version >= VERSION_ADDED_SNOOZE) {
1565 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001566 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001567 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001568 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001569 final boolean metered;
1570 if (version >= VERSION_ADDED_METERED) {
1571 metered = readBooleanAttribute(in, ATTR_METERED);
1572 } else {
1573 switch (networkTemplate) {
1574 case MATCH_MOBILE_3G_LOWER:
1575 case MATCH_MOBILE_4G:
1576 case MATCH_MOBILE_ALL:
1577 metered = true;
1578 break;
1579 default:
1580 metered = false;
1581 }
1582 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001583 final long lastWarningSnooze;
1584 if (version >= VERSION_SPLIT_SNOOZE) {
1585 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1586 } else {
1587 lastWarningSnooze = SNOOZE_NEVER;
1588 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001589 final boolean inferred;
1590 if (version >= VERSION_ADDED_INFERRED) {
1591 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1592 } else {
1593 inferred = false;
1594 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001595
Jeff Sharkey32566012014-12-02 18:30:14 -08001596 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1597 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001598 if (template.isPersistable()) {
1599 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1600 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1601 lastLimitSnooze, metered, inferred));
1602 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001603
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001604 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001605 final int uid = readIntAttribute(in, ATTR_UID);
1606 final int policy = readIntAttribute(in, ATTR_POLICY);
1607
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001608 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001609 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001610 } else {
1611 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1612 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001613 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001614 final int appId = readIntAttribute(in, ATTR_APP_ID);
1615 final int policy = readIntAttribute(in, ATTR_POLICY);
1616
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001617 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001618 // app policy is deprecated so this is only used in pre system user split.
1619 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001620 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001621 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001622 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001623 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001624 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001625 } else if (TAG_WHITELIST.equals(tag)) {
1626 insideWhitelist = true;
1627 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1628 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001629 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001630 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1631 final int uid = readIntAttribute(in, ATTR_UID);
1632 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001633 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001634 } else if (type == END_TAG) {
1635 if (TAG_WHITELIST.equals(tag)) {
1636 insideWhitelist = false;
1637 }
1638
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001639 }
1640 }
1641
Felipe Leme46b451f2016-08-19 08:46:17 -07001642 final int size = whitelistedRestrictBackground.size();
1643 for (int i = 0; i < size; i++) {
1644 final int uid = whitelistedRestrictBackground.keyAt(i);
1645 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1646 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1647 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1648 + " because its policy is " + uidPoliciesToString(policy));
1649 continue;
1650 }
1651 if (UserHandle.isApp(uid)) {
1652 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1653 if (LOGV)
1654 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1655 setUidPolicyUncheckedUL(uid, newPolicy, false);
1656 } else {
1657 Slog.w(TAG, "unable to update policy on UID " + uid);
1658 }
1659 }
1660
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001661 } catch (FileNotFoundException e) {
1662 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001663 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001664 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001665 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001666 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001667 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001668 } finally {
1669 IoUtils.closeQuietly(fis);
1670 }
1671 }
1672
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001673 /**
1674 * Upgrade legacy background data flags, notifying listeners of one last
1675 * change to always-true.
1676 */
Felipe Lemef0823852016-06-08 13:43:08 -07001677 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001678 mRestrictBackground = Settings.Secure.getInt(
1679 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1680
1681 // kick off one last broadcast if restricted
1682 if (mRestrictBackground) {
1683 final Intent broadcast = new Intent(
1684 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001685 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001686 }
1687 }
1688
Felipe Lemef0823852016-06-08 13:43:08 -07001689 void writePolicyAL() {
1690 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001691
1692 FileOutputStream fos = null;
1693 try {
1694 fos = mPolicyFile.startWrite();
1695
1696 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001697 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001698 out.startDocument(null, true);
1699
1700 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001701 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001702 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001703
1704 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001705 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1706 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001707 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001708 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001709
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001710 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001711 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1712 final String subscriberId = template.getSubscriberId();
1713 if (subscriberId != null) {
1714 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001715 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001716 final String networkId = template.getNetworkId();
1717 if (networkId != null) {
1718 out.attribute(null, ATTR_NETWORK_ID, networkId);
1719 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001720 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001721 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001722 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1723 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001724 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1725 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001726 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001727 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001728 out.endTag(null, TAG_NETWORK_POLICY);
1729 }
1730
1731 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001732 for (int i = 0; i < mUidPolicy.size(); i++) {
1733 final int uid = mUidPolicy.keyAt(i);
1734 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001735
Jeff Sharkey497e4432011-06-14 17:27:29 -07001736 // skip writing empty policies
1737 if (policy == POLICY_NONE) continue;
1738
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001739 out.startTag(null, TAG_UID_POLICY);
1740 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001741 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001742 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001743 }
1744
1745 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001746
1747 // write all whitelists
1748 out.startTag(null, TAG_WHITELIST);
1749
Felipe Lemea9505cc2016-02-26 10:28:41 -08001750 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001751 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001752 for (int i = 0; i < size; i++) {
1753 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1754 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1755 writeIntAttribute(out, ATTR_UID, uid);
1756 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1757 }
1758
Felipe Lemeb85a6372016-01-14 16:16:16 -08001759 out.endTag(null, TAG_WHITELIST);
1760
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001761 out.endDocument();
1762
1763 mPolicyFile.finishWrite(fos);
1764 } catch (IOException e) {
1765 if (fos != null) {
1766 mPolicyFile.failWrite(fos);
1767 }
1768 }
1769 }
1770
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001771 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001772 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001773 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001774
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001775 if (!UserHandle.isApp(uid)) {
1776 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001777 }
Felipe Lemef0823852016-06-08 13:43:08 -07001778 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001779 final long token = Binder.clearCallingIdentity();
1780 try {
1781 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1782 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001783 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001784 }
1785 } finally {
1786 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001787 }
1788 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001789 }
1790
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001791 @Override
1792 public void addUidPolicy(int uid, int policy) {
1793 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001794
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001795 if (!UserHandle.isApp(uid)) {
1796 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1797 }
1798
Felipe Lemef0823852016-06-08 13:43:08 -07001799 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001800 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1801 policy |= oldPolicy;
1802 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001803 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001804 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001805 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001806 }
1807
1808 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001809 public void removeUidPolicy(int uid, int policy) {
1810 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1811
1812 if (!UserHandle.isApp(uid)) {
1813 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1814 }
1815
Felipe Lemef0823852016-06-08 13:43:08 -07001816 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001817 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1818 policy = oldPolicy & ~policy;
1819 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001820 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001821 }
1822 }
1823 }
1824
Felipe Lemef0823852016-06-08 13:43:08 -07001825 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1826 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001827
Felipe Leme57e3d312016-08-23 14:42:52 -07001828 final boolean notifyApp;
1829 if (!isUidValidForWhitelistRules(uid)) {
1830 notifyApp = false;
1831 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001832 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1833 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1834 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1835 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001836 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1837 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001838 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1839 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1840 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1841 if (LOGD)
1842 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1843 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1844 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001845 notifyApp = wasBlocked != isBlocked;
1846 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001847 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1848 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001849 }
1850
Felipe Lemef0823852016-06-08 13:43:08 -07001851 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001852 if (policy == POLICY_NONE) {
1853 mUidPolicy.delete(uid);
1854 } else {
1855 mUidPolicy.put(uid, policy);
1856 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001857
1858 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00001859 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001860 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001861 synchronized (mNetworkPoliciesSecondLock) {
1862 writePolicyAL();
1863 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001864 }
1865 }
1866
1867 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001868 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001869 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1870
Felipe Lemef0823852016-06-08 13:43:08 -07001871 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001872 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001873 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001874 }
1875
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001876 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001877 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001878 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1879
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001880 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001881 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001882 for (int i = 0; i < mUidPolicy.size(); i++) {
1883 final int uid = mUidPolicy.keyAt(i);
1884 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001885 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1886 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001887 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001888 }
1889 }
1890 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001891 return uids;
1892 }
1893
1894 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001895 * Removes any persistable state associated with given {@link UserHandle}, persisting
1896 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001897 */
Felipe Lemef0823852016-06-08 13:43:08 -07001898 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001899
Felipe Lemef0823852016-06-08 13:43:08 -07001900 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001901 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001902
Felipe Lemea110eec2016-04-29 09:58:06 -07001903 // Remove entries from revoked default restricted background UID whitelist
1904 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1905 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1906 if (UserHandle.getUserId(uid) == userId) {
1907 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001908 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001909 }
1910 }
1911
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001912 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001913 int[] uids = new int[0];
1914 for (int i = 0; i < mUidPolicy.size(); i++) {
1915 final int uid = mUidPolicy.keyAt(i);
1916 if (UserHandle.getUserId(uid) == userId) {
1917 uids = appendInt(uids, uid);
1918 }
1919 }
1920
1921 if (uids.length > 0) {
1922 for (int uid : uids) {
1923 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001924 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001925 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001926 }
Felipe Lemef0823852016-06-08 13:43:08 -07001927 synchronized (mNetworkPoliciesSecondLock) {
1928 updateRulesForGlobalChangeAL(true);
1929 if (writePolicy && changed) {
1930 writePolicyAL();
1931 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001933 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001934 }
1935
1936 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001937 public void setConnectivityListener(INetworkPolicyListener listener) {
1938 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1939 if (mConnectivityListener != null) {
1940 throw new IllegalStateException("Connectivity listener already registered");
1941 }
1942 mConnectivityListener = listener;
1943 }
1944
1945 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001946 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001947 // TODO: create permission for observing network policy
1948 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001949 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001950 }
1951
1952 @Override
1953 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001954 // TODO: create permission for observing network policy
1955 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001956 mListeners.unregister(listener);
1957 }
1958
Jeff Sharkey1b861272011-05-22 00:34:52 -07001959 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001960 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1962
Felipe Leme6a05eee2016-02-19 14:43:51 -08001963 final long token = Binder.clearCallingIdentity();
1964 try {
1965 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001966 synchronized (mUidRulesFirstLock) {
1967 synchronized (mNetworkPoliciesSecondLock) {
1968 normalizePoliciesNL(policies);
1969 updateNetworkEnabledNL();
1970 updateNetworkRulesNL();
1971 updateNotificationsNL();
1972 writePolicyAL();
1973 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001974 }
1975 } finally {
1976 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001977 }
1978 }
1979
Felipe Lemef0823852016-06-08 13:43:08 -07001980 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001981 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001982 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1983 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001984 }
1985
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001986 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001987 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001988 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001989 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001990 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1991 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1992 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001993 } catch (SecurityException e) {
1994 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001995
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001996 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1997 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1998 return new NetworkPolicy[0];
1999 }
Svet Ganov16a16892015-04-16 10:32:04 -07002000 }
2001
Felipe Lemef0823852016-06-08 13:43:08 -07002002 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002003 final int size = mNetworkPolicy.size();
2004 final NetworkPolicy[] policies = new NetworkPolicy[size];
2005 for (int i = 0; i < size; i++) {
2006 policies[i] = mNetworkPolicy.valueAt(i);
2007 }
2008 return policies;
2009 }
2010 }
2011
Felipe Lemef0823852016-06-08 13:43:08 -07002012 private void normalizePoliciesNL() {
2013 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002014 }
2015
Felipe Lemef0823852016-06-08 13:43:08 -07002016 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002017 final TelephonyManager tele = TelephonyManager.from(mContext);
2018 final String[] merged = tele.getMergedSubscriberIds();
2019
2020 mNetworkPolicy.clear();
2021 for (NetworkPolicy policy : policies) {
2022 // When two normalized templates conflict, prefer the most
2023 // restrictive policy
2024 policy.template = NetworkTemplate.normalize(policy.template, merged);
2025 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2026 if (existing == null || existing.compareTo(policy) > 0) {
2027 if (existing != null) {
2028 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2029 }
2030 mNetworkPolicy.put(policy.template, policy);
2031 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002032 }
2033 }
2034
2035 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002036 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002037 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002038
2039 final long token = Binder.clearCallingIdentity();
2040 try {
2041 performSnooze(template, TYPE_LIMIT);
2042 } finally {
2043 Binder.restoreCallingIdentity(token);
2044 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002045 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002046
Dianne Hackborn497175b2014-07-01 12:56:08 -07002047 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002048 maybeRefreshTrustedTime();
2049 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002050 synchronized (mUidRulesFirstLock) {
2051 synchronized (mNetworkPoliciesSecondLock) {
2052 // find and snooze local policy that matches
2053 final NetworkPolicy policy = mNetworkPolicy.get(template);
2054 if (policy == null) {
2055 throw new IllegalArgumentException("unable to find policy for " + template);
2056 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002057
Felipe Lemef0823852016-06-08 13:43:08 -07002058 switch (type) {
2059 case TYPE_WARNING:
2060 policy.lastWarningSnooze = currentTime;
2061 break;
2062 case TYPE_LIMIT:
2063 policy.lastLimitSnooze = currentTime;
2064 break;
2065 default:
2066 throw new IllegalArgumentException("unexpected type");
2067 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002068
Felipe Lemef0823852016-06-08 13:43:08 -07002069 normalizePoliciesNL();
2070 updateNetworkEnabledNL();
2071 updateNetworkRulesNL();
2072 updateNotificationsNL();
2073 writePolicyAL();
2074 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002075 }
2076 }
2077
2078 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002079 public void onTetheringChanged(String iface, boolean tethering) {
2080 // No need to enforce permission because setRestrictBackground() will do it.
2081 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002082 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002083 if (mRestrictBackground && tethering) {
2084 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2085 setRestrictBackground(false);
2086 }
2087 }
2088 }
2089
2090 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002091 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002092 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002093 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002094 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2095 final long token = Binder.clearCallingIdentity();
2096 try {
2097 maybeRefreshTrustedTime();
2098 synchronized (mUidRulesFirstLock) {
2099 if (restrictBackground == mRestrictBackground) {
2100 // Ideally, UI should never allow this scenario...
2101 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2102 return;
2103 }
2104 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002105 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002106
2107 } finally {
2108 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002109 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002110
Felipe Leme29e72ea2016-09-08 13:26:55 -07002111 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2112 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002113 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002114 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002115 }
2116 }
2117
Felipe Lemef0823852016-06-08 13:43:08 -07002118 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002119 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002120 final boolean oldRestrictBackground = mRestrictBackground;
2121 mRestrictBackground = restrictBackground;
2122 // Must whitelist foreground apps before turning data saver mode on.
2123 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2124 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002125 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002126 try {
2127 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2128 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2129 mRestrictBackground = oldRestrictBackground;
2130 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002131 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002132 return;
2133 }
2134 } catch (RemoteException e) {
2135 // ignored; service lives in system_server
2136 }
Felipe Lemef0823852016-06-08 13:43:08 -07002137 synchronized (mNetworkPoliciesSecondLock) {
2138 updateNotificationsNL();
2139 writePolicyAL();
2140 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002141 }
2142
Felipe Lemeb85a6372016-01-14 16:16:16 -08002143 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002144 public int getRestrictBackgroundByCaller() {
2145 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2146 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002147
Felipe Lemef0823852016-06-08 13:43:08 -07002148 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002149 // Must clear identity because getUidPolicy() is restricted to system.
2150 final long token = Binder.clearCallingIdentity();
2151 final int policy;
2152 try {
2153 policy = getUidPolicy(uid);
2154 } finally {
2155 Binder.restoreCallingIdentity(token);
2156 }
2157 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2158 // App is blacklisted.
2159 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2160 }
Felipe Leme1b103232016-01-22 09:44:57 -08002161 if (!mRestrictBackground) {
2162 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2163 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002164 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002165 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2166 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2167 }
2168 }
2169
2170 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002171 public boolean getRestrictBackground() {
2172 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2173
Felipe Lemef0823852016-06-08 13:43:08 -07002174 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002175 return mRestrictBackground;
2176 }
2177 }
2178
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002179 @Override
2180 public void setDeviceIdleMode(boolean enabled) {
2181 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002182 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2183 try {
2184 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002185 if (mDeviceIdleMode == enabled) {
2186 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002187 }
Felipe Lemeea014392016-09-06 13:59:54 -07002188 mDeviceIdleMode = enabled;
2189 if (mSystemReady) {
2190 // Device idle change means we need to rebuild rules for all
2191 // known apps, so do a global refresh.
2192 updateRulesForRestrictPowerUL();
2193 }
2194 }
2195 if (enabled) {
2196 EventLogTags.writeDeviceIdleOnPhase("net");
2197 } else {
2198 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002199 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002200 } finally {
2201 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002202 }
2203 }
2204
Felipe Lemef0823852016-06-08 13:43:08 -07002205 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002206 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2207 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002208 if (policy.template.matches(ident)) {
2209 return policy;
2210 }
2211 }
2212 return null;
2213 }
2214
2215 @Override
2216 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2217 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2218
2219 // only returns usage summary, so we don't require caller to have
2220 // READ_NETWORK_USAGE_HISTORY.
2221 final long token = Binder.clearCallingIdentity();
2222 try {
2223 return getNetworkQuotaInfoUnchecked(state);
2224 } finally {
2225 Binder.restoreCallingIdentity(token);
2226 }
2227 }
2228
2229 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2230 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2231
2232 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002233 synchronized (mNetworkPoliciesSecondLock) {
2234 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002235 }
2236
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002237 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002238 // missing policy means we can't derive useful quota info
2239 return null;
2240 }
2241
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002242 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002243
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002244 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002245 final long start = computeLastCycleBoundary(currentTime, policy);
2246 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002247 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002248
2249 // report soft and hard limits under policy
2250 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2251 : NetworkQuotaInfo.NO_LIMIT;
2252 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2253 : NetworkQuotaInfo.NO_LIMIT;
2254
2255 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2256 }
2257
Jeff Sharkey46645002011-07-27 21:11:21 -07002258 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002259 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002260 if (state.networkInfo == null) {
2261 return false;
2262 }
2263
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002264 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2265
2266 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002267 synchronized (mNetworkPoliciesSecondLock) {
2268 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002269 }
2270
2271 if (policy != null) {
2272 return policy.metered;
2273 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002274 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002275 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002276 return true;
2277 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002278 return false;
2279 }
2280 }
2281
2282 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002283 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002284 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002285
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002286 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2287
Dianne Hackborn497175b2014-07-01 12:56:08 -07002288 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002289 for (String arg : args) {
2290 argSet.add(arg);
2291 }
2292
Felipe Lemef0823852016-06-08 13:43:08 -07002293 synchronized (mUidRulesFirstLock) {
2294 synchronized (mNetworkPoliciesSecondLock) {
2295 if (argSet.contains("--unsnooze")) {
2296 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2297 mNetworkPolicy.valueAt(i).clearSnooze();
2298 }
2299
2300 normalizePoliciesNL();
2301 updateNetworkEnabledNL();
2302 updateNetworkRulesNL();
2303 updateNotificationsNL();
2304 writePolicyAL();
2305
2306 fout.println("Cleared snooze timestamps");
2307 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002308 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002309
Felipe Lemef0823852016-06-08 13:43:08 -07002310 fout.print("System ready: "); fout.println(mSystemReady);
2311 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2312 fout.print("Restrict power: "); fout.println(mRestrictPower);
2313 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2314 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002315 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002316 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2317 fout.println(mNetworkPolicy.valueAt(i).toString());
2318 }
2319 fout.decreaseIndent();
2320
2321 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2322
2323 fout.println("Policy for UIDs:");
2324 fout.increaseIndent();
2325 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002326 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002327 final int uid = mUidPolicy.keyAt(i);
2328 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002329 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002330 fout.print(uid);
2331 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002332 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002333 fout.println();
2334 }
2335 fout.decreaseIndent();
2336
2337 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2338 if (size > 0) {
2339 fout.println("Power save whitelist (except idle) app ids:");
2340 fout.increaseIndent();
2341 for (int i = 0; i < size; i++) {
2342 fout.print("UID=");
2343 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2344 fout.print(": ");
2345 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2346 fout.println();
2347 }
2348 fout.decreaseIndent();
2349 }
2350
2351 size = mPowerSaveWhitelistAppIds.size();
2352 if (size > 0) {
2353 fout.println("Power save whitelist app ids:");
2354 fout.increaseIndent();
2355 for (int i = 0; i < size; i++) {
2356 fout.print("UID=");
2357 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2358 fout.print(": ");
2359 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2360 fout.println();
2361 }
2362 fout.decreaseIndent();
2363 }
2364
Felipe Lemef0823852016-06-08 13:43:08 -07002365 size = mDefaultRestrictBackgroundWhitelistUids.size();
2366 if (size > 0) {
2367 fout.println("Default restrict background whitelist uids:");
2368 fout.increaseIndent();
2369 for (int i = 0; i < size; i++) {
2370 fout.print("UID=");
2371 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2372 fout.println();
2373 }
2374 fout.decreaseIndent();
2375 }
2376
2377 size = mRestrictBackgroundWhitelistRevokedUids.size();
2378 if (size > 0) {
2379 fout.println("Default restrict background whitelist uids revoked by users:");
2380 fout.increaseIndent();
2381 for (int i = 0; i < size; i++) {
2382 fout.print("UID=");
2383 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2384 fout.println();
2385 }
2386 fout.decreaseIndent();
2387 }
2388
2389 final SparseBooleanArray knownUids = new SparseBooleanArray();
2390 collectKeys(mUidState, knownUids);
2391 collectKeys(mUidRules, knownUids);
2392
2393 fout.println("Status for all known UIDs:");
2394 fout.increaseIndent();
2395 size = knownUids.size();
2396 for (int i = 0; i < size; i++) {
2397 final int uid = knownUids.keyAt(i);
2398 fout.print("UID=");
2399 fout.print(uid);
2400
2401 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2402 fout.print(" state=");
2403 fout.print(state);
2404 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2405 fout.print(" (fg)");
2406 } else {
2407 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2408 ? " (fg svc)" : " (bg)");
2409 }
2410
2411 final int uidRules = mUidRules.get(uid, RULE_NONE);
2412 fout.print(" rules=");
2413 fout.print(uidRulesToString(uidRules));
2414 fout.println();
2415 }
2416 fout.decreaseIndent();
2417
2418 fout.println("Status for just UIDs with rules:");
2419 fout.increaseIndent();
2420 size = mUidRules.size();
2421 for (int i = 0; i < size; i++) {
2422 final int uid = mUidRules.keyAt(i);
2423 fout.print("UID=");
2424 fout.print(uid);
2425 final int uidRules = mUidRules.get(uid, RULE_NONE);
2426 fout.print(" rules=");
2427 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002428 fout.println();
2429 }
2430 fout.decreaseIndent();
2431 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002432 }
2433 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002434
2435 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002436 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002437 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002438 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002439 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002440 }
2441
2442 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002443 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002444 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2445
Felipe Lemef0823852016-06-08 13:43:08 -07002446 synchronized (mUidRulesFirstLock) {
2447 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002448 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002449 }
2450
Felipe Lemef0823852016-06-08 13:43:08 -07002451 private boolean isUidForegroundUL(int uid) {
2452 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002453 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2454 }
2455
Felipe Lemef0823852016-06-08 13:43:08 -07002456 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002457 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002458 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002459 }
2460
Felipe Lemef0823852016-06-08 13:43:08 -07002461 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002462 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2463 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2464 }
2465
Felipe Lemef0823852016-06-08 13:43:08 -07002466 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002467 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002468 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002469 }
2470
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002471 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002472 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002473 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2474 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002475 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002476 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002477 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2478 try {
2479 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2480 if (oldUidState != uidState) {
2481 // state changed, push updated rules
2482 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002483 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2484 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2485 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2486 if (isUidIdle(uid)) {
2487 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002488 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002489 if (mDeviceIdleMode) {
2490 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002491 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002492 if (mRestrictPower) {
2493 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002494 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002495 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002496 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002497 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002498 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002499 } finally {
2500 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002501 }
2502 }
2503
Felipe Lemef0823852016-06-08 13:43:08 -07002504 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002505 final int index = mUidState.indexOfKey(uid);
2506 if (index >= 0) {
2507 final int oldUidState = mUidState.valueAt(index);
2508 mUidState.removeAt(index);
2509 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002510 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002511 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002512 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002513 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002514 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002515 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002516 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002517 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002518 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002519 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002520 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002521 }
2522 }
2523
Felipe Lemef28983d2016-03-25 12:18:23 -07002524 // adjust stats accounting based on foreground status
2525 private void updateNetworkStats(int uid, boolean uidForeground) {
2526 try {
2527 mNetworkStats.setUidForeground(uid, uidForeground);
2528 } catch (RemoteException e) {
2529 // ignored; service lives in system_server
2530 }
2531 }
2532
Sudheer Shankac9d94072017-02-22 22:13:55 +00002533 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2534 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002535 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002536 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002537 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002538 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002539 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002540 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002541 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002542 }
2543
Felipe Lemef0823852016-06-08 13:43:08 -07002544 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002545 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2546 try {
2547 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2548 mUidFirewallPowerSaveRules);
2549 } finally {
2550 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2551 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002552 }
2553
Felipe Lemef0823852016-06-08 13:43:08 -07002554 void updateRuleForRestrictPowerUL(int uid) {
2555 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002556 }
2557
Felipe Lemef0823852016-06-08 13:43:08 -07002558 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002559 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2560 try {
2561 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2562 mUidFirewallDozableRules);
2563 } finally {
2564 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2565 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002566 }
2567
Felipe Lemef0823852016-06-08 13:43:08 -07002568 void updateRuleForDeviceIdleUL(int uid) {
2569 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002570 }
2571
Felipe Lemef28983d2016-03-25 12:18:23 -07002572 // NOTE: since both fw_dozable and fw_powersave uses the same map
2573 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002574 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002575 SparseIntArray rules) {
2576 if (enabled) {
2577 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002578 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002579 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002580 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002581 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002582 for (int ui = users.size() - 1; ui >= 0; ui--) {
2583 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002584 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002585 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2586 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2587 int uid = UserHandle.getUid(user.id, appId);
2588 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2589 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002590 }
2591 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2592 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2593 int uid = UserHandle.getUid(user.id, appId);
2594 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2595 }
2596 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002597 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002598 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002599 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2600 }
2601 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002602 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2603 } else {
2604 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002605 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002606 }
2607
Felipe Lemef0823852016-06-08 13:43:08 -07002608 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002609 final int appId = UserHandle.getAppId(uid);
2610 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2611 }
2612
Felipe Lemef28983d2016-03-25 12:18:23 -07002613 // NOTE: since both fw_dozable and fw_powersave uses the same map
2614 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002615 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002616 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002617 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002618 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002619 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002620 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002621 }
2622 }
2623 }
2624
Felipe Lemef0823852016-06-08 13:43:08 -07002625 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002626 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2627 try {
2628 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2629 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002630
Felipe Leme873a83a2016-09-07 11:34:10 -07002631 // Fully update the app idle firewall chain.
2632 final List<UserInfo> users = mUserManager.getUsers();
2633 for (int ui = users.size() - 1; ui >= 0; ui--) {
2634 UserInfo user = users.get(ui);
2635 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2636 for (int uid : idleUids) {
2637 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2638 // quick check: if this uid doesn't have INTERNET permission, it
2639 // doesn't have network access anyway, so it is a waste to mess
2640 // with it here.
2641 if (hasInternetPermissions(uid)) {
2642 uidRules.put(uid, FIREWALL_RULE_DENY);
2643 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002644 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002645 }
2646 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002647
Felipe Lemebc853dd2016-09-08 13:26:55 -07002648 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002649 } finally {
2650 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2651 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002652 }
2653
Felipe Lemef0823852016-06-08 13:43:08 -07002654 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002655 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002656
2657 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002658 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002659 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002660 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2661 } else {
2662 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2663 }
2664 }
2665
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002666 /**
2667 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2668 * changed.
2669 */
Felipe Lemef0823852016-06-08 13:43:08 -07002670 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002671 boolean paroled = mUsageStats.isAppIdleParoleOn();
2672 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002673 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002674
2675 int ruleCount = mUidFirewallStandbyRules.size();
2676 for (int i = 0; i < ruleCount; i++) {
2677 int uid = mUidFirewallStandbyRules.keyAt(i);
2678 int oldRules = mUidRules.get(uid);
2679 if (enableChain) {
2680 // Chain wasn't enabled before and the other power-related
2681 // chains are whitelists, so we can clear the
2682 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2683 // the effective rules result in blocking network access.
2684 oldRules &= MASK_METERED_NETWORKS;
2685 } else {
2686 // Skip if it had no restrictions to begin with
2687 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2688 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002689 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002690 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002691 }
2692
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002693 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002694 * Update rules that might be changed by {@link #mRestrictBackground},
2695 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002696 */
Felipe Lemef0823852016-06-08 13:43:08 -07002697 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002698 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2699 try {
Felipe Leme09700462016-09-08 09:33:48 -07002700 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002701 updateRulesForRestrictPowerUL();
2702 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002703
Felipe Leme873a83a2016-09-07 11:34:10 -07002704 // If the set of restricted networks may have changed, re-evaluate those.
2705 if (restrictedNetworksChanged) {
2706 normalizePoliciesNL();
2707 updateNetworkRulesNL();
2708 }
2709 } finally {
2710 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002711 }
2712 }
2713
Felipe Leme09700462016-09-08 09:33:48 -07002714 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002715 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002716 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2717 try {
2718 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002719 updateRulesForPowerSaveUL();
2720 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2721 } finally {
2722 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2723 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002724 }
2725
Felipe Lemef0823852016-06-08 13:43:08 -07002726 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002727 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2728 try {
2729 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2730 } finally {
2731 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2732 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002733 }
2734
2735 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2736 private static final int TYPE_RESTRICT_POWER = 2;
2737 @Retention(RetentionPolicy.SOURCE)
2738 @IntDef(flag = false, value = {
2739 TYPE_RESTRICT_BACKGROUND,
2740 TYPE_RESTRICT_POWER,
2741 })
2742 public @interface RestrictType {
2743 }
2744
2745 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002746 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002747 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2748 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2749 }
2750 try {
2751 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002752
Felipe Leme873a83a2016-09-07 11:34:10 -07002753 // update rules for all installed applications
2754 final List<UserInfo> users = mUserManager.getUsers();
2755 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002756 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
Felipe Leme873a83a2016-09-07 11:34:10 -07002757 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2758 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002759
Felipe Leme873a83a2016-09-07 11:34:10 -07002760 final int usersSize = users.size();
2761 final int appsSize = apps.size();
2762 for (int i = 0; i < usersSize; i++) {
2763 final UserInfo user = users.get(i);
2764 for (int j = 0; j < appsSize; j++) {
2765 final ApplicationInfo app = apps.get(j);
2766 final int uid = UserHandle.getUid(user.id, app.uid);
2767 switch (type) {
2768 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002769 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002770 break;
2771 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002772 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002773 break;
2774 default:
2775 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2776 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002777 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002778 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002779 } finally {
2780 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2781 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2782 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002783 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002784 }
2785
Felipe Lemef0823852016-06-08 13:43:08 -07002786 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002787 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002788 for (int i = 0; i < users.size(); i++) {
2789 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002790 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002791 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002792 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002793 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002794 updateRuleForAppIdleUL(uid);
2795 updateRuleForDeviceIdleUL(uid);
2796 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002797 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002798 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002799 }
2800 }
2801 }
2802
Felipe Leme70c57c22016-03-29 10:45:13 -07002803 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2804 // methods below could be merged into a isUidValidForRules() method.
2805 private boolean isUidValidForBlacklistRules(int uid) {
2806 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002807 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002808 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002809 return true;
2810 }
2811
2812 return false;
2813 }
2814
Felipe Leme70c57c22016-03-29 10:45:13 -07002815 private boolean isUidValidForWhitelistRules(int uid) {
2816 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2817 }
2818
Amith Yamasani15e472352015-04-24 19:06:07 -07002819 private boolean isUidIdle(int uid) {
2820 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2821 final int userId = UserHandle.getUserId(uid);
2822
songjinshi0655edd2016-05-18 19:55:32 +08002823 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002824 for (String packageName : packages) {
2825 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2826 return false;
2827 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002828 }
2829 }
2830 return true;
2831 }
2832
2833 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002834 * Checks if an uid has INTERNET permissions.
2835 * <p>
2836 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002837 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002838 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002839 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002840 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002841 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002842 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002843 }
2844 } catch (RemoteException e) {
2845 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002846 return true;
2847 }
2848
2849 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002850 * Clears all state - internal and external - associated with an UID.
2851 */
2852 private void onUidDeletedUL(int uid) {
2853 // First cleanup in-memory state synchronously...
2854 mUidRules.delete(uid);
2855 mUidPolicy.delete(uid);
2856 mUidFirewallStandbyRules.delete(uid);
2857 mUidFirewallDozableRules.delete(uid);
2858 mUidFirewallPowerSaveRules.delete(uid);
2859 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2860 mPowerSaveWhitelistAppIds.delete(uid);
2861 mPowerSaveTempWhitelistAppIds.delete(uid);
2862
2863 // ...then update iptables asynchronously.
2864 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2865 }
2866
2867 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002868 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002869 *
Felipe Leme781ba142016-05-09 16:24:48 -07002870 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002871 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002872 * <li>Doze mode
2873 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002874 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002875 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002876 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002877 *
2878 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002879 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002880 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002881 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002882 updateRuleForDeviceIdleUL(uid);
2883 updateRuleForAppIdleUL(uid);
2884 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002885
2886 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002887 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002888
2889 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002890 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002891 }
2892
Felipe Leme70c57c22016-03-29 10:45:13 -07002893 /**
2894 * Applies network rules to bandwidth controllers based on process state and user-defined
2895 * restrictions (blacklist / whitelist).
2896 *
2897 * <p>
2898 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2899 * networks:
2900 * <ul>
2901 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2902 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2903 * also blacklisted.
2904 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2905 * no UIDs other those whitelisted will have access.
2906 * <ul>
2907 *
2908 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2909 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2910 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2911 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002912 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002913 * {@link INetworkManagementService}, but this method should also be called in events (like
2914 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2915 * following rules should also be applied:
2916 *
2917 * <ul>
2918 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2919 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2920 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2921 * {@code bw_penalty_box}.
2922 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2923 * </ul>
2924 *
2925 * <p>For optimization, the rules are only applied on user apps that have internet access
2926 * permission, since there is no need to change the {@code iptables} rule if the app does not
2927 * have permission to use the internet.
2928 *
2929 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002930 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002931 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002932 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07002933 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002934 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002935 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07002936 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002937
Dianne Hackborn497175b2014-07-01 12:56:08 -07002938 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002939 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002940 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002941
Felipe Leme781ba142016-05-09 16:24:48 -07002942 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002943 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002944 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2945 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002946
Felipe Leme70c57c22016-03-29 10:45:13 -07002947 // First step: define the new rule based on user restrictions and foreground state.
2948 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002949 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2950 newRule = RULE_TEMPORARY_ALLOW_METERED;
2951 } else if (isWhitelisted) {
2952 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002953 }
2954 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002955 if (isBlacklisted) {
2956 newRule = RULE_REJECT_METERED;
2957 } else if (mRestrictBackground && isWhitelisted) {
2958 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002959 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002960 }
Felipe Leme781ba142016-05-09 16:24:48 -07002961 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002962
Felipe Lemef28983d2016-03-25 12:18:23 -07002963 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002964 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002965 + ": isForeground=" +isForeground
2966 + ", isBlacklisted=" + isBlacklisted
2967 + ", isWhitelisted=" + isWhitelisted
2968 + ", oldRule=" + uidRulesToString(oldRule)
2969 + ", newRule=" + uidRulesToString(newRule)
2970 + ", newUidRules=" + uidRulesToString(newUidRules)
2971 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002972 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002973
Felipe Leme46c4fc32016-05-04 09:21:43 -07002974 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002975 mUidRules.delete(uid);
2976 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002977 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002978 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002979
Felipe Leme70c57c22016-03-29 10:45:13 -07002980 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002981 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002982 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002983 // Temporarily whitelist foreground app, removing from blacklist if necessary
2984 // (since bw_penalty_box prevails over bw_happy_box).
2985
2986 setMeteredNetworkWhitelist(uid, true);
2987 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2988 // but ideally it should be just:
2989 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002990 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002991 setMeteredNetworkBlacklist(uid, false);
2992 }
Felipe Leme781ba142016-05-09 16:24:48 -07002993 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002994 // Remove temporary whitelist from app that is not on foreground anymore.
2995
2996 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2997 // but ideally they should be just:
2998 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2999 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003000 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003001 setMeteredNetworkWhitelist(uid, false);
3002 }
Felipe Leme781ba142016-05-09 16:24:48 -07003003 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003004 setMeteredNetworkBlacklist(uid, true);
3005 }
Felipe Leme781ba142016-05-09 16:24:48 -07003006 } else if ((newRule & RULE_REJECT_METERED) != 0
3007 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003008 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003009 setMeteredNetworkBlacklist(uid, isBlacklisted);
3010 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003011 // Since blacklist prevails over whitelist, we need to handle the special case
3012 // where app is whitelisted and blacklisted at the same time (although such
3013 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003014 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003015 }
Felipe Leme781ba142016-05-09 16:24:48 -07003016 } else if ((newRule & RULE_ALLOW_METERED) != 0
3017 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003018 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003019 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003020 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003021 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003022 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3023 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003024 + ", whitelisted=" + isWhitelisted
3025 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003026 + ", newRule=" + uidRulesToString(newUidRules)
3027 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003028 }
Felipe Leme781ba142016-05-09 16:24:48 -07003029
Sudheer Shankac9d94072017-02-22 22:13:55 +00003030 // Dispatch changed rule to existing listeners.
3031 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003032 }
3033 }
3034
3035 /**
3036 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3037 * listeners in case of change.
3038 * <p>
3039 * There are 3 power-related rules that affects whether an app has background access on
3040 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3041 * restriction, it's added to the equivalent firewall chain:
3042 * <ul>
3043 * <li>App is idle: {@code fw_standby} firewall chain.
3044 * <li>Device is idle: {@code fw_dozable} firewall chain.
3045 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3046 * </ul>
3047 * <p>
3048 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3049 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3050 * <p>
3051 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3052 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003053 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003054 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3055
Sudheer Shankac9d94072017-02-22 22:13:55 +00003056 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003057
Sudheer Shankac9d94072017-02-22 22:13:55 +00003058 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003059 mUidRules.delete(uid);
3060 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003061 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003062 }
3063 }
3064
3065 /**
3066 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3067 *
3068 * @param uid the uid of the app to update rules for
3069 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3070 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3071 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003072 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003073 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003074 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003075 if (!isUidValidForBlacklistRules(uid)) {
3076 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003077 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003078 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003079
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003080 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003081 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003082 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003083
Felipe Lemef0823852016-06-08 13:43:08 -07003084 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003085 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3086 int newRule = RULE_NONE;
3087
3088 // First step: define the new rule based on user restrictions and foreground state.
3089
3090 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3091 // by considering the foreground and non-foreground states.
3092 if (isForeground) {
3093 if (restrictMode) {
3094 newRule = RULE_ALLOW_ALL;
3095 }
3096 } else if (restrictMode) {
3097 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3098 }
3099
3100 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3101
3102 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003103 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003104 + ", isIdle: " + isIdle
3105 + ", mRestrictPower: " + mRestrictPower
3106 + ", mDeviceIdleMode: " + mDeviceIdleMode
3107 + ", isForeground=" + isForeground
3108 + ", isWhitelisted=" + isWhitelisted
3109 + ", oldRule=" + uidRulesToString(oldRule)
3110 + ", newRule=" + uidRulesToString(newRule)
3111 + ", newUidRules=" + uidRulesToString(newUidRules)
3112 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3113 }
3114
Felipe Leme781ba142016-05-09 16:24:48 -07003115 // Second step: notify listeners if state changed.
3116 if (newRule != oldRule) {
3117 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003118 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003119 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003120 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3121 } else {
3122 // All scenarios should have been covered above
3123 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3124 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003125 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003126 + ", newRule=" + uidRulesToString(newUidRules)
3127 + ", oldRule=" + uidRulesToString(oldUidRules));
3128 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003129 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003130 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003131
Sudheer Shankac9d94072017-02-22 22:13:55 +00003132 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003133 }
3134
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003135 private class AppIdleStateChangeListener
3136 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3137
3138 @Override
3139 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3140 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003141 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3142 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003143 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003144 synchronized (mUidRulesFirstLock) {
3145 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003146 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003147 }
3148 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003149 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003150 }
3151
3152 @Override
3153 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003154 synchronized (mUidRulesFirstLock) {
3155 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003156 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003157 }
3158 }
3159
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003160 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3161 if (listener != null) {
3162 try {
3163 listener.onUidRulesChanged(uid, uidRules);
3164 } catch (RemoteException ignored) {
3165 }
3166 }
3167 }
3168
3169 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3170 String[] meteredIfaces) {
3171 if (listener != null) {
3172 try {
3173 listener.onMeteredIfacesChanged(meteredIfaces);
3174 } catch (RemoteException ignored) {
3175 }
3176 }
3177 }
3178
3179 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3180 boolean restrictBackground) {
3181 if (listener != null) {
3182 try {
3183 listener.onRestrictBackgroundChanged(restrictBackground);
3184 } catch (RemoteException ignored) {
3185 }
3186 }
3187 }
3188
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003189 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3190 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003191 if (listener != null) {
3192 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003193 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003194 } catch (RemoteException ignored) {
3195 }
3196 }
3197 }
3198
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003199 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003200 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003201 public boolean handleMessage(Message msg) {
3202 switch (msg.what) {
3203 case MSG_RULES_CHANGED: {
3204 final int uid = msg.arg1;
3205 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003206 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
3207 final int length = mListeners.beginBroadcast();
3208 for (int i = 0; i < length; i++) {
3209 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3210 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003211 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003212 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003213 return true;
3214 }
3215 case MSG_METERED_IFACES_CHANGED: {
3216 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003217 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003218 final int length = mListeners.beginBroadcast();
3219 for (int i = 0; i < length; i++) {
3220 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003221 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003222 }
3223 mListeners.finishBroadcast();
3224 return true;
3225 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003226 case MSG_LIMIT_REACHED: {
3227 final String iface = (String) msg.obj;
3228
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003229 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003230 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003231 if (mMeteredIfaces.contains(iface)) {
3232 try {
3233 // force stats update to make sure we have
3234 // numbers that caused alert to trigger.
3235 mNetworkStats.forceUpdate();
3236 } catch (RemoteException e) {
3237 // ignored; service lives in system_server
3238 }
3239
Felipe Lemef0823852016-06-08 13:43:08 -07003240 updateNetworkEnabledNL();
3241 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003242 }
3243 }
3244 return true;
3245 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003246 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3247 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003248 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003249 final int length = mListeners.beginBroadcast();
3250 for (int i = 0; i < length; i++) {
3251 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003252 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003253 }
3254 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003255 final Intent intent =
3256 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3257 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3258 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3259 return true;
3260 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003261 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003262 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003263 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003264 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003265 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003266 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003267 final int length = mListeners.beginBroadcast();
3268 for (int i = 0; i < length; i++) {
3269 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003270 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003271 }
3272 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003273 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3274 if (notifyApp.booleanValue()) {
3275 broadcastRestrictBackgroundChanged(uid, notifyApp);
3276 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003277 return true;
3278 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003279 case MSG_ADVISE_PERSIST_THRESHOLD: {
3280 final long lowestRule = (Long) msg.obj;
3281 try {
3282 // make sure stats are recorded frequently enough; we aim
3283 // for 2MB threshold for 2GB/month rules.
3284 final long persistThreshold = lowestRule / 1000;
3285 mNetworkStats.advisePersistThreshold(persistThreshold);
3286 } catch (RemoteException e) {
3287 // ignored; service lives in system_server
3288 }
3289 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003290 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003291 case MSG_UPDATE_INTERFACE_QUOTA: {
3292 removeInterfaceQuota((String) msg.obj);
3293 // int params need to be stitched back into a long
3294 setInterfaceQuota((String) msg.obj,
3295 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3296 return true;
3297 }
3298 case MSG_REMOVE_INTERFACE_QUOTA: {
3299 removeInterfaceQuota((String) msg.obj);
3300 return true;
3301 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003302 case MSG_SET_FIREWALL_RULES: {
3303 final int chain = msg.arg1;
3304 final int toggle = msg.arg2;
3305 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3306 if (uidRules != null) {
3307 setUidFirewallRules(chain, uidRules);
3308 }
3309 if (toggle != CHAIN_TOGGLE_NONE) {
3310 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3311 }
3312 return true;
3313 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003314 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3315 resetUidFirewallRules(msg.arg1);
3316 return true;
3317 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003318 default: {
3319 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003320 }
3321 }
3322 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003323
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003324 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003325
Felipe Leme57e3d312016-08-23 14:42:52 -07003326 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3327 final PackageManager pm = mContext.getPackageManager();
3328 final String[] packages = pm.getPackagesForUid(uid);
3329 if (packages != null) {
3330 final int userId = UserHandle.getUserId(uid);
3331 for (String packageName : packages) {
3332 final Intent intent =
3333 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3334 intent.setPackage(packageName);
3335 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3336 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3337 }
3338 }
3339 }
3340
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003341 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003342 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003343 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003344 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003345 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003346 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003347 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003348 }
3349 }
3350
3351 private void removeInterfaceQuota(String iface) {
3352 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003353 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003354 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003355 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003356 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003357 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003358 }
3359 }
3360
Felipe Leme70c57c22016-03-29 10:45:13 -07003361 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3362 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003363 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003364 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003365 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003366 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3367 } catch (RemoteException e) {
3368 // ignored; service lives in system_server
3369 }
3370 }
3371
3372 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3373 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3374 try {
3375 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3376 } catch (IllegalStateException e) {
3377 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003378 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003379 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003380 }
3381 }
3382
Felipe Lemebc853dd2016-09-08 13:26:55 -07003383 private static final int CHAIN_TOGGLE_NONE = 0;
3384 private static final int CHAIN_TOGGLE_ENABLE = 1;
3385 private static final int CHAIN_TOGGLE_DISABLE = 2;
3386 @Retention(RetentionPolicy.SOURCE)
3387 @IntDef(flag = false, value = {
3388 CHAIN_TOGGLE_NONE,
3389 CHAIN_TOGGLE_ENABLE,
3390 CHAIN_TOGGLE_DISABLE
3391 })
3392 public @interface ChainToggleType {
3393 }
3394
3395 /**
3396 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3397 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3398 *
3399 * @param chain firewall chain.
3400 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3401 * @param toggle whether the chain should be enabled, disabled, or not changed.
3402 */
3403 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3404 @ChainToggleType int toggle) {
3405 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3406 }
3407
Amith Yamasani15e472352015-04-24 19:06:07 -07003408 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003409 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3410 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3411 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003412 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003413 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003414 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003415 int size = uidRules.size();
3416 int[] uids = new int[size];
3417 int[] rules = new int[size];
3418 for(int index = size - 1; index >= 0; --index) {
3419 uids[index] = uidRules.keyAt(index);
3420 rules[index] = uidRules.valueAt(index);
3421 }
3422 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003423 } catch (IllegalStateException e) {
3424 Log.wtf(TAG, "problem setting firewall uid rules", e);
3425 } catch (RemoteException e) {
3426 // ignored; service lives in system_server
3427 }
3428 }
3429
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003430 /**
3431 * Add or remove a uid to the firewall blacklist for all network ifaces.
3432 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003433 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003434 if (chain == FIREWALL_CHAIN_DOZABLE) {
3435 mUidFirewallDozableRules.put(uid, rule);
3436 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3437 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003438 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3439 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003440 }
3441
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003442 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003443 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003444 } catch (IllegalStateException e) {
3445 Log.wtf(TAG, "problem setting firewall uid rules", e);
3446 } catch (RemoteException e) {
3447 // ignored; service lives in system_server
3448 }
3449 }
3450
3451 /**
3452 * Add or remove a uid to the firewall blacklist for all network ifaces.
3453 */
Felipe Lemef0823852016-06-08 13:43:08 -07003454 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003455 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3456 mFirewallChainStates.get(chain) == enable) {
3457 // All is the same, nothing to do.
3458 return;
3459 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003460 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003461 try {
3462 mNetworkManager.setFirewallChainEnabled(chain, enable);
3463 } catch (IllegalStateException e) {
3464 Log.wtf(TAG, "problem enable firewall chain", e);
3465 } catch (RemoteException e) {
3466 // ignored; service lives in system_server
3467 }
3468 }
3469
Felipe Leme03e95e22016-09-09 09:25:31 -07003470 /**
3471 * Resets all firewall rules associated with an UID.
3472 */
3473 private void resetUidFirewallRules(int uid) {
3474 try {
3475 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3476 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3477 mNetworkManager
3478 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3479 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3480 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3481 } catch (IllegalStateException e) {
3482 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3483 } catch (RemoteException e) {
3484 // ignored; service lives in system_server
3485 }
3486 }
3487
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003488 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3489 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003490 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003491 } catch (RuntimeException e) {
3492 Slog.w(TAG, "problem reading network stats: " + e);
3493 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003494 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003495 // ignored; service lives in system_server
3496 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003497 }
3498 }
3499
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003500 private boolean isBandwidthControlEnabled() {
3501 final long token = Binder.clearCallingIdentity();
3502 try {
3503 return mNetworkManager.isBandwidthControlEnabled();
3504 } catch (RemoteException e) {
3505 // ignored; service lives in system_server
3506 return false;
3507 } finally {
3508 Binder.restoreCallingIdentity(token);
3509 }
3510 }
3511
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003512 /**
3513 * Try refreshing {@link #mTime} when stale.
3514 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003515 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003516 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003517 mTime.forceRefresh();
3518 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003519 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003520
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003521 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003522 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3523 }
3524
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003525 private static Intent buildAllowBackgroundDataIntent() {
3526 return new Intent(ACTION_ALLOW_BACKGROUND);
3527 }
3528
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003529 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3530 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3531 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3532 return intent;
3533 }
3534
Wei Liu546cb772016-07-21 16:19:01 -07003535 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003536 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003537 intent.setComponent(ComponentName.unflattenFromString(
3538 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003539 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3540 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3541 return intent;
3542 }
3543
Wei Liu546cb772016-07-21 16:19:01 -07003544 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003545 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003546 intent.setComponent(ComponentName.unflattenFromString(
3547 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003548 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3549 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3550 return intent;
3551 }
3552
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003553 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003554 public void addIdleHandler(IdleHandler handler) {
3555 mHandler.getLooper().getQueue().addIdleHandler(handler);
3556 }
3557
Jeff Sharkey1b861272011-05-22 00:34:52 -07003558 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3559 final int size = source.size();
3560 for (int i = 0; i < size; i++) {
3561 target.put(source.keyAt(i), true);
3562 }
3563 }
3564
Stuart Scottf1fb3972015-04-02 18:00:02 -07003565 @Override
3566 public void factoryReset(String subscriber) {
3567 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3568
Stuart Scotte3e314d2015-04-20 14:07:45 -07003569 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3570 return;
3571 }
3572
Stuart Scottf1fb3972015-04-02 18:00:02 -07003573 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003574 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003575 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3576 for (NetworkPolicy policy : policies) {
3577 if (policy.template.equals(template)) {
3578 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3579 policy.inferred = false;
3580 policy.clearSnooze();
3581 }
3582 }
3583 setNetworkPolicies(policies);
3584
3585 // Turn restrict background data off
3586 setRestrictBackground(false);
3587
Stuart Scotte3e314d2015-04-20 14:07:45 -07003588 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3589 // Remove app's "restrict background data" flag
3590 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3591 setUidPolicy(uid, POLICY_NONE);
3592 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003593 }
3594 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003595
Felipe Lemed17fda42016-04-29 11:12:45 -07003596 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3597
3598 @Override
3599 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003600 synchronized (mUidRulesFirstLock) {
3601 boolean changed = removeUserStateUL(userId, false);
3602 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003603 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003604 synchronized (mNetworkPoliciesSecondLock) {
3605 writePolicyAL();
3606 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003607 }
3608 }
3609 }
3610 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003611}