blob: 76ee67375bd595be38a0a27a36118a56f174220d [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;
Sudheer Shankae7361852017-03-07 11:51:46 -080099import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700100import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700101import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700103import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700104import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700105import android.app.Notification;
106import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700107import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700108import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700109import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700110import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.content.Intent;
112import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700113import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700114import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700115import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700116import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700117import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700118import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700120import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700121import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700123import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700124import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700125import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700128import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700129import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700131import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700132import android.net.wifi.WifiConfiguration;
133import android.net.wifi.WifiInfo;
134import android.net.wifi.WifiManager;
jackqdyulei455e90a2017-02-09 15:29:16 -0800135import android.os.PowerSaveState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700136import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700137import android.os.Environment;
138import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700139import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700140import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700141import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700142import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700143import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700145import android.os.PowerManagerInternal;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800146import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700147import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700148import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600149import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700150import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700151import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700152import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700153import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700154import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700155import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800156import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700157import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400158import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700159import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700160import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700161import android.util.ArrayMap;
162import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700163import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700164import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700166import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700167import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700168import android.util.SparseBooleanArray;
169import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.util.TrustedTime;
171import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700172
Jeff Sharkey497e4432011-06-14 17:27:29 -0700173import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700174import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800175import com.android.internal.annotations.VisibleForTesting;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500176import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey32566012014-12-02 18:30:14 -0800177import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700178import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700179import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700180import com.android.server.DeviceIdleController;
181import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700182import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800183import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600184
jackqdyulei455e90a2017-02-09 15:29:16 -0800185import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600186import libcore.io.IoUtils;
187
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700189
190import org.xmlpull.v1.XmlPullParser;
191import org.xmlpull.v1.XmlPullParserException;
192import org.xmlpull.v1.XmlSerializer;
193
194import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700195import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196import java.io.FileInputStream;
197import java.io.FileNotFoundException;
198import java.io.FileOutputStream;
199import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700200import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700201import java.lang.annotation.Retention;
202import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100203import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700204import java.util.ArrayList;
205import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700206import java.util.List;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800207import java.util.concurrent.CountDownLatch;
208import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700209
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700210/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700211 * Service that maintains low-level network policy rules, using
212 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700213 * <p>
214 * Derives active rules by combining a given policy with other system status,
215 * and delivers to listeners, such as {@link ConnectivityManager}, for
216 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700217 *
218 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000219 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700220 * <ul>
221 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
222 * rules).
223 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
224 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000225 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
226 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700227 * </ul>
228 *
229 * <p>
230 * As such, methods that require synchronization have the following prefixes:
231 * <ul>
232 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
233 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000234 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
235 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700236 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700237 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700238public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800239 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700240 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700241 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700242
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700243 private static final int VERSION_INIT = 1;
244 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700245 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800246 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800247 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800248 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700249 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700250 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700251 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700252 private static final int VERSION_SWITCH_UID = 10;
253 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700254
Sudheer Shankae7361852017-03-07 11:51:46 -0800255 /**
256 * Max items written to {@link #ProcStateSeqHistory}.
257 */
258 @VisibleForTesting
259 public static final int MAX_PROC_STATE_SEQ_HISTORY =
260 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
261
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800262 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700263 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800264 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700265 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800266 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700267 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700268
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269 private static final String TAG_POLICY_LIST = "policy-list";
270 private static final String TAG_NETWORK_POLICY = "network-policy";
271 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700272 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800273 private static final String TAG_WHITELIST = "whitelist";
274 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800275 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700276
277 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700278 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700279 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
280 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700281 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800283 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700284 private static final String ATTR_WARNING_BYTES = "warningBytes";
285 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700286 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800287 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
288 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800289 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700290 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700292 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 private static final String ATTR_POLICY = "policy";
294
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800295 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800296 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800297 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800298 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700299
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700300 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
301
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700302 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700303 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800304 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800305 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700306 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700307 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
308 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700309 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700310 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700311 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700312
Jeff Sharkey75279902011-05-24 18:39:45 -0700313 private final Context mContext;
314 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700315 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700316 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700317 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700318 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700319 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320
321 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700322 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700323 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700324 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700325
Felipe Lemef0823852016-06-08 13:43:08 -0700326 // See main javadoc for instructions on how to use these locks.
327 final Object mUidRulesFirstLock = new Object();
328 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700329
Felipe Lemef0823852016-06-08 13:43:08 -0700330 @GuardedBy("allLocks") volatile boolean mSystemReady;
331
Felipe Lemef0823852016-06-08 13:43:08 -0700332 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
333 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
334 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700335
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700336 private final boolean mSuppressDefaultPolicy;
337
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700338 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800339 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700340 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800341 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700342
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700343 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700344 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700345 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700346 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700347
Felipe Lemef0823852016-06-08 13:43:08 -0700348 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700349 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700350 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700351 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700352 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800353 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700354
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700355 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700357 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
358
Jeff Sharkey32566012014-12-02 18:30:14 -0800359 /**
360 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700361 * in power save mode, except device idle (doze) still applies.
362 * TODO: An int array might be sufficient
363 */
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700365 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
366
367 /**
368 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800369 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700370 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800371 */
Felipe Lemef0823852016-06-08 13:43:08 -0700372 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700373 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700374
Felipe Lemef0823852016-06-08 13:43:08 -0700375 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700376 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
377
Felipe Lemeb85a6372016-01-14 16:16:16 -0800378 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800379 * UIDs that have been initially white-listed by system to avoid restricted background.
380 */
Felipe Lemef0823852016-06-08 13:43:08 -0700381 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800382 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
383 new SparseBooleanArray();
384
385 /**
386 * UIDs that have been initially white-listed by system to avoid restricted background,
387 * but later revoked by user.
388 */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800390 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
391 new SparseBooleanArray();
392
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700393 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700394 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800395 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700396 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700397 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800398 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700399
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700400 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700401 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700402 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700403
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700404 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700405 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800406 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700407
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600408 /** Higher priority listener before general event dispatch */
409 private INetworkPolicyListener mConnectivityListener;
410
Jeff Sharkey32566012014-12-02 18:30:14 -0800411 private final RemoteCallbackList<INetworkPolicyListener>
412 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700413
Dianne Hackborn497175b2014-07-01 12:56:08 -0700414 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700415
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700417 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700418
Svet Ganov16a16892015-04-16 10:32:04 -0700419 private final AppOpsManager mAppOps;
420
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800421 private final IPackageManager mIPm;
422
Sudheer Shankae7361852017-03-07 11:51:46 -0800423 private ActivityManagerInternal mActivityManagerInternal;
424
425 /**
426 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
427 * the uid and procStateSeq will be written to this and will be printed as part of dump.
428 */
429 @VisibleForTesting
430 public ProcStateSeqHistory mObservedHistory
431 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800432
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700433 // TODO: keep whitelist of system-critical services that should never have
434 // rules enforced, such as system, phone, and radio UIDs.
435
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700436 // TODO: migrate notifications to SystemUI
437
Jeff Sharkey75279902011-05-24 18:39:45 -0700438 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700439 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
440 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700441 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
442 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700443 }
444
445 private static File getSystemDir() {
446 return new File(Environment.getDataDirectory(), "system");
447 }
448
449 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700450 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700451 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700452 mContext = checkNotNull(context, "missing context");
453 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700454 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700455 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700456 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700457 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700458 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700459 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700460 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700461
Amith Yamasani450a16b2013-09-18 16:28:50 -0700462 HandlerThread thread = new HandlerThread(TAG);
463 thread.start();
464 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700465
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700466 mSuppressDefaultPolicy = suppressDefaultPolicy;
467
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700468 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700469
470 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800471
Felipe Lemed17fda42016-04-29 11:12:45 -0700472 // Expose private service for system components to use.
473 LocalServices.addService(NetworkPolicyManagerInternal.class,
474 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700475 }
476
477 public void bindConnectivityManager(IConnectivityManager connManager) {
478 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700479 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700480
Jeff Sharkey497e4432011-06-14 17:27:29 -0700481 public void bindNotificationManager(INotificationManager notifManager) {
482 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
483 }
484
Felipe Lemef0823852016-06-08 13:43:08 -0700485 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700486 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700487 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
488 mPowerSaveWhitelistExceptIdleAppIds.clear();
489 if (whitelist != null) {
490 for (int uid : whitelist) {
491 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
492 }
493 }
494 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700495 mPowerSaveWhitelistAppIds.clear();
496 if (whitelist != null) {
497 for (int uid : whitelist) {
498 mPowerSaveWhitelistAppIds.put(uid, true);
499 }
500 }
501 } catch (RemoteException e) {
502 }
503 }
504
Felipe Lemea9505cc2016-02-26 10:28:41 -0800505 /**
506 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
507 * revoke the whitelist.
508 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700509 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800510 */
Felipe Lemef0823852016-06-08 13:43:08 -0700511 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800512 final List<UserInfo> users = mUserManager.getUsers();
513 final int numberUsers = users.size();
514
Felipe Lemea110eec2016-04-29 09:58:06 -0700515 boolean changed = false;
516 for (int i = 0; i < numberUsers; i++) {
517 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700518 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700519 }
520 return changed;
521 }
522
Felipe Lemef0823852016-06-08 13:43:08 -0700523 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700524 final SystemConfig sysConfig = SystemConfig.getInstance();
525 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800526 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
527 boolean changed = false;
528 for (int i = 0; i < allowDataUsage.size(); i++) {
529 final String pkg = allowDataUsage.valueAt(i);
530 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700531 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
532 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800533 final ApplicationInfo app;
534 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700535 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700537 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
538 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800539 continue;
540 }
541 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700542 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
543 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800544 continue;
545 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700546 final int uid = UserHandle.getUid(userId, app.uid);
547 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
548 if (LOGD)
549 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
550 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800551 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700552 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700553 if (LOGD)
554 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
555 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700556 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700557 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800558 }
559 }
560 return changed;
561 }
562
Felipe Lemef0823852016-06-08 13:43:08 -0700563 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700564 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700565 // Clear the states of the current whitelist
566 final int N = mPowerSaveTempWhitelistAppIds.size();
567 for (int i = 0; i < N; i++) {
568 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
569 }
570 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700571 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700572 if (whitelist != null) {
573 for (int uid : whitelist) {
574 mPowerSaveTempWhitelistAppIds.put(uid, true);
575 }
576 }
577 } catch (RemoteException e) {
578 }
579 }
580
Amith Yamasani06f08062015-06-12 13:23:33 -0700581 /**
582 * Remove unnecessary entries in the temp whitelist
583 */
Felipe Lemef0823852016-06-08 13:43:08 -0700584 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700585 final int N = mPowerSaveTempWhitelistAppIds.size();
586 for (int i = N - 1; i >= 0; i--) {
587 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
588 mPowerSaveTempWhitelistAppIds.removeAt(i);
589 }
590 }
591 }
592
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800593 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700594 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800595 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700596 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800597 // Boost thread's priority during system server init
598 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700599 if (!isBandwidthControlEnabled()) {
600 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
601 return;
602 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700603
Felipe Leme873a83a2016-09-07 11:34:10 -0700604 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700605
Felipe Leme873a83a2016-09-07 11:34:10 -0700606 synchronized (mUidRulesFirstLock) {
607 synchronized (mNetworkPoliciesSecondLock) {
608 updatePowerSaveWhitelistUL();
609 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
610 mPowerManagerInternal.registerLowPowerModeObserver(
611 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800612 @Override
613 public int getServiceType() {
614 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700615 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800616
617 @Override
618 public void onLowPowerModeChanged(PowerSaveState result) {
619 final boolean enabled = result.batterySaverEnabled;
620 if (LOGD) Slog.d(TAG,
621 "onLowPowerModeChanged(" + enabled + ")");
622 synchronized (mUidRulesFirstLock) {
623 if (mRestrictPower != enabled) {
624 mRestrictPower = enabled;
625 updateRulesForRestrictPowerUL();
626 }
627 }
628 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700629 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800630 mRestrictPower = mPowerManagerInternal.getLowPowerState(
631 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700632
633 mSystemReady = true;
634
635 // read policy from disk
636 readPolicyAL();
637
638 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
639 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700640 }
Felipe Lemef0823852016-06-08 13:43:08 -0700641
Felipe Leme873a83a2016-09-07 11:34:10 -0700642 setRestrictBackgroundUL(mRestrictBackground);
643 updateRulesForGlobalChangeAL(false);
644 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700645 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800646 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700647
Sudheer Shankae7361852017-03-07 11:51:46 -0800648 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700649 try {
650 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000651 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800652 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700653 mNetworkManager.registerObserver(mAlertObserver);
654 } catch (RemoteException e) {
655 // ignored; both services live in system_server
656 }
657
658 // listen for changes to power save whitelist
659 final IntentFilter whitelistFilter = new IntentFilter(
660 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
661 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
662
663 DeviceIdleController.LocalService deviceIdleService
664 = LocalServices.getService(DeviceIdleController.LocalService.class);
665 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
666
667 // watch for network interfaces to be claimed
668 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
669 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
670
671 // listen for package changes to update policy
672 final IntentFilter packageFilter = new IntentFilter();
673 packageFilter.addAction(ACTION_PACKAGE_ADDED);
674 packageFilter.addDataScheme("package");
675 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
676
677 // listen for UID changes to update policy
678 mContext.registerReceiver(
679 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
680
681 // listen for user changes to update policy
682 final IntentFilter userFilter = new IntentFilter();
683 userFilter.addAction(ACTION_USER_ADDED);
684 userFilter.addAction(ACTION_USER_REMOVED);
685 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
686
687 // listen for stats update events
688 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
689 mContext.registerReceiver(
690 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
691
692 // listen for restrict background changes from notifications
693 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
694 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
695
696 // listen for snooze warning from notifications
697 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
698 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
699 MANAGE_NETWORK_POLICY, mHandler);
700
701 // listen for configured wifi networks to be removed
702 final IntentFilter wifiConfigFilter =
703 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
704 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
705
706 // listen for wifi state changes to catch metered hint
707 final IntentFilter wifiStateFilter = new IntentFilter(
708 WifiManager.NETWORK_STATE_CHANGED_ACTION);
709 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
710
711 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800712 // tell systemReady() that the service has been initialized
713 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700714 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800715 // Restore the default priority after init is done
716 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700717 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700718 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700719 }
720
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800721 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
722 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
723 mHandler.post(() -> initService(initCompleteSignal));
724 return initCompleteSignal;
725 }
726
727 public void systemReady(CountDownLatch initCompleteSignal) {
728 // wait for initService to complete
729 try {
730 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
731 throw new IllegalStateException("Service " + TAG +" init timeout");
732 }
733 } catch (InterruptedException e) {
734 Thread.currentThread().interrupt();
735 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
736 }
737 }
738
Sudheer Shankac9d94072017-02-22 22:13:55 +0000739 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800740 @Override public void onUidStateChanged(int uid, int procState,
741 long procStateSeq) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700742 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
743 try {
744 synchronized (mUidRulesFirstLock) {
Sudheer Shankae7361852017-03-07 11:51:46 -0800745 // We received a uid state change callback, add it to the history so that it
746 // will be useful for debugging.
747 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
748 // Now update the network policy rules as per the updated uid state.
Sudheer Shankac9d94072017-02-22 22:13:55 +0000749 updateUidStateUL(uid, procState);
Sudheer Shankae7361852017-03-07 11:51:46 -0800750 // Updating the network rules is done, so notify AMS about this.
751 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
Felipe Leme873a83a2016-09-07 11:34:10 -0700752 }
753 } finally {
754 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700755 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700756 }
757
Dianne Hackborne07641d2016-11-09 15:07:23 -0800758 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700759 synchronized (mUidRulesFirstLock) {
760 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700761 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700762 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700763
764 @Override public void onUidActive(int uid) throws RemoteException {
765 }
766
Dianne Hackborne07641d2016-11-09 15:07:23 -0800767 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700768 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700769 };
770
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700771 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700772 @Override
773 public void onReceive(Context context, Intent intent) {
774 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700775 synchronized (mUidRulesFirstLock) {
776 updatePowerSaveWhitelistUL();
777 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700778 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700779 }
780 }
781 };
782
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700783 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
784 @Override
785 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700786 synchronized (mUidRulesFirstLock) {
787 updatePowerSaveTempWhitelistUL();
788 updateRulesForTempWhitelistChangeUL();
789 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700790 }
791 }
792 };
793
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700794 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700795 @Override
796 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700797 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700798
799 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700800 final int uid = intent.getIntExtra(EXTRA_UID, -1);
801 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700802
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700803 if (ACTION_PACKAGE_ADDED.equals(action)) {
804 // update rules for UID, since it might be subject to
805 // global background data policy
806 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700807 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700808 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700809 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700810 }
811 }
812 };
813
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700814 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700815 @Override
816 public void onReceive(Context context, Intent intent) {
817 // on background handler thread, and UID_REMOVED is protected
818
819 final int uid = intent.getIntExtra(EXTRA_UID, -1);
820 if (uid == -1) return;
821
822 // remove any policy and update rules to clean up
823 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700824 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700825 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700826 synchronized (mNetworkPoliciesSecondLock) {
827 writePolicyAL();
828 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700829 }
830 }
831 };
832
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700833 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700834 @Override
835 public void onReceive(Context context, Intent intent) {
836 // on background handler thread, and USER_ADDED and USER_REMOVED
837 // broadcasts are protected
838
839 final String action = intent.getAction();
840 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
841 if (userId == -1) return;
842
Amith Yamasani15e472352015-04-24 19:06:07 -0700843 switch (action) {
844 case ACTION_USER_REMOVED:
845 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700846 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800847 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700848 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700849 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700850 if (action == ACTION_USER_ADDED) {
851 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700852 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700853 }
854 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700855 synchronized (mNetworkPoliciesSecondLock) {
856 updateRulesForGlobalChangeAL(true);
857 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700858 }
859 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700860 }
861 }
862 };
863
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700864 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700865 * Receiver that watches for {@link INetworkStatsService} updates, which we
866 * use to check against {@link NetworkPolicy#warningBytes}.
867 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700868 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700869 @Override
870 public void onReceive(Context context, Intent intent) {
871 // on background handler thread, and verified
872 // READ_NETWORK_USAGE_HISTORY permission above.
873
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800874 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700875 synchronized (mNetworkPoliciesSecondLock) {
876 updateNetworkEnabledNL();
877 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700878 }
879 }
880 };
881
882 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700883 * Receiver that watches for {@link Notification} control of
884 * {@link #mRestrictBackground}.
885 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700886 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700887 @Override
888 public void onReceive(Context context, Intent intent) {
889 // on background handler thread, and verified MANAGE_NETWORK_POLICY
890 // permission above.
891
892 setRestrictBackground(false);
893 }
894 };
895
896 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800897 * Receiver that watches for {@link Notification} control of
898 * {@link NetworkPolicy#lastWarningSnooze}.
899 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700900 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800901 @Override
902 public void onReceive(Context context, Intent intent) {
903 // on background handler thread, and verified MANAGE_NETWORK_POLICY
904 // permission above.
905
906 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
907 performSnooze(template, TYPE_WARNING);
908 }
909 };
910
911 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700912 * Receiver that watches for {@link WifiConfiguration} to be changed.
913 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700914 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700915 @Override
916 public void onReceive(Context context, Intent intent) {
917 // on background handler thread, and verified CONNECTIVITY_INTERNAL
918 // permission above.
919
920 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
921 if (reason == CHANGE_REASON_REMOVED) {
922 final WifiConfiguration config = intent.getParcelableExtra(
923 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700924 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800925 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700926 synchronized (mUidRulesFirstLock) {
927 synchronized (mNetworkPoliciesSecondLock) {
928 if (mNetworkPolicy.containsKey(template)) {
929 mNetworkPolicy.remove(template);
930 writePolicyAL();
931 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700932 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700933 }
934 }
935 }
936 }
937 };
938
939 /**
940 * Receiver that watches {@link WifiInfo} state changes to infer metered
941 * state. Ignores hints when policy is user-defined.
942 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700943 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700944 @Override
945 public void onReceive(Context context, Intent intent) {
946 // on background handler thread, and verified CONNECTIVITY_INTERNAL
947 // permission above.
948
949 // ignore when not connected
950 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
951 if (!netInfo.isConnected()) return;
952
953 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
954 final boolean meteredHint = info.getMeteredHint();
955
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800956 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700957 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700958 NetworkPolicy policy = mNetworkPolicy.get(template);
959 if (policy == null && meteredHint) {
960 // policy doesn't exist, and AP is hinting that it's
961 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800962 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700963 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700964
965 } else if (policy != null && policy.inferred) {
966 // policy exists, and was inferred: update its current
967 // metered state.
968 policy.metered = meteredHint;
969
970 // since this is inferred for each wifi session, just update
971 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700972 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700973 }
974 }
975 }
976 };
977
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800978 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
979 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
980 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
981 metered, true);
982 }
983
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700984 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700985 * Observer that watches for {@link INetworkManagementService} alerts.
986 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700987 final private INetworkManagementEventObserver mAlertObserver
988 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700989 @Override
990 public void limitReached(String limitName, String iface) {
991 // only someone like NMS should be calling us
992 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
993
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800994 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
995 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700996 }
997 }
998 };
999
1000 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1002 * to show visible notifications as needed.
1003 */
Felipe Lemef0823852016-06-08 13:43:08 -07001004 void updateNotificationsNL() {
1005 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001006
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001007 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -07001008 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001009 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001010
1011 // TODO: when switching to kernel notifications, compute next future
1012 // cycle boundary to recompute notifications.
1013
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001014 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001015 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001016 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1017 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001018 // ignore policies that aren't relevant to user
1019 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001020 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021
Jeff Sharkey497e4432011-06-14 17:27:29 -07001022 final long start = computeLastCycleBoundary(currentTime, policy);
1023 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001024 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001025
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001026 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001027 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001028 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1029 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001030 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001031 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001032 }
1033
Jeff Sharkey497e4432011-06-14 17:27:29 -07001034 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001035 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001037 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001039 }
1040 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001041 }
1042
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001043 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001044 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
1045 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 if (!mActiveNotifs.contains(tag)) {
1047 cancelNotification(tag);
1048 }
1049 }
1050 }
1051
1052 /**
1053 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001054 * current device state, such as when
1055 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1056 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001057 */
1058 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001059 if (template.isMatchRuleMobile()) {
1060 final TelephonyManager tele = TelephonyManager.from(mContext);
1061 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001062
Jeff Sharkey32566012014-12-02 18:30:14 -08001063 // Mobile template is relevant when any active subscriber matches
1064 final int[] subIds = sub.getActiveSubscriptionIdList();
1065 for (int subId : subIds) {
1066 final String subscriberId = tele.getSubscriberId(subId);
1067 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001068 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001069 if (template.matches(probeIdent)) {
1070 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001071 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001072 }
1073 return false;
1074 } else {
1075 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001076 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077 }
1078
1079 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001080 * Notify that given {@link NetworkTemplate} is over
1081 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1082 */
Felipe Lemef0823852016-06-08 13:43:08 -07001083 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001085 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001086 mOverLimitNotified.add(template);
1087 }
1088 }
1089
Felipe Lemef0823852016-06-08 13:43:08 -07001090 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001091 mOverLimitNotified.remove(template);
1092 }
1093
1094 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001095 * Build unique tag that identifies an active {@link NetworkPolicy}
1096 * notification of a specific type, like {@link #TYPE_LIMIT}.
1097 */
1098 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001099 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001100 }
1101
1102 /**
1103 * Show notification for combined {@link NetworkPolicy} and specific type,
1104 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1105 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001106 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001107 final String tag = buildNotificationTag(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001108 final Notification.Builder builder =
1109 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001110 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001111 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001112 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001113 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001114
1115 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001116 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001117 switch (type) {
1118 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001120 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001121
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001122 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001123 builder.setTicker(title);
1124 builder.setContentTitle(title);
1125 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001126 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001127 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001128
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001129 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1130 builder.setDeleteIntent(PendingIntent.getBroadcast(
1131 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1132
Wei Liu546cb772016-07-21 16:19:01 -07001133 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001134 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001135 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1136
Jeff Sharkey497e4432011-06-14 17:27:29 -07001137 break;
1138 }
1139 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001140 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001141
1142 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001143 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001144 switch (policy.template.getMatchRule()) {
1145 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001146 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001147 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001148 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001150 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001151 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001152 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001153 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001154 case MATCH_WIFI:
1155 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001156 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001157 break;
1158 default:
1159 title = null;
1160 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001161 }
1162
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001163 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001164 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001165 builder.setTicker(title);
1166 builder.setContentTitle(title);
1167 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001168
Wei Liu546cb772016-07-21 16:19:01 -07001169 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001170 builder.setContentIntent(PendingIntent.getActivity(
1171 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1172 break;
1173 }
1174 case TYPE_LIMIT_SNOOZED: {
1175 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001176 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001177 Formatter.formatFileSize(mContext, overBytes));
1178
1179 final CharSequence title;
1180 switch (policy.template.getMatchRule()) {
1181 case MATCH_MOBILE_3G_LOWER:
1182 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1183 break;
1184 case MATCH_MOBILE_4G:
1185 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1186 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001187 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001188 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1189 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001190 case MATCH_WIFI:
1191 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1192 break;
1193 default:
1194 title = null;
1195 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001196 }
1197
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001198 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001199 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001200 builder.setTicker(title);
1201 builder.setContentTitle(title);
1202 builder.setContentText(body);
1203
Wei Liu546cb772016-07-21 16:19:01 -07001204 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001205 builder.setContentIntent(PendingIntent.getActivity(
1206 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001207 break;
1208 }
1209 }
1210
1211 // TODO: move to NotificationManager once we can mock it
1212 try {
1213 final String packageName = mContext.getPackageName();
1214 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001215 if(!TextUtils.isEmpty(body)) {
1216 builder.setStyle(new Notification.BigTextStyle()
1217 .bigText(body));
1218 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001219 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001220 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001221 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001222 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001223 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001224 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001225 }
1226 }
1227
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001228 private void cancelNotification(String tag) {
1229 // TODO: move to NotificationManager once we can mock it
1230 try {
1231 final String packageName = mContext.getPackageName();
1232 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001233 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001234 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001235 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001236 }
1237 }
1238
1239 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001240 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001241 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001242 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001243 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001244 @Override
1245 public void onReceive(Context context, Intent intent) {
1246 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1247 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001248
1249 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001250 synchronized (mNetworkPoliciesSecondLock) {
1251 ensureActiveMobilePolicyNL();
1252 normalizePoliciesNL();
1253 updateNetworkEnabledNL();
1254 updateNetworkRulesNL();
1255 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001256 }
1257 }
1258 };
1259
1260 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001261 * Proactively control network data connections when they exceed
1262 * {@link NetworkPolicy#limitBytes}.
1263 */
Felipe Lemef0823852016-06-08 13:43:08 -07001264 void updateNetworkEnabledNL() {
1265 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001266
1267 // TODO: reset any policy-disabled networks when any policy is removed
1268 // completely, which is currently rare case.
1269
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001270 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001271 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1272 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001273 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001274 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001275 setNetworkTemplateEnabled(policy.template, true);
1276 continue;
1277 }
1278
1279 final long start = computeLastCycleBoundary(currentTime, policy);
1280 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001281 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001282
1283 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001284 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1285 && policy.lastLimitSnooze < start;
1286 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001287
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001288 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001289 }
1290 }
1291
1292 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001293 * Proactively disable networks that match the given
1294 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001295 */
1296 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001297 // TODO: reach into ConnectivityManager to proactively disable bringing
1298 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001299
1300 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1301 // If mobile data usage hits the limit or if the user resumes the data, we need to
1302 // notify telephony.
1303 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1304 final TelephonyManager tm = TelephonyManager.from(mContext);
1305
1306 final int[] subIds = sm.getActiveSubscriptionIdList();
1307 for (int subId : subIds) {
1308 final String subscriberId = tm.getSubscriberId(subId);
1309 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1310 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1311 // Template is matched when subscriber id matches.
1312 if (template.matches(probeIdent)) {
1313 tm.setPolicyDataEnabled(enabled, subId);
1314 }
1315 }
1316 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001317 }
1318
1319 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001320 * Examine all connected {@link NetworkState}, looking for
1321 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1322 * remaining quota based on usage cycle and historical stats.
1323 */
Felipe Lemef0823852016-06-08 13:43:08 -07001324 void updateNetworkRulesNL() {
1325 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001326
1327 final NetworkState[] states;
1328 try {
1329 states = mConnManager.getAllNetworkState();
1330 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001331 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001332 return;
1333 }
1334
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001335 // First, generate identities of all connected networks so we can
1336 // quickly compare them against all defined policies below.
1337 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001338 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001339 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001340 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001341 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001342
1343 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001344 if (baseIface != null) {
1345 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001346 }
1347
1348 // Stacked interfaces are considered to have same identity as
1349 // their parent network.
1350 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1351 for (LinkProperties stackedLink : stackedLinks) {
1352 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001353 if (stackedIface != null) {
1354 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001355 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001356 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001357 }
1358 }
1359
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001360 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001361 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001362 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001363 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001364 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001366 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001367 for (int j = connIdents.size() - 1; j >= 0; j--) {
1368 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1369 if (policy.template.matches(ident.second)) {
1370 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001371 }
1372 }
1373
1374 if (ifaceList.size() > 0) {
1375 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001376 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001377 }
1378 }
1379
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001380 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001381 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001382
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001383 // apply each policy that we found ifaces for; compute remaining data
1384 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001385 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001386 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1387 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1388 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001389
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001390 final long start;
1391 final long totalBytes;
1392 if (policy.hasCycle()) {
1393 start = computeLastCycleBoundary(currentTime, policy);
1394 totalBytes = getTotalBytes(policy.template, start, currentTime);
1395 } else {
1396 start = Long.MAX_VALUE;
1397 totalBytes = 0;
1398 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001399
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001400 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001401 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001402 }
1403
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001404 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001405 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001406 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001407 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001408 if (!hasLimit) {
1409 // metered network, but no policy limit; we still need to
1410 // restrict apps, so push really high quota.
1411 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001412 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001413 // snoozing past quota, but we still need to restrict apps,
1414 // so push really high quota.
1415 quotaBytes = Long.MAX_VALUE;
1416 } else {
1417 // remaining "quota" bytes are based on total usage in
1418 // current cycle. kernel doesn't like 0-byte rules, so we
1419 // set 1-byte quota and disable the radio later.
1420 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1421 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001422
1423 if (ifaces.length > 1) {
1424 // TODO: switch to shared quota once NMS supports
1425 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001426 }
1427
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001428 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001429 // long quotaBytes split up into two ints to fit in message
1430 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1431 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1432 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001433 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001434 }
1435 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001436
1437 // keep track of lowest warning or limit of active policies
1438 if (hasWarning && policy.warningBytes < lowestRule) {
1439 lowestRule = policy.warningBytes;
1440 }
1441 if (hasLimit && policy.limitBytes < lowestRule) {
1442 lowestRule = policy.limitBytes;
1443 }
1444 }
1445
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001446 for (int i = connIfaces.size()-1; i >= 0; i--) {
1447 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001448 // long quotaBytes split up into two ints to fit in message
1449 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1450 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1451 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001452 newMeteredIfaces.add(iface);
1453 }
1454
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001455 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001456
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001457 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001458 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1459 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001460 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001461 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1462 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001463 }
1464 }
1465 mMeteredIfaces = newMeteredIfaces;
1466
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001467 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001468 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001469 }
1470
1471 /**
1472 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1473 * have at least a default mobile policy defined.
1474 */
Felipe Lemef0823852016-06-08 13:43:08 -07001475 private void ensureActiveMobilePolicyNL() {
1476 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001477 if (mSuppressDefaultPolicy) return;
1478
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001479 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001480 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001481
Jeff Sharkey32566012014-12-02 18:30:14 -08001482 final int[] subIds = sub.getActiveSubscriptionIdList();
1483 for (int subId : subIds) {
1484 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001485 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001486 }
1487 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001488
Felipe Lemef0823852016-06-08 13:43:08 -07001489 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001490 // Poke around to see if we already have a policy
1491 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001492 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001493 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1494 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1495 if (template.matches(probeIdent)) {
1496 if (LOGD) {
1497 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1498 + NetworkIdentity.scrubSubscriberId(subscriberId));
1499 }
1500 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001501 }
1502 }
1503
Jeff Sharkey32566012014-12-02 18:30:14 -08001504 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1505 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001506
Jeff Sharkey32566012014-12-02 18:30:14 -08001507 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001508 final int dataWarningConfig = mContext.getResources().getInteger(
1509 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1510 final long warningBytes;
1511 if (dataWarningConfig == WARNING_DISABLED) {
1512 warningBytes = WARNING_DISABLED;
1513 } else {
1514 warningBytes = dataWarningConfig * MB_IN_BYTES;
1515 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001516
Jeff Sharkey32566012014-12-02 18:30:14 -08001517 final Time time = new Time();
1518 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001519
Jeff Sharkey32566012014-12-02 18:30:14 -08001520 final int cycleDay = time.monthDay;
1521 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001522
Jeff Sharkey32566012014-12-02 18:30:14 -08001523 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1524 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1525 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001526 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001527 }
1528
Felipe Lemef0823852016-06-08 13:43:08 -07001529 private void readPolicyAL() {
1530 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531
1532 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001533 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001534 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001535
1536 FileInputStream fis = null;
1537 try {
1538 fis = mPolicyFile.openRead();
1539 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001540 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541
Felipe Leme46b451f2016-08-19 08:46:17 -07001542 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1543 // to skip UIDs that were explicitly blacklisted.
1544 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1545
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001546 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001547 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001548 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 while ((type = in.next()) != END_DOCUMENT) {
1550 final String tag = in.getName();
1551 if (type == START_TAG) {
1552 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001553 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001554 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001555 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1556 mRestrictBackground = readBooleanAttribute(
1557 in, ATTR_RESTRICT_BACKGROUND);
1558 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001559 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001560 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001561 if (mRestrictBackground != oldValue) {
1562 // Some early services may have read the default value,
1563 // so notify them that it's changed
1564 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1565 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1566 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567
1568 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1569 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1570 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001571 final String networkId;
1572 if (version >= VERSION_ADDED_NETWORK_ID) {
1573 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1574 } else {
1575 networkId = null;
1576 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001577 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001578 final String cycleTimezone;
1579 if (version >= VERSION_ADDED_TIMEZONE) {
1580 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1581 } else {
1582 cycleTimezone = Time.TIMEZONE_UTC;
1583 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1585 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001586 final long lastLimitSnooze;
1587 if (version >= VERSION_SPLIT_SNOOZE) {
1588 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1589 } else if (version >= VERSION_ADDED_SNOOZE) {
1590 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001591 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001592 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001593 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001594 final boolean metered;
1595 if (version >= VERSION_ADDED_METERED) {
1596 metered = readBooleanAttribute(in, ATTR_METERED);
1597 } else {
1598 switch (networkTemplate) {
1599 case MATCH_MOBILE_3G_LOWER:
1600 case MATCH_MOBILE_4G:
1601 case MATCH_MOBILE_ALL:
1602 metered = true;
1603 break;
1604 default:
1605 metered = false;
1606 }
1607 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001608 final long lastWarningSnooze;
1609 if (version >= VERSION_SPLIT_SNOOZE) {
1610 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1611 } else {
1612 lastWarningSnooze = SNOOZE_NEVER;
1613 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001614 final boolean inferred;
1615 if (version >= VERSION_ADDED_INFERRED) {
1616 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1617 } else {
1618 inferred = false;
1619 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620
Jeff Sharkey32566012014-12-02 18:30:14 -08001621 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1622 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001623 if (template.isPersistable()) {
1624 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1625 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1626 lastLimitSnooze, metered, inferred));
1627 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001628
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001629 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001630 final int uid = readIntAttribute(in, ATTR_UID);
1631 final int policy = readIntAttribute(in, ATTR_POLICY);
1632
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001633 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001634 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001635 } else {
1636 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1637 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001638 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001639 final int appId = readIntAttribute(in, ATTR_APP_ID);
1640 final int policy = readIntAttribute(in, ATTR_POLICY);
1641
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001642 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001643 // app policy is deprecated so this is only used in pre system user split.
1644 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001645 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001646 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001647 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001648 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001649 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001650 } else if (TAG_WHITELIST.equals(tag)) {
1651 insideWhitelist = true;
1652 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1653 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001654 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001655 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1656 final int uid = readIntAttribute(in, ATTR_UID);
1657 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001658 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001659 } else if (type == END_TAG) {
1660 if (TAG_WHITELIST.equals(tag)) {
1661 insideWhitelist = false;
1662 }
1663
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001664 }
1665 }
1666
Felipe Leme46b451f2016-08-19 08:46:17 -07001667 final int size = whitelistedRestrictBackground.size();
1668 for (int i = 0; i < size; i++) {
1669 final int uid = whitelistedRestrictBackground.keyAt(i);
1670 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1671 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1672 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1673 + " because its policy is " + uidPoliciesToString(policy));
1674 continue;
1675 }
1676 if (UserHandle.isApp(uid)) {
1677 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1678 if (LOGV)
1679 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1680 setUidPolicyUncheckedUL(uid, newPolicy, false);
1681 } else {
1682 Slog.w(TAG, "unable to update policy on UID " + uid);
1683 }
1684 }
1685
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001686 } catch (FileNotFoundException e) {
1687 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001688 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001689 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001690 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001691 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001692 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001693 } finally {
1694 IoUtils.closeQuietly(fis);
1695 }
1696 }
1697
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001698 /**
1699 * Upgrade legacy background data flags, notifying listeners of one last
1700 * change to always-true.
1701 */
Felipe Lemef0823852016-06-08 13:43:08 -07001702 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001703 mRestrictBackground = Settings.Secure.getInt(
1704 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1705
1706 // kick off one last broadcast if restricted
1707 if (mRestrictBackground) {
1708 final Intent broadcast = new Intent(
1709 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001710 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001711 }
1712 }
1713
Felipe Lemef0823852016-06-08 13:43:08 -07001714 void writePolicyAL() {
1715 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001716
1717 FileOutputStream fos = null;
1718 try {
1719 fos = mPolicyFile.startWrite();
1720
1721 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001722 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001723 out.startDocument(null, true);
1724
1725 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001726 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001727 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001728
1729 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001730 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1731 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001732 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001733 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001734
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001735 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001736 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1737 final String subscriberId = template.getSubscriberId();
1738 if (subscriberId != null) {
1739 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001740 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001741 final String networkId = template.getNetworkId();
1742 if (networkId != null) {
1743 out.attribute(null, ATTR_NETWORK_ID, networkId);
1744 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001745 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001746 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001747 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1748 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001749 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1750 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001751 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001752 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001753 out.endTag(null, TAG_NETWORK_POLICY);
1754 }
1755
1756 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001757 for (int i = 0; i < mUidPolicy.size(); i++) {
1758 final int uid = mUidPolicy.keyAt(i);
1759 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001760
Jeff Sharkey497e4432011-06-14 17:27:29 -07001761 // skip writing empty policies
1762 if (policy == POLICY_NONE) continue;
1763
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001764 out.startTag(null, TAG_UID_POLICY);
1765 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001766 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001767 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001768 }
1769
1770 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001771
1772 // write all whitelists
1773 out.startTag(null, TAG_WHITELIST);
1774
Felipe Lemea9505cc2016-02-26 10:28:41 -08001775 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001776 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001777 for (int i = 0; i < size; i++) {
1778 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1779 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1780 writeIntAttribute(out, ATTR_UID, uid);
1781 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1782 }
1783
Felipe Lemeb85a6372016-01-14 16:16:16 -08001784 out.endTag(null, TAG_WHITELIST);
1785
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001786 out.endDocument();
1787
1788 mPolicyFile.finishWrite(fos);
1789 } catch (IOException e) {
1790 if (fos != null) {
1791 mPolicyFile.failWrite(fos);
1792 }
1793 }
1794 }
1795
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001796 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001797 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001798 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001799
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001800 if (!UserHandle.isApp(uid)) {
1801 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001802 }
Felipe Lemef0823852016-06-08 13:43:08 -07001803 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001804 final long token = Binder.clearCallingIdentity();
1805 try {
1806 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1807 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001808 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001809 }
1810 } finally {
1811 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001812 }
1813 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001814 }
1815
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001816 @Override
1817 public void addUidPolicy(int uid, int policy) {
1818 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001819
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001820 if (!UserHandle.isApp(uid)) {
1821 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1822 }
1823
Felipe Lemef0823852016-06-08 13:43:08 -07001824 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001825 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1826 policy |= oldPolicy;
1827 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001828 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001829 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001830 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001831 }
1832
1833 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001834 public void removeUidPolicy(int uid, int policy) {
1835 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1836
1837 if (!UserHandle.isApp(uid)) {
1838 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1839 }
1840
Felipe Lemef0823852016-06-08 13:43:08 -07001841 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001842 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1843 policy = oldPolicy & ~policy;
1844 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001845 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001846 }
1847 }
1848 }
1849
Felipe Lemef0823852016-06-08 13:43:08 -07001850 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1851 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001852
Felipe Leme57e3d312016-08-23 14:42:52 -07001853 final boolean notifyApp;
1854 if (!isUidValidForWhitelistRules(uid)) {
1855 notifyApp = false;
1856 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001857 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1858 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1859 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1860 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001861 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1862 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001863 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1864 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1865 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1866 if (LOGD)
1867 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1868 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1869 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001870 notifyApp = wasBlocked != isBlocked;
1871 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001872 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1873 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001874 }
1875
Felipe Lemef0823852016-06-08 13:43:08 -07001876 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001877 if (policy == POLICY_NONE) {
1878 mUidPolicy.delete(uid);
1879 } else {
1880 mUidPolicy.put(uid, policy);
1881 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001882
1883 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00001884 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001885 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001886 synchronized (mNetworkPoliciesSecondLock) {
1887 writePolicyAL();
1888 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001889 }
1890 }
1891
1892 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001893 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001894 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1895
Felipe Lemef0823852016-06-08 13:43:08 -07001896 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001897 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001898 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001899 }
1900
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001901 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001902 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001903 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1904
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001905 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001906 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001907 for (int i = 0; i < mUidPolicy.size(); i++) {
1908 final int uid = mUidPolicy.keyAt(i);
1909 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001910 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1911 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001912 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001913 }
1914 }
1915 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001916 return uids;
1917 }
1918
1919 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001920 * Removes any persistable state associated with given {@link UserHandle}, persisting
1921 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001922 */
Felipe Lemef0823852016-06-08 13:43:08 -07001923 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001924
Felipe Lemef0823852016-06-08 13:43:08 -07001925 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001926 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001927
Felipe Lemea110eec2016-04-29 09:58:06 -07001928 // Remove entries from revoked default restricted background UID whitelist
1929 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1930 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1931 if (UserHandle.getUserId(uid) == userId) {
1932 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001933 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001934 }
1935 }
1936
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001937 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001938 int[] uids = new int[0];
1939 for (int i = 0; i < mUidPolicy.size(); i++) {
1940 final int uid = mUidPolicy.keyAt(i);
1941 if (UserHandle.getUserId(uid) == userId) {
1942 uids = appendInt(uids, uid);
1943 }
1944 }
1945
1946 if (uids.length > 0) {
1947 for (int uid : uids) {
1948 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001949 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001950 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001951 }
Felipe Lemef0823852016-06-08 13:43:08 -07001952 synchronized (mNetworkPoliciesSecondLock) {
1953 updateRulesForGlobalChangeAL(true);
1954 if (writePolicy && changed) {
1955 writePolicyAL();
1956 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001957 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001958 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001959 }
1960
1961 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001962 public void setConnectivityListener(INetworkPolicyListener listener) {
1963 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1964 if (mConnectivityListener != null) {
1965 throw new IllegalStateException("Connectivity listener already registered");
1966 }
1967 mConnectivityListener = listener;
1968 }
1969
1970 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001971 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001972 // TODO: create permission for observing network policy
1973 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001974 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001975 }
1976
1977 @Override
1978 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001979 // TODO: create permission for observing network policy
1980 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001981 mListeners.unregister(listener);
1982 }
1983
Jeff Sharkey1b861272011-05-22 00:34:52 -07001984 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001985 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001986 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1987
Felipe Leme6a05eee2016-02-19 14:43:51 -08001988 final long token = Binder.clearCallingIdentity();
1989 try {
1990 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001991 synchronized (mUidRulesFirstLock) {
1992 synchronized (mNetworkPoliciesSecondLock) {
1993 normalizePoliciesNL(policies);
1994 updateNetworkEnabledNL();
1995 updateNetworkRulesNL();
1996 updateNotificationsNL();
1997 writePolicyAL();
1998 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001999 }
2000 } finally {
2001 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002002 }
2003 }
2004
Felipe Lemef0823852016-06-08 13:43:08 -07002005 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002006 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002007 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2008 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002009 }
2010
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002011 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002012 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002013 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002014 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002015 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2016 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2017 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002018 } catch (SecurityException e) {
2019 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002021 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2022 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2023 return new NetworkPolicy[0];
2024 }
Svet Ganov16a16892015-04-16 10:32:04 -07002025 }
2026
Felipe Lemef0823852016-06-08 13:43:08 -07002027 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002028 final int size = mNetworkPolicy.size();
2029 final NetworkPolicy[] policies = new NetworkPolicy[size];
2030 for (int i = 0; i < size; i++) {
2031 policies[i] = mNetworkPolicy.valueAt(i);
2032 }
2033 return policies;
2034 }
2035 }
2036
Felipe Lemef0823852016-06-08 13:43:08 -07002037 private void normalizePoliciesNL() {
2038 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002039 }
2040
Felipe Lemef0823852016-06-08 13:43:08 -07002041 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002042 final TelephonyManager tele = TelephonyManager.from(mContext);
2043 final String[] merged = tele.getMergedSubscriberIds();
2044
2045 mNetworkPolicy.clear();
2046 for (NetworkPolicy policy : policies) {
2047 // When two normalized templates conflict, prefer the most
2048 // restrictive policy
2049 policy.template = NetworkTemplate.normalize(policy.template, merged);
2050 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2051 if (existing == null || existing.compareTo(policy) > 0) {
2052 if (existing != null) {
2053 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2054 }
2055 mNetworkPolicy.put(policy.template, policy);
2056 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002057 }
2058 }
2059
2060 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002061 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002062 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002063
2064 final long token = Binder.clearCallingIdentity();
2065 try {
2066 performSnooze(template, TYPE_LIMIT);
2067 } finally {
2068 Binder.restoreCallingIdentity(token);
2069 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002070 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002071
Dianne Hackborn497175b2014-07-01 12:56:08 -07002072 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002073 maybeRefreshTrustedTime();
2074 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002075 synchronized (mUidRulesFirstLock) {
2076 synchronized (mNetworkPoliciesSecondLock) {
2077 // find and snooze local policy that matches
2078 final NetworkPolicy policy = mNetworkPolicy.get(template);
2079 if (policy == null) {
2080 throw new IllegalArgumentException("unable to find policy for " + template);
2081 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002082
Felipe Lemef0823852016-06-08 13:43:08 -07002083 switch (type) {
2084 case TYPE_WARNING:
2085 policy.lastWarningSnooze = currentTime;
2086 break;
2087 case TYPE_LIMIT:
2088 policy.lastLimitSnooze = currentTime;
2089 break;
2090 default:
2091 throw new IllegalArgumentException("unexpected type");
2092 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002093
Felipe Lemef0823852016-06-08 13:43:08 -07002094 normalizePoliciesNL();
2095 updateNetworkEnabledNL();
2096 updateNetworkRulesNL();
2097 updateNotificationsNL();
2098 writePolicyAL();
2099 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002100 }
2101 }
2102
2103 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002104 public void onTetheringChanged(String iface, boolean tethering) {
2105 // No need to enforce permission because setRestrictBackground() will do it.
2106 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002107 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002108 if (mRestrictBackground && tethering) {
2109 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2110 setRestrictBackground(false);
2111 }
2112 }
2113 }
2114
2115 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002116 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002117 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002118 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002119 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2120 final long token = Binder.clearCallingIdentity();
2121 try {
2122 maybeRefreshTrustedTime();
2123 synchronized (mUidRulesFirstLock) {
2124 if (restrictBackground == mRestrictBackground) {
2125 // Ideally, UI should never allow this scenario...
2126 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2127 return;
2128 }
2129 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002130 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002131
2132 } finally {
2133 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002134 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002135
Felipe Leme29e72ea2016-09-08 13:26:55 -07002136 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2137 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002138 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002139 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002140 }
2141 }
2142
Felipe Lemef0823852016-06-08 13:43:08 -07002143 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002144 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002145 final boolean oldRestrictBackground = mRestrictBackground;
2146 mRestrictBackground = restrictBackground;
2147 // Must whitelist foreground apps before turning data saver mode on.
2148 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2149 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002150 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002151 try {
2152 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2153 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2154 mRestrictBackground = oldRestrictBackground;
2155 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002156 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002157 return;
2158 }
2159 } catch (RemoteException e) {
2160 // ignored; service lives in system_server
2161 }
Felipe Lemef0823852016-06-08 13:43:08 -07002162 synchronized (mNetworkPoliciesSecondLock) {
2163 updateNotificationsNL();
2164 writePolicyAL();
2165 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002166 }
2167
Felipe Lemeb85a6372016-01-14 16:16:16 -08002168 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002169 public int getRestrictBackgroundByCaller() {
2170 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2171 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002172
Felipe Lemef0823852016-06-08 13:43:08 -07002173 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002174 // Must clear identity because getUidPolicy() is restricted to system.
2175 final long token = Binder.clearCallingIdentity();
2176 final int policy;
2177 try {
2178 policy = getUidPolicy(uid);
2179 } finally {
2180 Binder.restoreCallingIdentity(token);
2181 }
2182 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2183 // App is blacklisted.
2184 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2185 }
Felipe Leme1b103232016-01-22 09:44:57 -08002186 if (!mRestrictBackground) {
2187 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2188 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002189 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002190 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2191 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2192 }
2193 }
2194
2195 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002196 public boolean getRestrictBackground() {
2197 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2198
Felipe Lemef0823852016-06-08 13:43:08 -07002199 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002200 return mRestrictBackground;
2201 }
2202 }
2203
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002204 @Override
2205 public void setDeviceIdleMode(boolean enabled) {
2206 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002207 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2208 try {
2209 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002210 if (mDeviceIdleMode == enabled) {
2211 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002212 }
Felipe Lemeea014392016-09-06 13:59:54 -07002213 mDeviceIdleMode = enabled;
2214 if (mSystemReady) {
2215 // Device idle change means we need to rebuild rules for all
2216 // known apps, so do a global refresh.
2217 updateRulesForRestrictPowerUL();
2218 }
2219 }
2220 if (enabled) {
2221 EventLogTags.writeDeviceIdleOnPhase("net");
2222 } else {
2223 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002224 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002225 } finally {
2226 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002227 }
2228 }
2229
Felipe Lemef0823852016-06-08 13:43:08 -07002230 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002231 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2232 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002233 if (policy.template.matches(ident)) {
2234 return policy;
2235 }
2236 }
2237 return null;
2238 }
2239
2240 @Override
2241 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2242 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2243
2244 // only returns usage summary, so we don't require caller to have
2245 // READ_NETWORK_USAGE_HISTORY.
2246 final long token = Binder.clearCallingIdentity();
2247 try {
2248 return getNetworkQuotaInfoUnchecked(state);
2249 } finally {
2250 Binder.restoreCallingIdentity(token);
2251 }
2252 }
2253
2254 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2255 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2256
2257 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002258 synchronized (mNetworkPoliciesSecondLock) {
2259 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002260 }
2261
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002262 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002263 // missing policy means we can't derive useful quota info
2264 return null;
2265 }
2266
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002267 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002268
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002269 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002270 final long start = computeLastCycleBoundary(currentTime, policy);
2271 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002272 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002273
2274 // report soft and hard limits under policy
2275 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2276 : NetworkQuotaInfo.NO_LIMIT;
2277 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2278 : NetworkQuotaInfo.NO_LIMIT;
2279
2280 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2281 }
2282
Jeff Sharkey46645002011-07-27 21:11:21 -07002283 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002284 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002285 if (state.networkInfo == null) {
2286 return false;
2287 }
2288
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002289 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2290
2291 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002292 synchronized (mNetworkPoliciesSecondLock) {
2293 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002294 }
2295
2296 if (policy != null) {
2297 return policy.metered;
2298 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002299 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002300 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002301 return true;
2302 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002303 return false;
2304 }
2305 }
2306
2307 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002308 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002309 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002310
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002311 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2312
Dianne Hackborn497175b2014-07-01 12:56:08 -07002313 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002314 for (String arg : args) {
2315 argSet.add(arg);
2316 }
2317
Felipe Lemef0823852016-06-08 13:43:08 -07002318 synchronized (mUidRulesFirstLock) {
2319 synchronized (mNetworkPoliciesSecondLock) {
2320 if (argSet.contains("--unsnooze")) {
2321 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2322 mNetworkPolicy.valueAt(i).clearSnooze();
2323 }
2324
2325 normalizePoliciesNL();
2326 updateNetworkEnabledNL();
2327 updateNetworkRulesNL();
2328 updateNotificationsNL();
2329 writePolicyAL();
2330
2331 fout.println("Cleared snooze timestamps");
2332 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002333 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002334
Felipe Lemef0823852016-06-08 13:43:08 -07002335 fout.print("System ready: "); fout.println(mSystemReady);
2336 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2337 fout.print("Restrict power: "); fout.println(mRestrictPower);
2338 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2339 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002340 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002341 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2342 fout.println(mNetworkPolicy.valueAt(i).toString());
2343 }
2344 fout.decreaseIndent();
2345
2346 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2347
2348 fout.println("Policy for UIDs:");
2349 fout.increaseIndent();
2350 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002351 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002352 final int uid = mUidPolicy.keyAt(i);
2353 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002354 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002355 fout.print(uid);
2356 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002357 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002358 fout.println();
2359 }
2360 fout.decreaseIndent();
2361
2362 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2363 if (size > 0) {
2364 fout.println("Power save whitelist (except idle) app ids:");
2365 fout.increaseIndent();
2366 for (int i = 0; i < size; i++) {
2367 fout.print("UID=");
2368 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2369 fout.print(": ");
2370 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2371 fout.println();
2372 }
2373 fout.decreaseIndent();
2374 }
2375
2376 size = mPowerSaveWhitelistAppIds.size();
2377 if (size > 0) {
2378 fout.println("Power save whitelist app ids:");
2379 fout.increaseIndent();
2380 for (int i = 0; i < size; i++) {
2381 fout.print("UID=");
2382 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2383 fout.print(": ");
2384 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2385 fout.println();
2386 }
2387 fout.decreaseIndent();
2388 }
2389
Felipe Lemef0823852016-06-08 13:43:08 -07002390 size = mDefaultRestrictBackgroundWhitelistUids.size();
2391 if (size > 0) {
2392 fout.println("Default restrict background whitelist uids:");
2393 fout.increaseIndent();
2394 for (int i = 0; i < size; i++) {
2395 fout.print("UID=");
2396 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2397 fout.println();
2398 }
2399 fout.decreaseIndent();
2400 }
2401
2402 size = mRestrictBackgroundWhitelistRevokedUids.size();
2403 if (size > 0) {
2404 fout.println("Default restrict background whitelist uids revoked by users:");
2405 fout.increaseIndent();
2406 for (int i = 0; i < size; i++) {
2407 fout.print("UID=");
2408 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2409 fout.println();
2410 }
2411 fout.decreaseIndent();
2412 }
2413
2414 final SparseBooleanArray knownUids = new SparseBooleanArray();
2415 collectKeys(mUidState, knownUids);
2416 collectKeys(mUidRules, knownUids);
2417
2418 fout.println("Status for all known UIDs:");
2419 fout.increaseIndent();
2420 size = knownUids.size();
2421 for (int i = 0; i < size; i++) {
2422 final int uid = knownUids.keyAt(i);
2423 fout.print("UID=");
2424 fout.print(uid);
2425
2426 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2427 fout.print(" state=");
2428 fout.print(state);
2429 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2430 fout.print(" (fg)");
2431 } else {
2432 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2433 ? " (fg svc)" : " (bg)");
2434 }
2435
2436 final int uidRules = mUidRules.get(uid, RULE_NONE);
2437 fout.print(" rules=");
2438 fout.print(uidRulesToString(uidRules));
2439 fout.println();
2440 }
2441 fout.decreaseIndent();
2442
2443 fout.println("Status for just UIDs with rules:");
2444 fout.increaseIndent();
2445 size = mUidRules.size();
2446 for (int i = 0; i < size; i++) {
2447 final int uid = mUidRules.keyAt(i);
2448 fout.print("UID=");
2449 fout.print(uid);
2450 final int uidRules = mUidRules.get(uid, RULE_NONE);
2451 fout.print(" rules=");
2452 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002453 fout.println();
2454 }
2455 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002456
2457 fout.println("Observed uid state changes:");
2458 fout.increaseIndent();
2459 mObservedHistory.dumpUL(fout);
2460 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002461 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002462 }
2463 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002464
2465 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002466 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002467 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002468 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002469 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002470 }
2471
2472 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002473 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002474 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2475
Felipe Lemef0823852016-06-08 13:43:08 -07002476 synchronized (mUidRulesFirstLock) {
2477 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002478 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002479 }
2480
Felipe Lemef0823852016-06-08 13:43:08 -07002481 private boolean isUidForegroundUL(int uid) {
2482 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002483 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2484 }
2485
Felipe Lemef0823852016-06-08 13:43:08 -07002486 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002487 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002488 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002489 }
2490
Felipe Lemef0823852016-06-08 13:43:08 -07002491 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002492 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2493 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2494 }
2495
Felipe Lemef0823852016-06-08 13:43:08 -07002496 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002497 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002498 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002499 }
2500
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002501 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002502 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002503 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2504 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002505 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002506 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002507 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2508 try {
2509 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2510 if (oldUidState != uidState) {
2511 // state changed, push updated rules
2512 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002513 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2514 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2515 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2516 if (isUidIdle(uid)) {
2517 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002518 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002519 if (mDeviceIdleMode) {
2520 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002521 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002522 if (mRestrictPower) {
2523 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002524 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002525 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002526 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002527 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002528 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002529 } finally {
2530 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002531 }
2532 }
2533
Felipe Lemef0823852016-06-08 13:43:08 -07002534 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002535 final int index = mUidState.indexOfKey(uid);
2536 if (index >= 0) {
2537 final int oldUidState = mUidState.valueAt(index);
2538 mUidState.removeAt(index);
2539 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002540 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002541 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002542 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002543 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002544 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002545 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002546 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002547 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002548 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002549 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002550 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002551 }
2552 }
2553
Felipe Lemef28983d2016-03-25 12:18:23 -07002554 // adjust stats accounting based on foreground status
2555 private void updateNetworkStats(int uid, boolean uidForeground) {
2556 try {
2557 mNetworkStats.setUidForeground(uid, uidForeground);
2558 } catch (RemoteException e) {
2559 // ignored; service lives in system_server
2560 }
2561 }
2562
Sudheer Shankac9d94072017-02-22 22:13:55 +00002563 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2564 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002565 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002566 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002567 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002568 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002569 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002570 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002571 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002572 }
2573
Felipe Lemef0823852016-06-08 13:43:08 -07002574 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002575 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2576 try {
2577 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2578 mUidFirewallPowerSaveRules);
2579 } finally {
2580 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2581 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002582 }
2583
Felipe Lemef0823852016-06-08 13:43:08 -07002584 void updateRuleForRestrictPowerUL(int uid) {
2585 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002586 }
2587
Felipe Lemef0823852016-06-08 13:43:08 -07002588 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002589 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2590 try {
2591 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2592 mUidFirewallDozableRules);
2593 } finally {
2594 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2595 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002596 }
2597
Felipe Lemef0823852016-06-08 13:43:08 -07002598 void updateRuleForDeviceIdleUL(int uid) {
2599 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002600 }
2601
Felipe Lemef28983d2016-03-25 12:18:23 -07002602 // NOTE: since both fw_dozable and fw_powersave uses the same map
2603 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002604 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002605 SparseIntArray rules) {
2606 if (enabled) {
2607 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002608 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002609 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002610 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002611 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002612 for (int ui = users.size() - 1; ui >= 0; ui--) {
2613 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002614 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002615 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2616 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2617 int uid = UserHandle.getUid(user.id, appId);
2618 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2619 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002620 }
2621 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2622 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2623 int uid = UserHandle.getUid(user.id, appId);
2624 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2625 }
2626 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002627 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002628 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002629 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2630 }
2631 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002632 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2633 } else {
2634 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002635 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002636 }
2637
Felipe Lemef0823852016-06-08 13:43:08 -07002638 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002639 final int appId = UserHandle.getAppId(uid);
2640 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2641 }
2642
Felipe Lemef28983d2016-03-25 12:18:23 -07002643 // NOTE: since both fw_dozable and fw_powersave uses the same map
2644 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002645 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002646 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002647 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002648 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002649 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002650 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002651 }
2652 }
2653 }
2654
Felipe Lemef0823852016-06-08 13:43:08 -07002655 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002656 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2657 try {
2658 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2659 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002660
Felipe Leme873a83a2016-09-07 11:34:10 -07002661 // Fully update the app idle firewall chain.
2662 final List<UserInfo> users = mUserManager.getUsers();
2663 for (int ui = users.size() - 1; ui >= 0; ui--) {
2664 UserInfo user = users.get(ui);
2665 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2666 for (int uid : idleUids) {
2667 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2668 // quick check: if this uid doesn't have INTERNET permission, it
2669 // doesn't have network access anyway, so it is a waste to mess
2670 // with it here.
2671 if (hasInternetPermissions(uid)) {
2672 uidRules.put(uid, FIREWALL_RULE_DENY);
2673 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002674 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002675 }
2676 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002677
Felipe Lemebc853dd2016-09-08 13:26:55 -07002678 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002679 } finally {
2680 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2681 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002682 }
2683
Felipe Lemef0823852016-06-08 13:43:08 -07002684 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002685 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002686
2687 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002688 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002689 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002690 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2691 } else {
2692 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2693 }
2694 }
2695
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002696 /**
2697 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2698 * changed.
2699 */
Felipe Lemef0823852016-06-08 13:43:08 -07002700 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002701 boolean paroled = mUsageStats.isAppIdleParoleOn();
2702 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002703 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002704
2705 int ruleCount = mUidFirewallStandbyRules.size();
2706 for (int i = 0; i < ruleCount; i++) {
2707 int uid = mUidFirewallStandbyRules.keyAt(i);
2708 int oldRules = mUidRules.get(uid);
2709 if (enableChain) {
2710 // Chain wasn't enabled before and the other power-related
2711 // chains are whitelists, so we can clear the
2712 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2713 // the effective rules result in blocking network access.
2714 oldRules &= MASK_METERED_NETWORKS;
2715 } else {
2716 // Skip if it had no restrictions to begin with
2717 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2718 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002719 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002720 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002721 }
2722
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002723 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002724 * Update rules that might be changed by {@link #mRestrictBackground},
2725 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002726 */
Felipe Lemef0823852016-06-08 13:43:08 -07002727 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002728 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2729 try {
Felipe Leme09700462016-09-08 09:33:48 -07002730 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002731 updateRulesForRestrictPowerUL();
2732 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002733
Felipe Leme873a83a2016-09-07 11:34:10 -07002734 // If the set of restricted networks may have changed, re-evaluate those.
2735 if (restrictedNetworksChanged) {
2736 normalizePoliciesNL();
2737 updateNetworkRulesNL();
2738 }
2739 } finally {
2740 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002741 }
2742 }
2743
Felipe Leme09700462016-09-08 09:33:48 -07002744 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002745 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002746 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2747 try {
2748 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002749 updateRulesForPowerSaveUL();
2750 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2751 } finally {
2752 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2753 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002754 }
2755
Felipe Lemef0823852016-06-08 13:43:08 -07002756 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002757 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2758 try {
2759 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2760 } finally {
2761 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2762 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002763 }
2764
2765 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2766 private static final int TYPE_RESTRICT_POWER = 2;
2767 @Retention(RetentionPolicy.SOURCE)
2768 @IntDef(flag = false, value = {
2769 TYPE_RESTRICT_BACKGROUND,
2770 TYPE_RESTRICT_POWER,
2771 })
2772 public @interface RestrictType {
2773 }
2774
2775 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002776 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002777 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2778 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2779 }
2780 try {
2781 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002782
Felipe Leme873a83a2016-09-07 11:34:10 -07002783 // update rules for all installed applications
2784 final List<UserInfo> users = mUserManager.getUsers();
2785 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002786 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
Felipe Leme873a83a2016-09-07 11:34:10 -07002787 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2788 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002789
Felipe Leme873a83a2016-09-07 11:34:10 -07002790 final int usersSize = users.size();
2791 final int appsSize = apps.size();
2792 for (int i = 0; i < usersSize; i++) {
2793 final UserInfo user = users.get(i);
2794 for (int j = 0; j < appsSize; j++) {
2795 final ApplicationInfo app = apps.get(j);
2796 final int uid = UserHandle.getUid(user.id, app.uid);
2797 switch (type) {
2798 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002799 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002800 break;
2801 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002802 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002803 break;
2804 default:
2805 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2806 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002807 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002808 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002809 } finally {
2810 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2811 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2812 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002813 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002814 }
2815
Felipe Lemef0823852016-06-08 13:43:08 -07002816 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002817 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002818 for (int i = 0; i < users.size(); i++) {
2819 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002820 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002821 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002822 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002823 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002824 updateRuleForAppIdleUL(uid);
2825 updateRuleForDeviceIdleUL(uid);
2826 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002827 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002828 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002829 }
2830 }
2831 }
2832
Felipe Leme70c57c22016-03-29 10:45:13 -07002833 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2834 // methods below could be merged into a isUidValidForRules() method.
2835 private boolean isUidValidForBlacklistRules(int uid) {
2836 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002837 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002838 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002839 return true;
2840 }
2841
2842 return false;
2843 }
2844
Felipe Leme70c57c22016-03-29 10:45:13 -07002845 private boolean isUidValidForWhitelistRules(int uid) {
2846 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2847 }
2848
Amith Yamasani15e472352015-04-24 19:06:07 -07002849 private boolean isUidIdle(int uid) {
2850 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2851 final int userId = UserHandle.getUserId(uid);
2852
songjinshi0655edd2016-05-18 19:55:32 +08002853 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002854 for (String packageName : packages) {
2855 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2856 return false;
2857 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002858 }
2859 }
2860 return true;
2861 }
2862
2863 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002864 * Checks if an uid has INTERNET permissions.
2865 * <p>
2866 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002867 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002868 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002869 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002870 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002871 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002872 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002873 }
2874 } catch (RemoteException e) {
2875 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002876 return true;
2877 }
2878
2879 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002880 * Clears all state - internal and external - associated with an UID.
2881 */
2882 private void onUidDeletedUL(int uid) {
2883 // First cleanup in-memory state synchronously...
2884 mUidRules.delete(uid);
2885 mUidPolicy.delete(uid);
2886 mUidFirewallStandbyRules.delete(uid);
2887 mUidFirewallDozableRules.delete(uid);
2888 mUidFirewallPowerSaveRules.delete(uid);
2889 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2890 mPowerSaveWhitelistAppIds.delete(uid);
2891 mPowerSaveTempWhitelistAppIds.delete(uid);
2892
2893 // ...then update iptables asynchronously.
2894 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2895 }
2896
2897 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002898 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002899 *
Felipe Leme781ba142016-05-09 16:24:48 -07002900 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002901 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002902 * <li>Doze mode
2903 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002904 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002905 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002906 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002907 *
2908 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002909 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002910 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002911 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002912 updateRuleForDeviceIdleUL(uid);
2913 updateRuleForAppIdleUL(uid);
2914 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002915
2916 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002917 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002918
2919 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002920 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002921 }
2922
Felipe Leme70c57c22016-03-29 10:45:13 -07002923 /**
2924 * Applies network rules to bandwidth controllers based on process state and user-defined
2925 * restrictions (blacklist / whitelist).
2926 *
2927 * <p>
2928 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2929 * networks:
2930 * <ul>
2931 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2932 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2933 * also blacklisted.
2934 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2935 * no UIDs other those whitelisted will have access.
2936 * <ul>
2937 *
2938 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2939 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2940 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2941 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002942 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002943 * {@link INetworkManagementService}, but this method should also be called in events (like
2944 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2945 * following rules should also be applied:
2946 *
2947 * <ul>
2948 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2949 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2950 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2951 * {@code bw_penalty_box}.
2952 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2953 * </ul>
2954 *
2955 * <p>For optimization, the rules are only applied on user apps that have internet access
2956 * permission, since there is no need to change the {@code iptables} rule if the app does not
2957 * have permission to use the internet.
2958 *
2959 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002960 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002961 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002962 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07002963 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002964 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002965 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07002966 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002967
Dianne Hackborn497175b2014-07-01 12:56:08 -07002968 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002969 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002970 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002971
Felipe Leme781ba142016-05-09 16:24:48 -07002972 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002973 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002974 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2975 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002976
Felipe Leme70c57c22016-03-29 10:45:13 -07002977 // First step: define the new rule based on user restrictions and foreground state.
2978 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002979 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2980 newRule = RULE_TEMPORARY_ALLOW_METERED;
2981 } else if (isWhitelisted) {
2982 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002983 }
2984 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002985 if (isBlacklisted) {
2986 newRule = RULE_REJECT_METERED;
2987 } else if (mRestrictBackground && isWhitelisted) {
2988 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002989 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002990 }
Felipe Leme781ba142016-05-09 16:24:48 -07002991 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002992
Felipe Lemef28983d2016-03-25 12:18:23 -07002993 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002994 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002995 + ": isForeground=" +isForeground
2996 + ", isBlacklisted=" + isBlacklisted
2997 + ", isWhitelisted=" + isWhitelisted
2998 + ", oldRule=" + uidRulesToString(oldRule)
2999 + ", newRule=" + uidRulesToString(newRule)
3000 + ", newUidRules=" + uidRulesToString(newUidRules)
3001 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003002 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003003
Felipe Leme46c4fc32016-05-04 09:21:43 -07003004 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003005 mUidRules.delete(uid);
3006 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003007 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003008 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003009
Felipe Leme70c57c22016-03-29 10:45:13 -07003010 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003011 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07003012 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003013 // Temporarily whitelist foreground app, removing from blacklist if necessary
3014 // (since bw_penalty_box prevails over bw_happy_box).
3015
3016 setMeteredNetworkWhitelist(uid, true);
3017 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3018 // but ideally it should be just:
3019 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003020 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003021 setMeteredNetworkBlacklist(uid, false);
3022 }
Felipe Leme781ba142016-05-09 16:24:48 -07003023 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003024 // Remove temporary whitelist from app that is not on foreground anymore.
3025
3026 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3027 // but ideally they should be just:
3028 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3029 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003030 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003031 setMeteredNetworkWhitelist(uid, false);
3032 }
Felipe Leme781ba142016-05-09 16:24:48 -07003033 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003034 setMeteredNetworkBlacklist(uid, true);
3035 }
Felipe Leme781ba142016-05-09 16:24:48 -07003036 } else if ((newRule & RULE_REJECT_METERED) != 0
3037 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003038 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003039 setMeteredNetworkBlacklist(uid, isBlacklisted);
3040 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003041 // Since blacklist prevails over whitelist, we need to handle the special case
3042 // where app is whitelisted and blacklisted at the same time (although such
3043 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003044 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003045 }
Felipe Leme781ba142016-05-09 16:24:48 -07003046 } else if ((newRule & RULE_ALLOW_METERED) != 0
3047 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003048 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003049 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003050 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003051 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003052 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3053 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003054 + ", whitelisted=" + isWhitelisted
3055 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003056 + ", newRule=" + uidRulesToString(newUidRules)
3057 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003058 }
Felipe Leme781ba142016-05-09 16:24:48 -07003059
Sudheer Shankac9d94072017-02-22 22:13:55 +00003060 // Dispatch changed rule to existing listeners.
3061 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003062 }
3063 }
3064
3065 /**
3066 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3067 * listeners in case of change.
3068 * <p>
3069 * There are 3 power-related rules that affects whether an app has background access on
3070 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3071 * restriction, it's added to the equivalent firewall chain:
3072 * <ul>
3073 * <li>App is idle: {@code fw_standby} firewall chain.
3074 * <li>Device is idle: {@code fw_dozable} firewall chain.
3075 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3076 * </ul>
3077 * <p>
3078 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3079 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3080 * <p>
3081 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3082 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003083 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003084 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3085
Sudheer Shankac9d94072017-02-22 22:13:55 +00003086 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003087
Sudheer Shankac9d94072017-02-22 22:13:55 +00003088 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003089 mUidRules.delete(uid);
3090 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003091 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003092 }
3093 }
3094
3095 /**
3096 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3097 *
3098 * @param uid the uid of the app to update rules for
3099 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3100 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3101 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003102 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003103 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003104 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003105 if (!isUidValidForBlacklistRules(uid)) {
3106 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003107 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003108 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003109
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003110 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003111 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003112 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003113
Felipe Lemef0823852016-06-08 13:43:08 -07003114 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003115 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3116 int newRule = RULE_NONE;
3117
3118 // First step: define the new rule based on user restrictions and foreground state.
3119
3120 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3121 // by considering the foreground and non-foreground states.
3122 if (isForeground) {
3123 if (restrictMode) {
3124 newRule = RULE_ALLOW_ALL;
3125 }
3126 } else if (restrictMode) {
3127 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3128 }
3129
3130 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3131
3132 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003133 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003134 + ", isIdle: " + isIdle
3135 + ", mRestrictPower: " + mRestrictPower
3136 + ", mDeviceIdleMode: " + mDeviceIdleMode
3137 + ", isForeground=" + isForeground
3138 + ", isWhitelisted=" + isWhitelisted
3139 + ", oldRule=" + uidRulesToString(oldRule)
3140 + ", newRule=" + uidRulesToString(newRule)
3141 + ", newUidRules=" + uidRulesToString(newUidRules)
3142 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3143 }
3144
Felipe Leme781ba142016-05-09 16:24:48 -07003145 // Second step: notify listeners if state changed.
3146 if (newRule != oldRule) {
3147 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003148 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003149 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003150 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3151 } else {
3152 // All scenarios should have been covered above
3153 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3154 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003155 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003156 + ", newRule=" + uidRulesToString(newUidRules)
3157 + ", oldRule=" + uidRulesToString(oldUidRules));
3158 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003159 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003160 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003161
Sudheer Shankac9d94072017-02-22 22:13:55 +00003162 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003163 }
3164
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003165 private class AppIdleStateChangeListener
3166 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3167
3168 @Override
3169 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3170 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003171 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3172 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003173 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003174 synchronized (mUidRulesFirstLock) {
3175 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003176 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003177 }
3178 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003179 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003180 }
3181
3182 @Override
3183 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003184 synchronized (mUidRulesFirstLock) {
3185 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003186 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003187 }
3188 }
3189
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003190 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3191 if (listener != null) {
3192 try {
3193 listener.onUidRulesChanged(uid, uidRules);
3194 } catch (RemoteException ignored) {
3195 }
3196 }
3197 }
3198
3199 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3200 String[] meteredIfaces) {
3201 if (listener != null) {
3202 try {
3203 listener.onMeteredIfacesChanged(meteredIfaces);
3204 } catch (RemoteException ignored) {
3205 }
3206 }
3207 }
3208
3209 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3210 boolean restrictBackground) {
3211 if (listener != null) {
3212 try {
3213 listener.onRestrictBackgroundChanged(restrictBackground);
3214 } catch (RemoteException ignored) {
3215 }
3216 }
3217 }
3218
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003219 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3220 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003221 if (listener != null) {
3222 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003223 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003224 } catch (RemoteException ignored) {
3225 }
3226 }
3227 }
3228
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003229 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003230 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003231 public boolean handleMessage(Message msg) {
3232 switch (msg.what) {
3233 case MSG_RULES_CHANGED: {
3234 final int uid = msg.arg1;
3235 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003236 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
3237 final int length = mListeners.beginBroadcast();
3238 for (int i = 0; i < length; i++) {
3239 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3240 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003241 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003242 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003243 return true;
3244 }
3245 case MSG_METERED_IFACES_CHANGED: {
3246 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003247 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003248 final int length = mListeners.beginBroadcast();
3249 for (int i = 0; i < length; i++) {
3250 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003251 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003252 }
3253 mListeners.finishBroadcast();
3254 return true;
3255 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003256 case MSG_LIMIT_REACHED: {
3257 final String iface = (String) msg.obj;
3258
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003259 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003260 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003261 if (mMeteredIfaces.contains(iface)) {
3262 try {
3263 // force stats update to make sure we have
3264 // numbers that caused alert to trigger.
3265 mNetworkStats.forceUpdate();
3266 } catch (RemoteException e) {
3267 // ignored; service lives in system_server
3268 }
3269
Felipe Lemef0823852016-06-08 13:43:08 -07003270 updateNetworkEnabledNL();
3271 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003272 }
3273 }
3274 return true;
3275 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003276 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3277 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003278 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003279 final int length = mListeners.beginBroadcast();
3280 for (int i = 0; i < length; i++) {
3281 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003282 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003283 }
3284 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003285 final Intent intent =
3286 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3287 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3288 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3289 return true;
3290 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003291 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003292 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003293 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003294 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003295 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003296 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003297 final int length = mListeners.beginBroadcast();
3298 for (int i = 0; i < length; i++) {
3299 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003300 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003301 }
3302 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003303 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3304 if (notifyApp.booleanValue()) {
3305 broadcastRestrictBackgroundChanged(uid, notifyApp);
3306 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003307 return true;
3308 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003309 case MSG_ADVISE_PERSIST_THRESHOLD: {
3310 final long lowestRule = (Long) msg.obj;
3311 try {
3312 // make sure stats are recorded frequently enough; we aim
3313 // for 2MB threshold for 2GB/month rules.
3314 final long persistThreshold = lowestRule / 1000;
3315 mNetworkStats.advisePersistThreshold(persistThreshold);
3316 } catch (RemoteException e) {
3317 // ignored; service lives in system_server
3318 }
3319 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003320 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003321 case MSG_UPDATE_INTERFACE_QUOTA: {
3322 removeInterfaceQuota((String) msg.obj);
3323 // int params need to be stitched back into a long
3324 setInterfaceQuota((String) msg.obj,
3325 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3326 return true;
3327 }
3328 case MSG_REMOVE_INTERFACE_QUOTA: {
3329 removeInterfaceQuota((String) msg.obj);
3330 return true;
3331 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003332 case MSG_SET_FIREWALL_RULES: {
3333 final int chain = msg.arg1;
3334 final int toggle = msg.arg2;
3335 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3336 if (uidRules != null) {
3337 setUidFirewallRules(chain, uidRules);
3338 }
3339 if (toggle != CHAIN_TOGGLE_NONE) {
3340 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3341 }
3342 return true;
3343 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003344 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3345 resetUidFirewallRules(msg.arg1);
3346 return true;
3347 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003348 default: {
3349 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003350 }
3351 }
3352 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003353
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003354 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003355
Felipe Leme57e3d312016-08-23 14:42:52 -07003356 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3357 final PackageManager pm = mContext.getPackageManager();
3358 final String[] packages = pm.getPackagesForUid(uid);
3359 if (packages != null) {
3360 final int userId = UserHandle.getUserId(uid);
3361 for (String packageName : packages) {
3362 final Intent intent =
3363 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3364 intent.setPackage(packageName);
3365 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3366 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3367 }
3368 }
3369 }
3370
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003371 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003372 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003373 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003374 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003375 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003376 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003377 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003378 }
3379 }
3380
3381 private void removeInterfaceQuota(String iface) {
3382 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003383 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003384 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003385 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003386 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003387 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003388 }
3389 }
3390
Felipe Leme70c57c22016-03-29 10:45:13 -07003391 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3392 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003393 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003394 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003395 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003396 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3397 } catch (RemoteException e) {
3398 // ignored; service lives in system_server
3399 }
3400 }
3401
3402 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3403 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3404 try {
3405 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3406 } catch (IllegalStateException e) {
3407 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003408 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003409 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003410 }
3411 }
3412
Felipe Lemebc853dd2016-09-08 13:26:55 -07003413 private static final int CHAIN_TOGGLE_NONE = 0;
3414 private static final int CHAIN_TOGGLE_ENABLE = 1;
3415 private static final int CHAIN_TOGGLE_DISABLE = 2;
3416 @Retention(RetentionPolicy.SOURCE)
3417 @IntDef(flag = false, value = {
3418 CHAIN_TOGGLE_NONE,
3419 CHAIN_TOGGLE_ENABLE,
3420 CHAIN_TOGGLE_DISABLE
3421 })
3422 public @interface ChainToggleType {
3423 }
3424
3425 /**
3426 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3427 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3428 *
3429 * @param chain firewall chain.
3430 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3431 * @param toggle whether the chain should be enabled, disabled, or not changed.
3432 */
3433 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3434 @ChainToggleType int toggle) {
3435 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3436 }
3437
Amith Yamasani15e472352015-04-24 19:06:07 -07003438 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003439 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3440 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3441 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003442 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003443 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003444 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003445 int size = uidRules.size();
3446 int[] uids = new int[size];
3447 int[] rules = new int[size];
3448 for(int index = size - 1; index >= 0; --index) {
3449 uids[index] = uidRules.keyAt(index);
3450 rules[index] = uidRules.valueAt(index);
3451 }
3452 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003453 } catch (IllegalStateException e) {
3454 Log.wtf(TAG, "problem setting firewall uid rules", e);
3455 } catch (RemoteException e) {
3456 // ignored; service lives in system_server
3457 }
3458 }
3459
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003460 /**
3461 * Add or remove a uid to the firewall blacklist for all network ifaces.
3462 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003463 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003464 if (chain == FIREWALL_CHAIN_DOZABLE) {
3465 mUidFirewallDozableRules.put(uid, rule);
3466 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3467 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003468 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3469 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003470 }
3471
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003472 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003473 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003474 } catch (IllegalStateException e) {
3475 Log.wtf(TAG, "problem setting firewall uid rules", e);
3476 } catch (RemoteException e) {
3477 // ignored; service lives in system_server
3478 }
3479 }
3480
3481 /**
3482 * Add or remove a uid to the firewall blacklist for all network ifaces.
3483 */
Felipe Lemef0823852016-06-08 13:43:08 -07003484 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003485 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3486 mFirewallChainStates.get(chain) == enable) {
3487 // All is the same, nothing to do.
3488 return;
3489 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003490 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003491 try {
3492 mNetworkManager.setFirewallChainEnabled(chain, enable);
3493 } catch (IllegalStateException e) {
3494 Log.wtf(TAG, "problem enable firewall chain", e);
3495 } catch (RemoteException e) {
3496 // ignored; service lives in system_server
3497 }
3498 }
3499
Felipe Leme03e95e22016-09-09 09:25:31 -07003500 /**
3501 * Resets all firewall rules associated with an UID.
3502 */
3503 private void resetUidFirewallRules(int uid) {
3504 try {
3505 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3506 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3507 mNetworkManager
3508 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3509 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3510 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3511 } catch (IllegalStateException e) {
3512 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3513 } catch (RemoteException e) {
3514 // ignored; service lives in system_server
3515 }
3516 }
3517
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003518 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3519 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003520 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003521 } catch (RuntimeException e) {
3522 Slog.w(TAG, "problem reading network stats: " + e);
3523 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003524 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003525 // ignored; service lives in system_server
3526 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003527 }
3528 }
3529
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003530 private boolean isBandwidthControlEnabled() {
3531 final long token = Binder.clearCallingIdentity();
3532 try {
3533 return mNetworkManager.isBandwidthControlEnabled();
3534 } catch (RemoteException e) {
3535 // ignored; service lives in system_server
3536 return false;
3537 } finally {
3538 Binder.restoreCallingIdentity(token);
3539 }
3540 }
3541
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003542 /**
3543 * Try refreshing {@link #mTime} when stale.
3544 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003545 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003546 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003547 mTime.forceRefresh();
3548 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003549 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003550
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003551 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003552 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3553 }
3554
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003555 private static Intent buildAllowBackgroundDataIntent() {
3556 return new Intent(ACTION_ALLOW_BACKGROUND);
3557 }
3558
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003559 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3560 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3561 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3562 return intent;
3563 }
3564
Wei Liu546cb772016-07-21 16:19:01 -07003565 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003566 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003567 intent.setComponent(ComponentName.unflattenFromString(
3568 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003569 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3570 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3571 return intent;
3572 }
3573
Wei Liu546cb772016-07-21 16:19:01 -07003574 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003575 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003576 intent.setComponent(ComponentName.unflattenFromString(
3577 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003578 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3579 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3580 return intent;
3581 }
3582
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003583 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003584 public void addIdleHandler(IdleHandler handler) {
3585 mHandler.getLooper().getQueue().addIdleHandler(handler);
3586 }
3587
Jeff Sharkey1b861272011-05-22 00:34:52 -07003588 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3589 final int size = source.size();
3590 for (int i = 0; i < size; i++) {
3591 target.put(source.keyAt(i), true);
3592 }
3593 }
3594
Stuart Scottf1fb3972015-04-02 18:00:02 -07003595 @Override
3596 public void factoryReset(String subscriber) {
3597 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3598
Stuart Scotte3e314d2015-04-20 14:07:45 -07003599 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3600 return;
3601 }
3602
Stuart Scottf1fb3972015-04-02 18:00:02 -07003603 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003604 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003605 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3606 for (NetworkPolicy policy : policies) {
3607 if (policy.template.equals(template)) {
3608 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3609 policy.inferred = false;
3610 policy.clearSnooze();
3611 }
3612 }
3613 setNetworkPolicies(policies);
3614
3615 // Turn restrict background data off
3616 setRestrictBackground(false);
3617
Stuart Scotte3e314d2015-04-20 14:07:45 -07003618 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3619 // Remove app's "restrict background data" flag
3620 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3621 setUidPolicy(uid, POLICY_NONE);
3622 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003623 }
3624 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003625
Felipe Lemed17fda42016-04-29 11:12:45 -07003626 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3627
3628 @Override
3629 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003630 synchronized (mUidRulesFirstLock) {
3631 boolean changed = removeUserStateUL(userId, false);
3632 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003633 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003634 synchronized (mNetworkPoliciesSecondLock) {
3635 writePolicyAL();
3636 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003637 }
3638 }
3639 }
3640 }
Sudheer Shankae7361852017-03-07 11:51:46 -08003641
3642 /**
3643 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
3644 * (uid, procStateSeq) pairs.
3645 */
3646 @VisibleForTesting
3647 public static final class ProcStateSeqHistory {
3648 private static final int INVALID_UID = -1;
3649
3650 /**
3651 * Denotes maximum number of items this history can hold.
3652 */
3653 private final int mMaxCapacity;
3654 /**
3655 * Used for storing the uid information.
3656 */
3657 private final int[] mUids;
3658 /**
3659 * Used for storing the sequence numbers associated with {@link #mUids}.
3660 */
3661 private final long[] mProcStateSeqs;
3662 /**
3663 * Points to the next available slot for writing (uid, procStateSeq) pair.
3664 */
3665 private int mHistoryNext;
3666
3667 public ProcStateSeqHistory(int maxCapacity) {
3668 mMaxCapacity = maxCapacity;
3669 mUids = new int[mMaxCapacity];
3670 Arrays.fill(mUids, INVALID_UID);
3671 mProcStateSeqs = new long[mMaxCapacity];
3672 }
3673
3674 @GuardedBy("mUidRulesFirstLock")
3675 public void addProcStateSeqUL(int uid, long procStateSeq) {
3676 mUids[mHistoryNext] = uid;
3677 mProcStateSeqs[mHistoryNext] = procStateSeq;
3678 mHistoryNext = increaseNext(mHistoryNext, 1);
3679 }
3680
3681 @GuardedBy("mUidRulesFirstLock")
3682 public void dumpUL(IndentingPrintWriter fout) {
3683 if (mUids[0] == INVALID_UID) {
3684 fout.println("NONE");
3685 return;
3686 }
3687 int index = mHistoryNext;
3688 do {
3689 index = increaseNext(index, -1);
3690 if (mUids[index] == INVALID_UID) {
3691 break;
3692 }
3693 fout.println(getString(mUids[index], mProcStateSeqs[index]));
3694 } while (index != mHistoryNext);
3695 }
3696
3697 public static String getString(int uid, long procStateSeq) {
3698 return "UID=" + uid + " procStateSeq=" + procStateSeq;
3699 }
3700
3701 private int increaseNext(int next, int increment) {
3702 next += increment;
3703 if (next >= mMaxCapacity) {
3704 next = 0;
3705 } else if (next < 0) {
3706 next = mMaxCapacity - 1;
3707 }
3708 return next;
3709 }
3710 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003711}