blob: fc45344b2f4dbd00c4b9536f40579656a8ea87f4 [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;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800325 @GuardedBy("mUidRulesFirstLock")
326 private PowerSaveState mRestrictBackgroundPowerState;
327
328 // Store the status of restrict background before turning on battery saver.
329 // Used to restore mRestrictBackground when battery saver is turned off.
330 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700331
Felipe Lemef0823852016-06-08 13:43:08 -0700332 // See main javadoc for instructions on how to use these locks.
333 final Object mUidRulesFirstLock = new Object();
334 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700335
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("allLocks") volatile boolean mSystemReady;
337
Felipe Lemef0823852016-06-08 13:43:08 -0700338 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
339 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
340 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800341 // Store whether user flipped restrict background in battery saver mode
342 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700343
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700344 private final boolean mSuppressDefaultPolicy;
345
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700346 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800347 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700348 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700350
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700351 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700352 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700353 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700354 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700355
Felipe Lemef0823852016-06-08 13:43:08 -0700356 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700357 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700358 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700359 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700360 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800361 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700362
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700363 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700365 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
366
Jeff Sharkey32566012014-12-02 18:30:14 -0800367 /**
368 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700369 * in power save mode, except device idle (doze) still applies.
370 * TODO: An int array might be sufficient
371 */
Felipe Lemef0823852016-06-08 13:43:08 -0700372 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700373 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
374
375 /**
376 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800377 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700378 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800379 */
Felipe Lemef0823852016-06-08 13:43:08 -0700380 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700381 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700382
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700384 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
385
Felipe Lemeb85a6372016-01-14 16:16:16 -0800386 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800387 * UIDs that have been initially white-listed by system to avoid restricted background.
388 */
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800390 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
391 new SparseBooleanArray();
392
393 /**
394 * UIDs that have been initially white-listed by system to avoid restricted background,
395 * but later revoked by user.
396 */
Felipe Lemef0823852016-06-08 13:43:08 -0700397 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800398 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
399 new SparseBooleanArray();
400
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700401 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700402 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800403 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700404 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700405 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800406 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700407
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700408 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700409 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700410 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700411
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700412 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700413 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800414 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700415
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600416 /** Higher priority listener before general event dispatch */
417 private INetworkPolicyListener mConnectivityListener;
418
Jeff Sharkey32566012014-12-02 18:30:14 -0800419 private final RemoteCallbackList<INetworkPolicyListener>
420 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700421
Dianne Hackborn497175b2014-07-01 12:56:08 -0700422 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700423
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700425 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700426
Svet Ganov16a16892015-04-16 10:32:04 -0700427 private final AppOpsManager mAppOps;
428
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800429 private final IPackageManager mIPm;
430
Sudheer Shankae7361852017-03-07 11:51:46 -0800431 private ActivityManagerInternal mActivityManagerInternal;
432
433 /**
434 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
435 * the uid and procStateSeq will be written to this and will be printed as part of dump.
436 */
437 @VisibleForTesting
438 public ProcStateSeqHistory mObservedHistory
439 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800440
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700441 // TODO: keep whitelist of system-critical services that should never have
442 // rules enforced, such as system, phone, and radio UIDs.
443
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700444 // TODO: migrate notifications to SystemUI
445
Jeff Sharkey75279902011-05-24 18:39:45 -0700446 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700447 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
448 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700449 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
450 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700451 }
452
453 private static File getSystemDir() {
454 return new File(Environment.getDataDirectory(), "system");
455 }
456
457 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700458 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700459 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700460 mContext = checkNotNull(context, "missing context");
461 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700462 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700463 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700464 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700465 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700466 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700467 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700468 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700469
Amith Yamasani450a16b2013-09-18 16:28:50 -0700470 HandlerThread thread = new HandlerThread(TAG);
471 thread.start();
472 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700473
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700474 mSuppressDefaultPolicy = suppressDefaultPolicy;
475
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700476 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700477
478 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800479
Felipe Lemed17fda42016-04-29 11:12:45 -0700480 // Expose private service for system components to use.
481 LocalServices.addService(NetworkPolicyManagerInternal.class,
482 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700483 }
484
485 public void bindConnectivityManager(IConnectivityManager connManager) {
486 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700487 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700488
Jeff Sharkey497e4432011-06-14 17:27:29 -0700489 public void bindNotificationManager(INotificationManager notifManager) {
490 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
491 }
492
Felipe Lemef0823852016-06-08 13:43:08 -0700493 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700494 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700495 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
496 mPowerSaveWhitelistExceptIdleAppIds.clear();
497 if (whitelist != null) {
498 for (int uid : whitelist) {
499 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
500 }
501 }
502 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700503 mPowerSaveWhitelistAppIds.clear();
504 if (whitelist != null) {
505 for (int uid : whitelist) {
506 mPowerSaveWhitelistAppIds.put(uid, true);
507 }
508 }
509 } catch (RemoteException e) {
510 }
511 }
512
Felipe Lemea9505cc2016-02-26 10:28:41 -0800513 /**
514 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
515 * revoke the whitelist.
516 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700517 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800518 */
Felipe Lemef0823852016-06-08 13:43:08 -0700519 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800520 final List<UserInfo> users = mUserManager.getUsers();
521 final int numberUsers = users.size();
522
Felipe Lemea110eec2016-04-29 09:58:06 -0700523 boolean changed = false;
524 for (int i = 0; i < numberUsers; i++) {
525 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700526 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700527 }
528 return changed;
529 }
530
Felipe Lemef0823852016-06-08 13:43:08 -0700531 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700532 final SystemConfig sysConfig = SystemConfig.getInstance();
533 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800534 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
535 boolean changed = false;
536 for (int i = 0; i < allowDataUsage.size(); i++) {
537 final String pkg = allowDataUsage.valueAt(i);
538 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700539 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
540 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800541 final ApplicationInfo app;
542 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700543 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800544 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700545 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
546 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800547 continue;
548 }
549 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700550 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
551 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800552 continue;
553 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700554 final int uid = UserHandle.getUid(userId, app.uid);
555 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
556 if (LOGD)
557 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
558 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700560 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700561 if (LOGD)
562 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
563 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700564 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700565 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800566 }
567 }
568 return changed;
569 }
570
Felipe Lemef0823852016-06-08 13:43:08 -0700571 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700572 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700573 // Clear the states of the current whitelist
574 final int N = mPowerSaveTempWhitelistAppIds.size();
575 for (int i = 0; i < N; i++) {
576 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
577 }
578 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700579 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700580 if (whitelist != null) {
581 for (int uid : whitelist) {
582 mPowerSaveTempWhitelistAppIds.put(uid, true);
583 }
584 }
585 } catch (RemoteException e) {
586 }
587 }
588
Amith Yamasani06f08062015-06-12 13:23:33 -0700589 /**
590 * Remove unnecessary entries in the temp whitelist
591 */
Felipe Lemef0823852016-06-08 13:43:08 -0700592 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700593 final int N = mPowerSaveTempWhitelistAppIds.size();
594 for (int i = N - 1; i >= 0; i--) {
595 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
596 mPowerSaveTempWhitelistAppIds.removeAt(i);
597 }
598 }
599 }
600
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800601 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700602 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800603 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700604 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800605 // Boost thread's priority during system server init
606 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700607 if (!isBandwidthControlEnabled()) {
608 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
609 return;
610 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700611
Felipe Leme873a83a2016-09-07 11:34:10 -0700612 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700613
Felipe Leme873a83a2016-09-07 11:34:10 -0700614 synchronized (mUidRulesFirstLock) {
615 synchronized (mNetworkPoliciesSecondLock) {
616 updatePowerSaveWhitelistUL();
617 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
618 mPowerManagerInternal.registerLowPowerModeObserver(
619 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800620 @Override
621 public int getServiceType() {
622 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700623 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800624
625 @Override
626 public void onLowPowerModeChanged(PowerSaveState result) {
627 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800628 if (LOGD) {
629 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
630 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800631 synchronized (mUidRulesFirstLock) {
632 if (mRestrictPower != enabled) {
633 mRestrictPower = enabled;
634 updateRulesForRestrictPowerUL();
635 }
636 }
637 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800638 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800639 mRestrictPower = mPowerManagerInternal.getLowPowerState(
640 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700641
642 mSystemReady = true;
643
644 // read policy from disk
645 readPolicyAL();
646
jackqdyulei29c82ab2017-03-10 14:09:16 -0800647 // Update the restrictBackground if battery saver is turned on
648 mRestrictBackgroundBeforeBsm = mRestrictBackground;
649 mRestrictBackgroundPowerState = mPowerManagerInternal
650 .getLowPowerState(ServiceType.DATA_SAVER);
651 final boolean localRestrictBackground =
652 mRestrictBackgroundPowerState.batterySaverEnabled;
653 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
654 mRestrictBackground = localRestrictBackground;
655 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
656 mRestrictBackground ? 1 : 0, 0).sendToTarget();
657 }
658 mPowerManagerInternal.registerLowPowerModeObserver(
659 new PowerManagerInternal.LowPowerModeListener() {
660 @Override
661 public int getServiceType() {
662 return ServiceType.DATA_SAVER;
663 }
664
665 @Override
666 public void onLowPowerModeChanged(PowerSaveState result) {
667 synchronized (mUidRulesFirstLock) {
668 updateRestrictBackgroundByLowPowerModeUL(result);
669 }
670 }
671 });
672
Felipe Leme873a83a2016-09-07 11:34:10 -0700673 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
674 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700675 }
Felipe Lemef0823852016-06-08 13:43:08 -0700676
Felipe Leme873a83a2016-09-07 11:34:10 -0700677 setRestrictBackgroundUL(mRestrictBackground);
678 updateRulesForGlobalChangeAL(false);
679 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700680 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800681 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700682
Sudheer Shankae7361852017-03-07 11:51:46 -0800683 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700684 try {
685 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000686 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800687 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700688 mNetworkManager.registerObserver(mAlertObserver);
689 } catch (RemoteException e) {
690 // ignored; both services live in system_server
691 }
692
693 // listen for changes to power save whitelist
694 final IntentFilter whitelistFilter = new IntentFilter(
695 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
696 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
697
698 DeviceIdleController.LocalService deviceIdleService
699 = LocalServices.getService(DeviceIdleController.LocalService.class);
700 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
701
702 // watch for network interfaces to be claimed
703 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
704 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
705
706 // listen for package changes to update policy
707 final IntentFilter packageFilter = new IntentFilter();
708 packageFilter.addAction(ACTION_PACKAGE_ADDED);
709 packageFilter.addDataScheme("package");
710 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
711
712 // listen for UID changes to update policy
713 mContext.registerReceiver(
714 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
715
716 // listen for user changes to update policy
717 final IntentFilter userFilter = new IntentFilter();
718 userFilter.addAction(ACTION_USER_ADDED);
719 userFilter.addAction(ACTION_USER_REMOVED);
720 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
721
722 // listen for stats update events
723 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
724 mContext.registerReceiver(
725 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
726
727 // listen for restrict background changes from notifications
728 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
729 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
730
731 // listen for snooze warning from notifications
732 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
733 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
734 MANAGE_NETWORK_POLICY, mHandler);
735
736 // listen for configured wifi networks to be removed
737 final IntentFilter wifiConfigFilter =
738 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
739 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
740
741 // listen for wifi state changes to catch metered hint
742 final IntentFilter wifiStateFilter = new IntentFilter(
743 WifiManager.NETWORK_STATE_CHANGED_ACTION);
744 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
745
746 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800747 // tell systemReady() that the service has been initialized
748 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700749 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800750 // Restore the default priority after init is done
751 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700752 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700753 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700754 }
755
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800756 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
757 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
758 mHandler.post(() -> initService(initCompleteSignal));
759 return initCompleteSignal;
760 }
761
762 public void systemReady(CountDownLatch initCompleteSignal) {
763 // wait for initService to complete
764 try {
765 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
766 throw new IllegalStateException("Service " + TAG +" init timeout");
767 }
768 } catch (InterruptedException e) {
769 Thread.currentThread().interrupt();
770 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
771 }
772 }
773
Sudheer Shankac9d94072017-02-22 22:13:55 +0000774 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800775 @Override public void onUidStateChanged(int uid, int procState,
776 long procStateSeq) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700777 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
778 try {
779 synchronized (mUidRulesFirstLock) {
Sudheer Shankae7361852017-03-07 11:51:46 -0800780 // We received a uid state change callback, add it to the history so that it
781 // will be useful for debugging.
782 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
783 // Now update the network policy rules as per the updated uid state.
Sudheer Shankac9d94072017-02-22 22:13:55 +0000784 updateUidStateUL(uid, procState);
Sudheer Shankae7361852017-03-07 11:51:46 -0800785 // Updating the network rules is done, so notify AMS about this.
786 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
Felipe Leme873a83a2016-09-07 11:34:10 -0700787 }
788 } finally {
789 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700790 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700791 }
792
Dianne Hackborne07641d2016-11-09 15:07:23 -0800793 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700794 synchronized (mUidRulesFirstLock) {
795 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700796 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700797 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700798
799 @Override public void onUidActive(int uid) throws RemoteException {
800 }
801
Dianne Hackborne07641d2016-11-09 15:07:23 -0800802 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700803 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700804 };
805
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700806 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700807 @Override
808 public void onReceive(Context context, Intent intent) {
809 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700810 synchronized (mUidRulesFirstLock) {
811 updatePowerSaveWhitelistUL();
812 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700813 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700814 }
815 }
816 };
817
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700818 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
819 @Override
820 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700821 synchronized (mUidRulesFirstLock) {
822 updatePowerSaveTempWhitelistUL();
823 updateRulesForTempWhitelistChangeUL();
824 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700825 }
826 }
827 };
828
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700829 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700830 @Override
831 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700832 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700833
834 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700835 final int uid = intent.getIntExtra(EXTRA_UID, -1);
836 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700837
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700838 if (ACTION_PACKAGE_ADDED.equals(action)) {
839 // update rules for UID, since it might be subject to
840 // global background data policy
841 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700842 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700843 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700844 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700845 }
846 }
847 };
848
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700849 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700850 @Override
851 public void onReceive(Context context, Intent intent) {
852 // on background handler thread, and UID_REMOVED is protected
853
854 final int uid = intent.getIntExtra(EXTRA_UID, -1);
855 if (uid == -1) return;
856
857 // remove any policy and update rules to clean up
858 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700859 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700860 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700861 synchronized (mNetworkPoliciesSecondLock) {
862 writePolicyAL();
863 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700864 }
865 }
866 };
867
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700868 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700869 @Override
870 public void onReceive(Context context, Intent intent) {
871 // on background handler thread, and USER_ADDED and USER_REMOVED
872 // broadcasts are protected
873
874 final String action = intent.getAction();
875 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
876 if (userId == -1) return;
877
Amith Yamasani15e472352015-04-24 19:06:07 -0700878 switch (action) {
879 case ACTION_USER_REMOVED:
880 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700881 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800882 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700883 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700884 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700885 if (action == ACTION_USER_ADDED) {
886 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700887 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700888 }
889 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700890 synchronized (mNetworkPoliciesSecondLock) {
891 updateRulesForGlobalChangeAL(true);
892 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700893 }
894 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700895 }
896 }
897 };
898
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700899 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700900 * Receiver that watches for {@link INetworkStatsService} updates, which we
901 * use to check against {@link NetworkPolicy#warningBytes}.
902 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700903 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700904 @Override
905 public void onReceive(Context context, Intent intent) {
906 // on background handler thread, and verified
907 // READ_NETWORK_USAGE_HISTORY permission above.
908
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800909 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700910 synchronized (mNetworkPoliciesSecondLock) {
911 updateNetworkEnabledNL();
912 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700913 }
914 }
915 };
916
917 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700918 * Receiver that watches for {@link Notification} control of
919 * {@link #mRestrictBackground}.
920 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700921 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700922 @Override
923 public void onReceive(Context context, Intent intent) {
924 // on background handler thread, and verified MANAGE_NETWORK_POLICY
925 // permission above.
926
927 setRestrictBackground(false);
928 }
929 };
930
931 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800932 * Receiver that watches for {@link Notification} control of
933 * {@link NetworkPolicy#lastWarningSnooze}.
934 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700935 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800936 @Override
937 public void onReceive(Context context, Intent intent) {
938 // on background handler thread, and verified MANAGE_NETWORK_POLICY
939 // permission above.
940
941 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
942 performSnooze(template, TYPE_WARNING);
943 }
944 };
945
946 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700947 * Receiver that watches for {@link WifiConfiguration} to be changed.
948 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700950 @Override
951 public void onReceive(Context context, Intent intent) {
952 // on background handler thread, and verified CONNECTIVITY_INTERNAL
953 // permission above.
954
955 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
956 if (reason == CHANGE_REASON_REMOVED) {
957 final WifiConfiguration config = intent.getParcelableExtra(
958 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700959 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800960 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700961 synchronized (mUidRulesFirstLock) {
962 synchronized (mNetworkPoliciesSecondLock) {
963 if (mNetworkPolicy.containsKey(template)) {
964 mNetworkPolicy.remove(template);
965 writePolicyAL();
966 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700967 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700968 }
969 }
970 }
971 }
972 };
973
974 /**
975 * Receiver that watches {@link WifiInfo} state changes to infer metered
976 * state. Ignores hints when policy is user-defined.
977 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700978 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700979 @Override
980 public void onReceive(Context context, Intent intent) {
981 // on background handler thread, and verified CONNECTIVITY_INTERNAL
982 // permission above.
983
984 // ignore when not connected
985 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
986 if (!netInfo.isConnected()) return;
987
988 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
989 final boolean meteredHint = info.getMeteredHint();
990
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800991 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700992 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700993 NetworkPolicy policy = mNetworkPolicy.get(template);
994 if (policy == null && meteredHint) {
995 // policy doesn't exist, and AP is hinting that it's
996 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800997 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700998 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700999
1000 } else if (policy != null && policy.inferred) {
1001 // policy exists, and was inferred: update its current
1002 // metered state.
1003 policy.metered = meteredHint;
1004
1005 // since this is inferred for each wifi session, just update
1006 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -07001007 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001008 }
1009 }
1010 }
1011 };
1012
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08001013 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
1014 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
1015 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
1016 metered, true);
1017 }
1018
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001019 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001020 * Observer that watches for {@link INetworkManagementService} alerts.
1021 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001022 final private INetworkManagementEventObserver mAlertObserver
1023 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001024 @Override
1025 public void limitReached(String limitName, String iface) {
1026 // only someone like NMS should be calling us
1027 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1028
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001029 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1030 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001031 }
1032 }
1033 };
1034
1035 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001036 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1037 * to show visible notifications as needed.
1038 */
Felipe Lemef0823852016-06-08 13:43:08 -07001039 void updateNotificationsNL() {
1040 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001041
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001042 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -07001043 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001044 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001045
1046 // TODO: when switching to kernel notifications, compute next future
1047 // cycle boundary to recompute notifications.
1048
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001049 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001050 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001051 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1052 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001053 // ignore policies that aren't relevant to user
1054 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001055 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001056
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057 final long start = computeLastCycleBoundary(currentTime, policy);
1058 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001059 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001060
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001061 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001062 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001063 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1064 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001065 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001066 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 }
1068
Jeff Sharkey497e4432011-06-14 17:27:29 -07001069 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001070 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001071
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001072 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074 }
1075 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001076 }
1077
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001078 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001079 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
1080 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001081 if (!mActiveNotifs.contains(tag)) {
1082 cancelNotification(tag);
1083 }
1084 }
1085 }
1086
1087 /**
1088 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001089 * current device state, such as when
1090 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1091 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092 */
1093 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001094 if (template.isMatchRuleMobile()) {
1095 final TelephonyManager tele = TelephonyManager.from(mContext);
1096 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001097
Jeff Sharkey32566012014-12-02 18:30:14 -08001098 // Mobile template is relevant when any active subscriber matches
1099 final int[] subIds = sub.getActiveSubscriptionIdList();
1100 for (int subId : subIds) {
1101 final String subscriberId = tele.getSubscriberId(subId);
1102 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001103 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001104 if (template.matches(probeIdent)) {
1105 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001106 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001107 }
1108 return false;
1109 } else {
1110 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001111 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001112 }
1113
1114 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001115 * Notify that given {@link NetworkTemplate} is over
1116 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1117 */
Felipe Lemef0823852016-06-08 13:43:08 -07001118 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001120 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001121 mOverLimitNotified.add(template);
1122 }
1123 }
1124
Felipe Lemef0823852016-06-08 13:43:08 -07001125 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001126 mOverLimitNotified.remove(template);
1127 }
1128
1129 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130 * Build unique tag that identifies an active {@link NetworkPolicy}
1131 * notification of a specific type, like {@link #TYPE_LIMIT}.
1132 */
1133 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001134 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 }
1136
1137 /**
1138 * Show notification for combined {@link NetworkPolicy} and specific type,
1139 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1140 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001141 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001142 final String tag = buildNotificationTag(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001143 final Notification.Builder builder =
1144 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001146 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001147 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001148 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001149
1150 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001151 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152 switch (type) {
1153 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001154 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001155 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001156
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001157 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001158 builder.setTicker(title);
1159 builder.setContentTitle(title);
1160 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001161 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001162 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001163
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001164 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1165 builder.setDeleteIntent(PendingIntent.getBroadcast(
1166 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1167
Wei Liu546cb772016-07-21 16:19:01 -07001168 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001169 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001170 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1171
Jeff Sharkey497e4432011-06-14 17:27:29 -07001172 break;
1173 }
1174 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001175 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001176
1177 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001178 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001179 switch (policy.template.getMatchRule()) {
1180 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001181 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001182 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001183 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001184 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001185 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001187 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 case MATCH_WIFI:
1190 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001191 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001192 break;
1193 default:
1194 title = null;
1195 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001196 }
1197
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001198 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001199 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001200 builder.setTicker(title);
1201 builder.setContentTitle(title);
1202 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001203
Wei Liu546cb772016-07-21 16:19:01 -07001204 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001205 builder.setContentIntent(PendingIntent.getActivity(
1206 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1207 break;
1208 }
1209 case TYPE_LIMIT_SNOOZED: {
1210 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001211 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001212 Formatter.formatFileSize(mContext, overBytes));
1213
1214 final CharSequence title;
1215 switch (policy.template.getMatchRule()) {
1216 case MATCH_MOBILE_3G_LOWER:
1217 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1218 break;
1219 case MATCH_MOBILE_4G:
1220 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1221 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001222 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001223 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1224 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001225 case MATCH_WIFI:
1226 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1227 break;
1228 default:
1229 title = null;
1230 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001231 }
1232
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001233 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001234 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001235 builder.setTicker(title);
1236 builder.setContentTitle(title);
1237 builder.setContentText(body);
1238
Wei Liu546cb772016-07-21 16:19:01 -07001239 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001240 builder.setContentIntent(PendingIntent.getActivity(
1241 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001242 break;
1243 }
1244 }
1245
1246 // TODO: move to NotificationManager once we can mock it
1247 try {
1248 final String packageName = mContext.getPackageName();
1249 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001250 if(!TextUtils.isEmpty(body)) {
1251 builder.setStyle(new Notification.BigTextStyle()
1252 .bigText(body));
1253 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001254 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001255 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001256 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001257 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001258 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001259 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001260 }
1261 }
1262
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001263 private void cancelNotification(String tag) {
1264 // TODO: move to NotificationManager once we can mock it
1265 try {
1266 final String packageName = mContext.getPackageName();
1267 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001268 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001269 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001270 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001271 }
1272 }
1273
1274 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001276 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001277 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001278 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001279 @Override
1280 public void onReceive(Context context, Intent intent) {
1281 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1282 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001283
1284 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001285 synchronized (mNetworkPoliciesSecondLock) {
1286 ensureActiveMobilePolicyNL();
1287 normalizePoliciesNL();
1288 updateNetworkEnabledNL();
1289 updateNetworkRulesNL();
1290 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291 }
1292 }
1293 };
1294
1295 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001296 * Proactively control network data connections when they exceed
1297 * {@link NetworkPolicy#limitBytes}.
1298 */
Felipe Lemef0823852016-06-08 13:43:08 -07001299 void updateNetworkEnabledNL() {
1300 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001301
1302 // TODO: reset any policy-disabled networks when any policy is removed
1303 // completely, which is currently rare case.
1304
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001305 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001306 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1307 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001308 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001309 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001310 setNetworkTemplateEnabled(policy.template, true);
1311 continue;
1312 }
1313
1314 final long start = computeLastCycleBoundary(currentTime, policy);
1315 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001316 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001317
1318 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001319 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1320 && policy.lastLimitSnooze < start;
1321 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001322
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001323 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001324 }
1325 }
1326
1327 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001328 * Proactively disable networks that match the given
1329 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001330 */
1331 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 // TODO: reach into ConnectivityManager to proactively disable bringing
1333 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001334
1335 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1336 // If mobile data usage hits the limit or if the user resumes the data, we need to
1337 // notify telephony.
1338 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1339 final TelephonyManager tm = TelephonyManager.from(mContext);
1340
1341 final int[] subIds = sm.getActiveSubscriptionIdList();
1342 for (int subId : subIds) {
1343 final String subscriberId = tm.getSubscriberId(subId);
1344 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1345 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1346 // Template is matched when subscriber id matches.
1347 if (template.matches(probeIdent)) {
1348 tm.setPolicyDataEnabled(enabled, subId);
1349 }
1350 }
1351 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001352 }
1353
1354 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001355 * Examine all connected {@link NetworkState}, looking for
1356 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1357 * remaining quota based on usage cycle and historical stats.
1358 */
Felipe Lemef0823852016-06-08 13:43:08 -07001359 void updateNetworkRulesNL() {
1360 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001361
1362 final NetworkState[] states;
1363 try {
1364 states = mConnManager.getAllNetworkState();
1365 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001366 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001367 return;
1368 }
1369
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001370 // First, generate identities of all connected networks so we can
1371 // quickly compare them against all defined policies below.
1372 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001373 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001374 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001375 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001376 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001377
1378 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001379 if (baseIface != null) {
1380 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001381 }
1382
1383 // Stacked interfaces are considered to have same identity as
1384 // their parent network.
1385 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1386 for (LinkProperties stackedLink : stackedLinks) {
1387 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001388 if (stackedIface != null) {
1389 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001390 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001391 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001392 }
1393 }
1394
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001395 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001396 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001397 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001398 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001399 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001400
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001401 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001402 for (int j = connIdents.size() - 1; j >= 0; j--) {
1403 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1404 if (policy.template.matches(ident.second)) {
1405 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001406 }
1407 }
1408
1409 if (ifaceList.size() > 0) {
1410 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001411 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001412 }
1413 }
1414
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001415 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001416 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001417
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001418 // apply each policy that we found ifaces for; compute remaining data
1419 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001420 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001421 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1422 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1423 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001424
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001425 final long start;
1426 final long totalBytes;
1427 if (policy.hasCycle()) {
1428 start = computeLastCycleBoundary(currentTime, policy);
1429 totalBytes = getTotalBytes(policy.template, start, currentTime);
1430 } else {
1431 start = Long.MAX_VALUE;
1432 totalBytes = 0;
1433 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001434
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001435 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001436 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001437 }
1438
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001439 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001440 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001441 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001442 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001443 if (!hasLimit) {
1444 // metered network, but no policy limit; we still need to
1445 // restrict apps, so push really high quota.
1446 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001447 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001448 // snoozing past quota, but we still need to restrict apps,
1449 // so push really high quota.
1450 quotaBytes = Long.MAX_VALUE;
1451 } else {
1452 // remaining "quota" bytes are based on total usage in
1453 // current cycle. kernel doesn't like 0-byte rules, so we
1454 // set 1-byte quota and disable the radio later.
1455 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1456 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001457
1458 if (ifaces.length > 1) {
1459 // TODO: switch to shared quota once NMS supports
1460 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001461 }
1462
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001463 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001464 // long quotaBytes split up into two ints to fit in message
1465 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1466 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1467 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001468 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001469 }
1470 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001471
1472 // keep track of lowest warning or limit of active policies
1473 if (hasWarning && policy.warningBytes < lowestRule) {
1474 lowestRule = policy.warningBytes;
1475 }
1476 if (hasLimit && policy.limitBytes < lowestRule) {
1477 lowestRule = policy.limitBytes;
1478 }
1479 }
1480
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001481 for (int i = connIfaces.size()-1; i >= 0; i--) {
1482 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001483 // long quotaBytes split up into two ints to fit in message
1484 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1485 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1486 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001487 newMeteredIfaces.add(iface);
1488 }
1489
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001490 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001491
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001492 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001493 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1494 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001495 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001496 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1497 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001498 }
1499 }
1500 mMeteredIfaces = newMeteredIfaces;
1501
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001502 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001503 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001504 }
1505
1506 /**
1507 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1508 * have at least a default mobile policy defined.
1509 */
Felipe Lemef0823852016-06-08 13:43:08 -07001510 private void ensureActiveMobilePolicyNL() {
1511 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001512 if (mSuppressDefaultPolicy) return;
1513
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001514 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001515 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001516
Jeff Sharkey32566012014-12-02 18:30:14 -08001517 final int[] subIds = sub.getActiveSubscriptionIdList();
1518 for (int subId : subIds) {
1519 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001520 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001521 }
1522 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001523
Felipe Lemef0823852016-06-08 13:43:08 -07001524 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001525 // Poke around to see if we already have a policy
1526 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001527 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001528 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1529 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1530 if (template.matches(probeIdent)) {
1531 if (LOGD) {
1532 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1533 + NetworkIdentity.scrubSubscriberId(subscriberId));
1534 }
1535 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001536 }
1537 }
1538
Jeff Sharkey32566012014-12-02 18:30:14 -08001539 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1540 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001541
Jeff Sharkey32566012014-12-02 18:30:14 -08001542 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001543 final int dataWarningConfig = mContext.getResources().getInteger(
1544 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1545 final long warningBytes;
1546 if (dataWarningConfig == WARNING_DISABLED) {
1547 warningBytes = WARNING_DISABLED;
1548 } else {
1549 warningBytes = dataWarningConfig * MB_IN_BYTES;
1550 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001551
Jeff Sharkey32566012014-12-02 18:30:14 -08001552 final Time time = new Time();
1553 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001554
Jeff Sharkey32566012014-12-02 18:30:14 -08001555 final int cycleDay = time.monthDay;
1556 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001557
Jeff Sharkey32566012014-12-02 18:30:14 -08001558 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1559 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1560 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001561 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001562 }
1563
Felipe Lemef0823852016-06-08 13:43:08 -07001564 private void readPolicyAL() {
1565 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001566
1567 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001568 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001569 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001570
1571 FileInputStream fis = null;
1572 try {
1573 fis = mPolicyFile.openRead();
1574 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001575 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001576
Felipe Leme46b451f2016-08-19 08:46:17 -07001577 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1578 // to skip UIDs that were explicitly blacklisted.
1579 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1580
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001582 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001583 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584 while ((type = in.next()) != END_DOCUMENT) {
1585 final String tag = in.getName();
1586 if (type == START_TAG) {
1587 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001588 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001589 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001590 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1591 mRestrictBackground = readBooleanAttribute(
1592 in, ATTR_RESTRICT_BACKGROUND);
1593 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001594 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001595 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001596 if (mRestrictBackground != oldValue) {
1597 // Some early services may have read the default value,
1598 // so notify them that it's changed
1599 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1600 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1601 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001602
1603 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1604 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1605 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001606 final String networkId;
1607 if (version >= VERSION_ADDED_NETWORK_ID) {
1608 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1609 } else {
1610 networkId = null;
1611 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001612 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001613 final String cycleTimezone;
1614 if (version >= VERSION_ADDED_TIMEZONE) {
1615 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1616 } else {
1617 cycleTimezone = Time.TIMEZONE_UTC;
1618 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1620 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001621 final long lastLimitSnooze;
1622 if (version >= VERSION_SPLIT_SNOOZE) {
1623 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1624 } else if (version >= VERSION_ADDED_SNOOZE) {
1625 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001626 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001627 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001628 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001629 final boolean metered;
1630 if (version >= VERSION_ADDED_METERED) {
1631 metered = readBooleanAttribute(in, ATTR_METERED);
1632 } else {
1633 switch (networkTemplate) {
1634 case MATCH_MOBILE_3G_LOWER:
1635 case MATCH_MOBILE_4G:
1636 case MATCH_MOBILE_ALL:
1637 metered = true;
1638 break;
1639 default:
1640 metered = false;
1641 }
1642 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001643 final long lastWarningSnooze;
1644 if (version >= VERSION_SPLIT_SNOOZE) {
1645 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1646 } else {
1647 lastWarningSnooze = SNOOZE_NEVER;
1648 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001649 final boolean inferred;
1650 if (version >= VERSION_ADDED_INFERRED) {
1651 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1652 } else {
1653 inferred = false;
1654 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655
Jeff Sharkey32566012014-12-02 18:30:14 -08001656 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1657 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001658 if (template.isPersistable()) {
1659 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1660 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1661 lastLimitSnooze, metered, inferred));
1662 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001663
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001664 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001665 final int uid = readIntAttribute(in, ATTR_UID);
1666 final int policy = readIntAttribute(in, ATTR_POLICY);
1667
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001668 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001669 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001670 } else {
1671 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1672 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001673 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001674 final int appId = readIntAttribute(in, ATTR_APP_ID);
1675 final int policy = readIntAttribute(in, ATTR_POLICY);
1676
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001677 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001678 // app policy is deprecated so this is only used in pre system user split.
1679 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001680 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001681 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001682 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001683 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001684 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001685 } else if (TAG_WHITELIST.equals(tag)) {
1686 insideWhitelist = true;
1687 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1688 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001689 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001690 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1691 final int uid = readIntAttribute(in, ATTR_UID);
1692 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001693 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001694 } else if (type == END_TAG) {
1695 if (TAG_WHITELIST.equals(tag)) {
1696 insideWhitelist = false;
1697 }
1698
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001699 }
1700 }
1701
Felipe Leme46b451f2016-08-19 08:46:17 -07001702 final int size = whitelistedRestrictBackground.size();
1703 for (int i = 0; i < size; i++) {
1704 final int uid = whitelistedRestrictBackground.keyAt(i);
1705 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1706 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1707 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1708 + " because its policy is " + uidPoliciesToString(policy));
1709 continue;
1710 }
1711 if (UserHandle.isApp(uid)) {
1712 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1713 if (LOGV)
1714 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1715 setUidPolicyUncheckedUL(uid, newPolicy, false);
1716 } else {
1717 Slog.w(TAG, "unable to update policy on UID " + uid);
1718 }
1719 }
1720
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001721 } catch (FileNotFoundException e) {
1722 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001723 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001724 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001725 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001726 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001727 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001728 } finally {
1729 IoUtils.closeQuietly(fis);
1730 }
1731 }
1732
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001733 /**
1734 * Upgrade legacy background data flags, notifying listeners of one last
1735 * change to always-true.
1736 */
Felipe Lemef0823852016-06-08 13:43:08 -07001737 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001738 mRestrictBackground = Settings.Secure.getInt(
1739 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1740
1741 // kick off one last broadcast if restricted
1742 if (mRestrictBackground) {
1743 final Intent broadcast = new Intent(
1744 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001745 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001746 }
1747 }
1748
Felipe Lemef0823852016-06-08 13:43:08 -07001749 void writePolicyAL() {
1750 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751
1752 FileOutputStream fos = null;
1753 try {
1754 fos = mPolicyFile.startWrite();
1755
1756 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001757 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001758 out.startDocument(null, true);
1759
1760 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001761 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001762 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763
1764 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001765 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1766 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001767 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001768 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001769
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001770 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001771 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1772 final String subscriberId = template.getSubscriberId();
1773 if (subscriberId != null) {
1774 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001775 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001776 final String networkId = template.getNetworkId();
1777 if (networkId != null) {
1778 out.attribute(null, ATTR_NETWORK_ID, networkId);
1779 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001780 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001781 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001782 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1783 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001784 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1785 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001786 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001787 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001788 out.endTag(null, TAG_NETWORK_POLICY);
1789 }
1790
1791 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001792 for (int i = 0; i < mUidPolicy.size(); i++) {
1793 final int uid = mUidPolicy.keyAt(i);
1794 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001795
Jeff Sharkey497e4432011-06-14 17:27:29 -07001796 // skip writing empty policies
1797 if (policy == POLICY_NONE) continue;
1798
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001799 out.startTag(null, TAG_UID_POLICY);
1800 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001801 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001802 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001803 }
1804
1805 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001806
1807 // write all whitelists
1808 out.startTag(null, TAG_WHITELIST);
1809
Felipe Lemea9505cc2016-02-26 10:28:41 -08001810 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001811 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001812 for (int i = 0; i < size; i++) {
1813 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1814 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1815 writeIntAttribute(out, ATTR_UID, uid);
1816 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1817 }
1818
Felipe Lemeb85a6372016-01-14 16:16:16 -08001819 out.endTag(null, TAG_WHITELIST);
1820
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821 out.endDocument();
1822
1823 mPolicyFile.finishWrite(fos);
1824 } catch (IOException e) {
1825 if (fos != null) {
1826 mPolicyFile.failWrite(fos);
1827 }
1828 }
1829 }
1830
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001831 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001832 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001833 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001834
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001835 if (!UserHandle.isApp(uid)) {
1836 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001837 }
Felipe Lemef0823852016-06-08 13:43:08 -07001838 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001839 final long token = Binder.clearCallingIdentity();
1840 try {
1841 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1842 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001843 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001844 }
1845 } finally {
1846 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001847 }
1848 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001849 }
1850
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001851 @Override
1852 public void addUidPolicy(int uid, int policy) {
1853 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001854
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001855 if (!UserHandle.isApp(uid)) {
1856 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1857 }
1858
Felipe Lemef0823852016-06-08 13:43:08 -07001859 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001860 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1861 policy |= oldPolicy;
1862 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001863 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001864 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001865 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001866 }
1867
1868 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001869 public void removeUidPolicy(int uid, int policy) {
1870 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1871
1872 if (!UserHandle.isApp(uid)) {
1873 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1874 }
1875
Felipe Lemef0823852016-06-08 13:43:08 -07001876 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001877 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1878 policy = oldPolicy & ~policy;
1879 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001880 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001881 }
1882 }
1883 }
1884
Felipe Lemef0823852016-06-08 13:43:08 -07001885 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1886 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001887
Felipe Leme57e3d312016-08-23 14:42:52 -07001888 final boolean notifyApp;
1889 if (!isUidValidForWhitelistRules(uid)) {
1890 notifyApp = false;
1891 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001892 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1893 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1894 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1895 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001896 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1897 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001898 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1899 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1900 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1901 if (LOGD)
1902 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1903 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1904 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001905 notifyApp = wasBlocked != isBlocked;
1906 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001907 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1908 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001909 }
1910
Felipe Lemef0823852016-06-08 13:43:08 -07001911 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001912 if (policy == POLICY_NONE) {
1913 mUidPolicy.delete(uid);
1914 } else {
1915 mUidPolicy.put(uid, policy);
1916 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001917
1918 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00001919 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001920 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001921 synchronized (mNetworkPoliciesSecondLock) {
1922 writePolicyAL();
1923 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001924 }
1925 }
1926
1927 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001928 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001929 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1930
Felipe Lemef0823852016-06-08 13:43:08 -07001931 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001933 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001934 }
1935
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001936 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001937 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001938 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1939
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001940 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001941 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001942 for (int i = 0; i < mUidPolicy.size(); i++) {
1943 final int uid = mUidPolicy.keyAt(i);
1944 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001945 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1946 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001947 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001948 }
1949 }
1950 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001951 return uids;
1952 }
1953
1954 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001955 * Removes any persistable state associated with given {@link UserHandle}, persisting
1956 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001957 */
Felipe Lemef0823852016-06-08 13:43:08 -07001958 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001959
Felipe Lemef0823852016-06-08 13:43:08 -07001960 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001961 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001962
Felipe Lemea110eec2016-04-29 09:58:06 -07001963 // Remove entries from revoked default restricted background UID whitelist
1964 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1965 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1966 if (UserHandle.getUserId(uid) == userId) {
1967 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001968 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001969 }
1970 }
1971
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001972 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001973 int[] uids = new int[0];
1974 for (int i = 0; i < mUidPolicy.size(); i++) {
1975 final int uid = mUidPolicy.keyAt(i);
1976 if (UserHandle.getUserId(uid) == userId) {
1977 uids = appendInt(uids, uid);
1978 }
1979 }
1980
1981 if (uids.length > 0) {
1982 for (int uid : uids) {
1983 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001984 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001985 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001986 }
Felipe Lemef0823852016-06-08 13:43:08 -07001987 synchronized (mNetworkPoliciesSecondLock) {
1988 updateRulesForGlobalChangeAL(true);
1989 if (writePolicy && changed) {
1990 writePolicyAL();
1991 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001992 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001993 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001994 }
1995
1996 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001997 public void setConnectivityListener(INetworkPolicyListener listener) {
1998 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1999 if (mConnectivityListener != null) {
2000 throw new IllegalStateException("Connectivity listener already registered");
2001 }
2002 mConnectivityListener = listener;
2003 }
2004
2005 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002006 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002007 // TODO: create permission for observing network policy
2008 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002009 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002010 }
2011
2012 @Override
2013 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002014 // TODO: create permission for observing network policy
2015 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002016 mListeners.unregister(listener);
2017 }
2018
Jeff Sharkey1b861272011-05-22 00:34:52 -07002019 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002020 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002021 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2022
Felipe Leme6a05eee2016-02-19 14:43:51 -08002023 final long token = Binder.clearCallingIdentity();
2024 try {
2025 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002026 synchronized (mUidRulesFirstLock) {
2027 synchronized (mNetworkPoliciesSecondLock) {
2028 normalizePoliciesNL(policies);
2029 updateNetworkEnabledNL();
2030 updateNetworkRulesNL();
2031 updateNotificationsNL();
2032 writePolicyAL();
2033 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002034 }
2035 } finally {
2036 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002037 }
2038 }
2039
Felipe Lemef0823852016-06-08 13:43:08 -07002040 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002041 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002042 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2043 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002044 }
2045
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002046 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002047 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002049 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002050 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2051 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2052 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002053 } catch (SecurityException e) {
2054 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002055
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002056 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2057 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2058 return new NetworkPolicy[0];
2059 }
Svet Ganov16a16892015-04-16 10:32:04 -07002060 }
2061
Felipe Lemef0823852016-06-08 13:43:08 -07002062 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002063 final int size = mNetworkPolicy.size();
2064 final NetworkPolicy[] policies = new NetworkPolicy[size];
2065 for (int i = 0; i < size; i++) {
2066 policies[i] = mNetworkPolicy.valueAt(i);
2067 }
2068 return policies;
2069 }
2070 }
2071
Felipe Lemef0823852016-06-08 13:43:08 -07002072 private void normalizePoliciesNL() {
2073 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002074 }
2075
Felipe Lemef0823852016-06-08 13:43:08 -07002076 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002077 final TelephonyManager tele = TelephonyManager.from(mContext);
2078 final String[] merged = tele.getMergedSubscriberIds();
2079
2080 mNetworkPolicy.clear();
2081 for (NetworkPolicy policy : policies) {
2082 // When two normalized templates conflict, prefer the most
2083 // restrictive policy
2084 policy.template = NetworkTemplate.normalize(policy.template, merged);
2085 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2086 if (existing == null || existing.compareTo(policy) > 0) {
2087 if (existing != null) {
2088 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2089 }
2090 mNetworkPolicy.put(policy.template, policy);
2091 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002092 }
2093 }
2094
2095 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002096 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002097 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002098
2099 final long token = Binder.clearCallingIdentity();
2100 try {
2101 performSnooze(template, TYPE_LIMIT);
2102 } finally {
2103 Binder.restoreCallingIdentity(token);
2104 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002105 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002106
Dianne Hackborn497175b2014-07-01 12:56:08 -07002107 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002108 maybeRefreshTrustedTime();
2109 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002110 synchronized (mUidRulesFirstLock) {
2111 synchronized (mNetworkPoliciesSecondLock) {
2112 // find and snooze local policy that matches
2113 final NetworkPolicy policy = mNetworkPolicy.get(template);
2114 if (policy == null) {
2115 throw new IllegalArgumentException("unable to find policy for " + template);
2116 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002117
Felipe Lemef0823852016-06-08 13:43:08 -07002118 switch (type) {
2119 case TYPE_WARNING:
2120 policy.lastWarningSnooze = currentTime;
2121 break;
2122 case TYPE_LIMIT:
2123 policy.lastLimitSnooze = currentTime;
2124 break;
2125 default:
2126 throw new IllegalArgumentException("unexpected type");
2127 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002128
Felipe Lemef0823852016-06-08 13:43:08 -07002129 normalizePoliciesNL();
2130 updateNetworkEnabledNL();
2131 updateNetworkRulesNL();
2132 updateNotificationsNL();
2133 writePolicyAL();
2134 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002135 }
2136 }
2137
2138 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002139 public void onTetheringChanged(String iface, boolean tethering) {
2140 // No need to enforce permission because setRestrictBackground() will do it.
2141 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002142 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002143 if (mRestrictBackground && tethering) {
2144 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2145 setRestrictBackground(false);
2146 }
2147 }
2148 }
2149
2150 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002151 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002152 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002153 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002154 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2155 final long token = Binder.clearCallingIdentity();
2156 try {
2157 maybeRefreshTrustedTime();
2158 synchronized (mUidRulesFirstLock) {
2159 if (restrictBackground == mRestrictBackground) {
2160 // Ideally, UI should never allow this scenario...
2161 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2162 return;
2163 }
2164 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002165 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002166
2167 } finally {
2168 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002169 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002170
Felipe Leme29e72ea2016-09-08 13:26:55 -07002171 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2172 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002173 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002174 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002175 }
2176 }
2177
Felipe Lemef0823852016-06-08 13:43:08 -07002178 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002179 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002180 final boolean oldRestrictBackground = mRestrictBackground;
2181 mRestrictBackground = restrictBackground;
2182 // Must whitelist foreground apps before turning data saver mode on.
2183 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2184 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002185 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002186 try {
2187 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2188 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2189 mRestrictBackground = oldRestrictBackground;
2190 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002191 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002192 return;
2193 }
2194 } catch (RemoteException e) {
2195 // ignored; service lives in system_server
2196 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002197
2198 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2199 mRestrictBackgroundChangedInBsm = true;
2200 }
Felipe Lemef0823852016-06-08 13:43:08 -07002201 synchronized (mNetworkPoliciesSecondLock) {
2202 updateNotificationsNL();
2203 writePolicyAL();
2204 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002205 }
2206
Felipe Lemeb85a6372016-01-14 16:16:16 -08002207 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002208 public int getRestrictBackgroundByCaller() {
2209 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2210 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002211
Felipe Lemef0823852016-06-08 13:43:08 -07002212 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002213 // Must clear identity because getUidPolicy() is restricted to system.
2214 final long token = Binder.clearCallingIdentity();
2215 final int policy;
2216 try {
2217 policy = getUidPolicy(uid);
2218 } finally {
2219 Binder.restoreCallingIdentity(token);
2220 }
2221 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2222 // App is blacklisted.
2223 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2224 }
Felipe Leme1b103232016-01-22 09:44:57 -08002225 if (!mRestrictBackground) {
2226 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2227 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002228 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002229 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2230 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2231 }
2232 }
2233
2234 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002235 public boolean getRestrictBackground() {
2236 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2237
Felipe Lemef0823852016-06-08 13:43:08 -07002238 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002239 return mRestrictBackground;
2240 }
2241 }
2242
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002243 @Override
2244 public void setDeviceIdleMode(boolean enabled) {
2245 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002246 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2247 try {
2248 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002249 if (mDeviceIdleMode == enabled) {
2250 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002251 }
Felipe Lemeea014392016-09-06 13:59:54 -07002252 mDeviceIdleMode = enabled;
2253 if (mSystemReady) {
2254 // Device idle change means we need to rebuild rules for all
2255 // known apps, so do a global refresh.
2256 updateRulesForRestrictPowerUL();
2257 }
2258 }
2259 if (enabled) {
2260 EventLogTags.writeDeviceIdleOnPhase("net");
2261 } else {
2262 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002263 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002264 } finally {
2265 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002266 }
2267 }
2268
Felipe Lemef0823852016-06-08 13:43:08 -07002269 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002270 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2271 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002272 if (policy.template.matches(ident)) {
2273 return policy;
2274 }
2275 }
2276 return null;
2277 }
2278
2279 @Override
2280 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2281 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2282
2283 // only returns usage summary, so we don't require caller to have
2284 // READ_NETWORK_USAGE_HISTORY.
2285 final long token = Binder.clearCallingIdentity();
2286 try {
2287 return getNetworkQuotaInfoUnchecked(state);
2288 } finally {
2289 Binder.restoreCallingIdentity(token);
2290 }
2291 }
2292
2293 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2294 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2295
2296 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002297 synchronized (mNetworkPoliciesSecondLock) {
2298 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002299 }
2300
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002301 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002302 // missing policy means we can't derive useful quota info
2303 return null;
2304 }
2305
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002306 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002307
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002308 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002309 final long start = computeLastCycleBoundary(currentTime, policy);
2310 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002311 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002312
2313 // report soft and hard limits under policy
2314 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2315 : NetworkQuotaInfo.NO_LIMIT;
2316 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2317 : NetworkQuotaInfo.NO_LIMIT;
2318
2319 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2320 }
2321
Jeff Sharkey46645002011-07-27 21:11:21 -07002322 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002323 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002324 if (state.networkInfo == null) {
2325 return false;
2326 }
2327
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002328 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2329
2330 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002331 synchronized (mNetworkPoliciesSecondLock) {
2332 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002333 }
2334
2335 if (policy != null) {
2336 return policy.metered;
2337 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002338 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002339 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002340 return true;
2341 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002342 return false;
2343 }
2344 }
2345
2346 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002347 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002348 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002349
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002350 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2351
Dianne Hackborn497175b2014-07-01 12:56:08 -07002352 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002353 for (String arg : args) {
2354 argSet.add(arg);
2355 }
2356
Felipe Lemef0823852016-06-08 13:43:08 -07002357 synchronized (mUidRulesFirstLock) {
2358 synchronized (mNetworkPoliciesSecondLock) {
2359 if (argSet.contains("--unsnooze")) {
2360 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2361 mNetworkPolicy.valueAt(i).clearSnooze();
2362 }
2363
2364 normalizePoliciesNL();
2365 updateNetworkEnabledNL();
2366 updateNetworkRulesNL();
2367 updateNotificationsNL();
2368 writePolicyAL();
2369
2370 fout.println("Cleared snooze timestamps");
2371 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002372 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002373
Felipe Lemef0823852016-06-08 13:43:08 -07002374 fout.print("System ready: "); fout.println(mSystemReady);
2375 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2376 fout.print("Restrict power: "); fout.println(mRestrictPower);
2377 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2378 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002379 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002380 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2381 fout.println(mNetworkPolicy.valueAt(i).toString());
2382 }
2383 fout.decreaseIndent();
2384
2385 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2386
2387 fout.println("Policy for UIDs:");
2388 fout.increaseIndent();
2389 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002390 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002391 final int uid = mUidPolicy.keyAt(i);
2392 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002393 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002394 fout.print(uid);
2395 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002396 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002397 fout.println();
2398 }
2399 fout.decreaseIndent();
2400
2401 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2402 if (size > 0) {
2403 fout.println("Power save whitelist (except idle) app ids:");
2404 fout.increaseIndent();
2405 for (int i = 0; i < size; i++) {
2406 fout.print("UID=");
2407 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2408 fout.print(": ");
2409 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2410 fout.println();
2411 }
2412 fout.decreaseIndent();
2413 }
2414
2415 size = mPowerSaveWhitelistAppIds.size();
2416 if (size > 0) {
2417 fout.println("Power save whitelist app ids:");
2418 fout.increaseIndent();
2419 for (int i = 0; i < size; i++) {
2420 fout.print("UID=");
2421 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2422 fout.print(": ");
2423 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2424 fout.println();
2425 }
2426 fout.decreaseIndent();
2427 }
2428
Felipe Lemef0823852016-06-08 13:43:08 -07002429 size = mDefaultRestrictBackgroundWhitelistUids.size();
2430 if (size > 0) {
2431 fout.println("Default restrict background whitelist uids:");
2432 fout.increaseIndent();
2433 for (int i = 0; i < size; i++) {
2434 fout.print("UID=");
2435 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2436 fout.println();
2437 }
2438 fout.decreaseIndent();
2439 }
2440
2441 size = mRestrictBackgroundWhitelistRevokedUids.size();
2442 if (size > 0) {
2443 fout.println("Default restrict background whitelist uids revoked by users:");
2444 fout.increaseIndent();
2445 for (int i = 0; i < size; i++) {
2446 fout.print("UID=");
2447 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2448 fout.println();
2449 }
2450 fout.decreaseIndent();
2451 }
2452
2453 final SparseBooleanArray knownUids = new SparseBooleanArray();
2454 collectKeys(mUidState, knownUids);
2455 collectKeys(mUidRules, knownUids);
2456
2457 fout.println("Status for all known UIDs:");
2458 fout.increaseIndent();
2459 size = knownUids.size();
2460 for (int i = 0; i < size; i++) {
2461 final int uid = knownUids.keyAt(i);
2462 fout.print("UID=");
2463 fout.print(uid);
2464
2465 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2466 fout.print(" state=");
2467 fout.print(state);
2468 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2469 fout.print(" (fg)");
2470 } else {
2471 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2472 ? " (fg svc)" : " (bg)");
2473 }
2474
2475 final int uidRules = mUidRules.get(uid, RULE_NONE);
2476 fout.print(" rules=");
2477 fout.print(uidRulesToString(uidRules));
2478 fout.println();
2479 }
2480 fout.decreaseIndent();
2481
2482 fout.println("Status for just UIDs with rules:");
2483 fout.increaseIndent();
2484 size = mUidRules.size();
2485 for (int i = 0; i < size; i++) {
2486 final int uid = mUidRules.keyAt(i);
2487 fout.print("UID=");
2488 fout.print(uid);
2489 final int uidRules = mUidRules.get(uid, RULE_NONE);
2490 fout.print(" rules=");
2491 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002492 fout.println();
2493 }
2494 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002495
2496 fout.println("Observed uid state changes:");
2497 fout.increaseIndent();
2498 mObservedHistory.dumpUL(fout);
2499 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002500 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002501 }
2502 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002503
2504 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002505 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002506 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002507 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002508 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002509 }
2510
2511 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002512 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002513 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2514
Felipe Lemef0823852016-06-08 13:43:08 -07002515 synchronized (mUidRulesFirstLock) {
2516 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002517 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002518 }
2519
Felipe Lemef0823852016-06-08 13:43:08 -07002520 private boolean isUidForegroundUL(int uid) {
2521 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002522 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2523 }
2524
Felipe Lemef0823852016-06-08 13:43:08 -07002525 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002526 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002527 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002528 }
2529
Felipe Lemef0823852016-06-08 13:43:08 -07002530 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002531 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2532 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2533 }
2534
Felipe Lemef0823852016-06-08 13:43:08 -07002535 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002536 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002537 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002538 }
2539
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002540 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002541 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002542 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2543 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002544 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002545 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002546 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2547 try {
2548 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2549 if (oldUidState != uidState) {
2550 // state changed, push updated rules
2551 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002552 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2553 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2554 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2555 if (isUidIdle(uid)) {
2556 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002557 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002558 if (mDeviceIdleMode) {
2559 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002560 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002561 if (mRestrictPower) {
2562 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002563 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002564 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002565 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002566 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002567 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002568 } finally {
2569 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002570 }
2571 }
2572
Felipe Lemef0823852016-06-08 13:43:08 -07002573 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002574 final int index = mUidState.indexOfKey(uid);
2575 if (index >= 0) {
2576 final int oldUidState = mUidState.valueAt(index);
2577 mUidState.removeAt(index);
2578 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002579 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002580 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002581 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002582 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002583 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002584 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002585 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002586 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002587 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002588 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002589 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002590 }
2591 }
2592
Felipe Lemef28983d2016-03-25 12:18:23 -07002593 // adjust stats accounting based on foreground status
2594 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002595 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2596 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2597 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2598 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002599 try {
2600 mNetworkStats.setUidForeground(uid, uidForeground);
2601 } catch (RemoteException e) {
2602 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002603 } finally {
2604 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002605 }
2606 }
2607
Sudheer Shankac9d94072017-02-22 22:13:55 +00002608 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2609 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002610 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002611 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002612 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002613 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002614 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002615 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002616 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002617 }
2618
Felipe Lemef0823852016-06-08 13:43:08 -07002619 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002620 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2621 try {
2622 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2623 mUidFirewallPowerSaveRules);
2624 } finally {
2625 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2626 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002627 }
2628
Felipe Lemef0823852016-06-08 13:43:08 -07002629 void updateRuleForRestrictPowerUL(int uid) {
2630 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002631 }
2632
Felipe Lemef0823852016-06-08 13:43:08 -07002633 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002634 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2635 try {
2636 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2637 mUidFirewallDozableRules);
2638 } finally {
2639 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2640 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002641 }
2642
Felipe Lemef0823852016-06-08 13:43:08 -07002643 void updateRuleForDeviceIdleUL(int uid) {
2644 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002645 }
2646
Felipe Lemef28983d2016-03-25 12:18:23 -07002647 // NOTE: since both fw_dozable and fw_powersave uses the same map
2648 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002649 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002650 SparseIntArray rules) {
2651 if (enabled) {
2652 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002653 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002654 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002655 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002656 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002657 for (int ui = users.size() - 1; ui >= 0; ui--) {
2658 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002659 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002660 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2661 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2662 int uid = UserHandle.getUid(user.id, appId);
2663 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2664 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002665 }
2666 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2667 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2668 int uid = UserHandle.getUid(user.id, appId);
2669 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2670 }
2671 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002672 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002673 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002674 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2675 }
2676 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002677 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2678 } else {
2679 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002680 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002681 }
2682
Felipe Lemef0823852016-06-08 13:43:08 -07002683 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002684 final int appId = UserHandle.getAppId(uid);
2685 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2686 }
2687
Felipe Lemef28983d2016-03-25 12:18:23 -07002688 // NOTE: since both fw_dozable and fw_powersave uses the same map
2689 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002690 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002691 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002692 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002693 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002694 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002695 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002696 }
2697 }
2698 }
2699
Felipe Lemef0823852016-06-08 13:43:08 -07002700 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002701 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2702 try {
2703 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2704 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002705
Felipe Leme873a83a2016-09-07 11:34:10 -07002706 // Fully update the app idle firewall chain.
2707 final List<UserInfo> users = mUserManager.getUsers();
2708 for (int ui = users.size() - 1; ui >= 0; ui--) {
2709 UserInfo user = users.get(ui);
2710 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2711 for (int uid : idleUids) {
2712 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2713 // quick check: if this uid doesn't have INTERNET permission, it
2714 // doesn't have network access anyway, so it is a waste to mess
2715 // with it here.
2716 if (hasInternetPermissions(uid)) {
2717 uidRules.put(uid, FIREWALL_RULE_DENY);
2718 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002719 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002720 }
2721 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002722
Felipe Lemebc853dd2016-09-08 13:26:55 -07002723 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002724 } finally {
2725 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2726 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002727 }
2728
Felipe Lemef0823852016-06-08 13:43:08 -07002729 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002730 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002731
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002732 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2733 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
2734 }
2735 try {
2736 int appId = UserHandle.getAppId(uid);
2737 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2738 && !isUidForegroundOnRestrictPowerUL(uid)) {
2739 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2740 } else {
2741 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2742 }
2743 } finally {
2744 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002745 }
2746 }
2747
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002748 /**
2749 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2750 * changed.
2751 */
Felipe Lemef0823852016-06-08 13:43:08 -07002752 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002753 boolean paroled = mUsageStats.isAppIdleParoleOn();
2754 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002755 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002756
2757 int ruleCount = mUidFirewallStandbyRules.size();
2758 for (int i = 0; i < ruleCount; i++) {
2759 int uid = mUidFirewallStandbyRules.keyAt(i);
2760 int oldRules = mUidRules.get(uid);
2761 if (enableChain) {
2762 // Chain wasn't enabled before and the other power-related
2763 // chains are whitelists, so we can clear the
2764 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2765 // the effective rules result in blocking network access.
2766 oldRules &= MASK_METERED_NETWORKS;
2767 } else {
2768 // Skip if it had no restrictions to begin with
2769 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2770 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002771 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002772 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002773 }
2774
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002775 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002776 * Update rules that might be changed by {@link #mRestrictBackground},
2777 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002778 */
Felipe Lemef0823852016-06-08 13:43:08 -07002779 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002780 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2781 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2782 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
2783 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002784 try {
Felipe Leme09700462016-09-08 09:33:48 -07002785 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002786 updateRulesForRestrictPowerUL();
2787 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002788
Felipe Leme873a83a2016-09-07 11:34:10 -07002789 // If the set of restricted networks may have changed, re-evaluate those.
2790 if (restrictedNetworksChanged) {
2791 normalizePoliciesNL();
2792 updateNetworkRulesNL();
2793 }
2794 } finally {
2795 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002796 }
2797 }
2798
Felipe Leme09700462016-09-08 09:33:48 -07002799 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002800 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002801 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2802 try {
2803 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002804 updateRulesForPowerSaveUL();
2805 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2806 } finally {
2807 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2808 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002809 }
2810
Felipe Lemef0823852016-06-08 13:43:08 -07002811 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002812 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2813 try {
2814 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2815 } finally {
2816 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2817 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002818 }
2819
2820 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2821 private static final int TYPE_RESTRICT_POWER = 2;
2822 @Retention(RetentionPolicy.SOURCE)
2823 @IntDef(flag = false, value = {
2824 TYPE_RESTRICT_BACKGROUND,
2825 TYPE_RESTRICT_POWER,
2826 })
2827 public @interface RestrictType {
2828 }
2829
2830 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002831 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002832 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2833 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2834 }
2835 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07002836 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002837
2838 final PackageManager pm = mContext.getPackageManager();
2839 final List<UserInfo> users;
2840 final List<ApplicationInfo> apps;
2841
2842 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
2843 try {
2844 users = mUserManager.getUsers();
2845 } finally {
2846 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2847 }
2848 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
2849 try {
2850 apps = pm.getInstalledApplications(
2851 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
2852 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2853 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
2854 } finally {
2855 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2856 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002857
Felipe Leme873a83a2016-09-07 11:34:10 -07002858 final int usersSize = users.size();
2859 final int appsSize = apps.size();
2860 for (int i = 0; i < usersSize; i++) {
2861 final UserInfo user = users.get(i);
2862 for (int j = 0; j < appsSize; j++) {
2863 final ApplicationInfo app = apps.get(j);
2864 final int uid = UserHandle.getUid(user.id, app.uid);
2865 switch (type) {
2866 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002867 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002868 break;
2869 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002870 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002871 break;
2872 default:
2873 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2874 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002875 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002876 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002877 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002878 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002879 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002880 }
2881
Felipe Lemef0823852016-06-08 13:43:08 -07002882 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002883 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002884 for (int i = 0; i < users.size(); i++) {
2885 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002886 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002887 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002888 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002889 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002890 updateRuleForAppIdleUL(uid);
2891 updateRuleForDeviceIdleUL(uid);
2892 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002893 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002894 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002895 }
2896 }
2897 }
2898
Felipe Leme70c57c22016-03-29 10:45:13 -07002899 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2900 // methods below could be merged into a isUidValidForRules() method.
2901 private boolean isUidValidForBlacklistRules(int uid) {
2902 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002903 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002904 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002905 return true;
2906 }
2907
2908 return false;
2909 }
2910
Felipe Leme70c57c22016-03-29 10:45:13 -07002911 private boolean isUidValidForWhitelistRules(int uid) {
2912 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2913 }
2914
Amith Yamasani15e472352015-04-24 19:06:07 -07002915 private boolean isUidIdle(int uid) {
2916 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2917 final int userId = UserHandle.getUserId(uid);
2918
songjinshi0655edd2016-05-18 19:55:32 +08002919 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002920 for (String packageName : packages) {
2921 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2922 return false;
2923 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002924 }
2925 }
2926 return true;
2927 }
2928
2929 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002930 * Checks if an uid has INTERNET permissions.
2931 * <p>
2932 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002933 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002934 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002935 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002936 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002937 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002938 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002939 }
2940 } catch (RemoteException e) {
2941 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002942 return true;
2943 }
2944
2945 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002946 * Clears all state - internal and external - associated with an UID.
2947 */
2948 private void onUidDeletedUL(int uid) {
2949 // First cleanup in-memory state synchronously...
2950 mUidRules.delete(uid);
2951 mUidPolicy.delete(uid);
2952 mUidFirewallStandbyRules.delete(uid);
2953 mUidFirewallDozableRules.delete(uid);
2954 mUidFirewallPowerSaveRules.delete(uid);
2955 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2956 mPowerSaveWhitelistAppIds.delete(uid);
2957 mPowerSaveTempWhitelistAppIds.delete(uid);
2958
2959 // ...then update iptables asynchronously.
2960 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2961 }
2962
2963 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002964 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002965 *
Felipe Leme781ba142016-05-09 16:24:48 -07002966 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002967 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002968 * <li>Doze mode
2969 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002970 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002971 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002972 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002973 *
2974 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002975 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002976 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002977 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002978 updateRuleForDeviceIdleUL(uid);
2979 updateRuleForAppIdleUL(uid);
2980 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002981
2982 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002983 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002984
2985 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002986 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002987 }
2988
Felipe Leme70c57c22016-03-29 10:45:13 -07002989 /**
2990 * Applies network rules to bandwidth controllers based on process state and user-defined
2991 * restrictions (blacklist / whitelist).
2992 *
2993 * <p>
2994 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2995 * networks:
2996 * <ul>
2997 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2998 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2999 * also blacklisted.
3000 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3001 * no UIDs other those whitelisted will have access.
3002 * <ul>
3003 *
3004 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3005 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3006 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3007 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003008 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003009 * {@link INetworkManagementService}, but this method should also be called in events (like
3010 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3011 * following rules should also be applied:
3012 *
3013 * <ul>
3014 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3015 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3016 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3017 * {@code bw_penalty_box}.
3018 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3019 * </ul>
3020 *
3021 * <p>For optimization, the rules are only applied on user apps that have internet access
3022 * permission, since there is no need to change the {@code iptables} rule if the app does not
3023 * have permission to use the internet.
3024 *
3025 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003026 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003027 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003028 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003029 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3030 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3031 "updateRulesForDataUsageRestrictionsUL: " + uid);
3032 }
3033 try {
3034 updateRulesForDataUsageRestrictionsULInner(uid);
3035 } finally {
3036 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3037 }
3038 }
3039
3040 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003041 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003042 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003043 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003044 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003045
Dianne Hackborn497175b2014-07-01 12:56:08 -07003046 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003047 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003048 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003049
Felipe Leme781ba142016-05-09 16:24:48 -07003050 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003051 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003052 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3053 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003054
Felipe Leme70c57c22016-03-29 10:45:13 -07003055 // First step: define the new rule based on user restrictions and foreground state.
3056 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003057 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3058 newRule = RULE_TEMPORARY_ALLOW_METERED;
3059 } else if (isWhitelisted) {
3060 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003061 }
3062 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003063 if (isBlacklisted) {
3064 newRule = RULE_REJECT_METERED;
3065 } else if (mRestrictBackground && isWhitelisted) {
3066 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003067 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003068 }
Felipe Leme781ba142016-05-09 16:24:48 -07003069 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003070
Felipe Lemef28983d2016-03-25 12:18:23 -07003071 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003072 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003073 + ": isForeground=" +isForeground
3074 + ", isBlacklisted=" + isBlacklisted
3075 + ", isWhitelisted=" + isWhitelisted
3076 + ", oldRule=" + uidRulesToString(oldRule)
3077 + ", newRule=" + uidRulesToString(newRule)
3078 + ", newUidRules=" + uidRulesToString(newUidRules)
3079 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003080 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003081
Felipe Leme46c4fc32016-05-04 09:21:43 -07003082 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003083 mUidRules.delete(uid);
3084 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003085 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003086 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003087
Felipe Leme70c57c22016-03-29 10:45:13 -07003088 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003089 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07003090 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003091 // Temporarily whitelist foreground app, removing from blacklist if necessary
3092 // (since bw_penalty_box prevails over bw_happy_box).
3093
3094 setMeteredNetworkWhitelist(uid, true);
3095 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3096 // but ideally it should be just:
3097 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003098 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003099 setMeteredNetworkBlacklist(uid, false);
3100 }
Felipe Leme781ba142016-05-09 16:24:48 -07003101 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003102 // Remove temporary whitelist from app that is not on foreground anymore.
3103
3104 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3105 // but ideally they should be just:
3106 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3107 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003108 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003109 setMeteredNetworkWhitelist(uid, false);
3110 }
Felipe Leme781ba142016-05-09 16:24:48 -07003111 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003112 setMeteredNetworkBlacklist(uid, true);
3113 }
Felipe Leme781ba142016-05-09 16:24:48 -07003114 } else if ((newRule & RULE_REJECT_METERED) != 0
3115 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003116 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003117 setMeteredNetworkBlacklist(uid, isBlacklisted);
3118 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003119 // Since blacklist prevails over whitelist, we need to handle the special case
3120 // where app is whitelisted and blacklisted at the same time (although such
3121 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003122 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003123 }
Felipe Leme781ba142016-05-09 16:24:48 -07003124 } else if ((newRule & RULE_ALLOW_METERED) != 0
3125 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003126 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003127 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003128 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003129 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003130 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3131 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003132 + ", whitelisted=" + isWhitelisted
3133 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003134 + ", newRule=" + uidRulesToString(newUidRules)
3135 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003136 }
Felipe Leme781ba142016-05-09 16:24:48 -07003137
Sudheer Shankac9d94072017-02-22 22:13:55 +00003138 // Dispatch changed rule to existing listeners.
3139 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003140 }
3141 }
3142
3143 /**
3144 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3145 * listeners in case of change.
3146 * <p>
3147 * There are 3 power-related rules that affects whether an app has background access on
3148 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3149 * restriction, it's added to the equivalent firewall chain:
3150 * <ul>
3151 * <li>App is idle: {@code fw_standby} firewall chain.
3152 * <li>Device is idle: {@code fw_dozable} firewall chain.
3153 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3154 * </ul>
3155 * <p>
3156 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3157 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3158 * <p>
3159 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3160 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003161 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003162 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3163
Sudheer Shankac9d94072017-02-22 22:13:55 +00003164 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003165
Sudheer Shankac9d94072017-02-22 22:13:55 +00003166 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003167 mUidRules.delete(uid);
3168 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003169 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003170 }
3171 }
3172
3173 /**
3174 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3175 *
3176 * @param uid the uid of the app to update rules for
3177 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3178 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3179 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003180 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003181 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003182 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003183 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3184 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3185 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3186 + (paroled ? "P" : "-"));
3187 }
3188 try {
3189 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3190 } finally {
3191 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3192 }
3193 }
3194
3195 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003196 if (!isUidValidForBlacklistRules(uid)) {
3197 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003198 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003199 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003200
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003201 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003202 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003203 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003204
Felipe Lemef0823852016-06-08 13:43:08 -07003205 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003206 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3207 int newRule = RULE_NONE;
3208
3209 // First step: define the new rule based on user restrictions and foreground state.
3210
3211 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3212 // by considering the foreground and non-foreground states.
3213 if (isForeground) {
3214 if (restrictMode) {
3215 newRule = RULE_ALLOW_ALL;
3216 }
3217 } else if (restrictMode) {
3218 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3219 }
3220
3221 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3222
3223 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003224 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003225 + ", isIdle: " + isIdle
3226 + ", mRestrictPower: " + mRestrictPower
3227 + ", mDeviceIdleMode: " + mDeviceIdleMode
3228 + ", isForeground=" + isForeground
3229 + ", isWhitelisted=" + isWhitelisted
3230 + ", oldRule=" + uidRulesToString(oldRule)
3231 + ", newRule=" + uidRulesToString(newRule)
3232 + ", newUidRules=" + uidRulesToString(newUidRules)
3233 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3234 }
3235
Felipe Leme781ba142016-05-09 16:24:48 -07003236 // Second step: notify listeners if state changed.
3237 if (newRule != oldRule) {
3238 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003239 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003240 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003241 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3242 } else {
3243 // All scenarios should have been covered above
3244 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3245 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003246 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003247 + ", newRule=" + uidRulesToString(newUidRules)
3248 + ", oldRule=" + uidRulesToString(oldUidRules));
3249 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003250 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003251 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003252
Sudheer Shankac9d94072017-02-22 22:13:55 +00003253 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003254 }
3255
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003256 private class AppIdleStateChangeListener
3257 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3258
3259 @Override
3260 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3261 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003262 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3263 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003264 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003265 synchronized (mUidRulesFirstLock) {
3266 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003267 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003268 }
3269 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003270 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003271 }
3272
3273 @Override
3274 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003275 synchronized (mUidRulesFirstLock) {
3276 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003277 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003278 }
3279 }
3280
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003281 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3282 if (listener != null) {
3283 try {
3284 listener.onUidRulesChanged(uid, uidRules);
3285 } catch (RemoteException ignored) {
3286 }
3287 }
3288 }
3289
3290 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3291 String[] meteredIfaces) {
3292 if (listener != null) {
3293 try {
3294 listener.onMeteredIfacesChanged(meteredIfaces);
3295 } catch (RemoteException ignored) {
3296 }
3297 }
3298 }
3299
3300 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3301 boolean restrictBackground) {
3302 if (listener != null) {
3303 try {
3304 listener.onRestrictBackgroundChanged(restrictBackground);
3305 } catch (RemoteException ignored) {
3306 }
3307 }
3308 }
3309
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003310 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3311 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003312 if (listener != null) {
3313 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003314 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003315 } catch (RemoteException ignored) {
3316 }
3317 }
3318 }
3319
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003320 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003321 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003322 public boolean handleMessage(Message msg) {
3323 switch (msg.what) {
3324 case MSG_RULES_CHANGED: {
3325 final int uid = msg.arg1;
3326 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003327 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
3328 final int length = mListeners.beginBroadcast();
3329 for (int i = 0; i < length; i++) {
3330 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3331 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003332 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003333 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003334 return true;
3335 }
3336 case MSG_METERED_IFACES_CHANGED: {
3337 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003338 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003339 final int length = mListeners.beginBroadcast();
3340 for (int i = 0; i < length; i++) {
3341 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003342 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003343 }
3344 mListeners.finishBroadcast();
3345 return true;
3346 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003347 case MSG_LIMIT_REACHED: {
3348 final String iface = (String) msg.obj;
3349
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003350 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003351 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003352 if (mMeteredIfaces.contains(iface)) {
3353 try {
3354 // force stats update to make sure we have
3355 // numbers that caused alert to trigger.
3356 mNetworkStats.forceUpdate();
3357 } catch (RemoteException e) {
3358 // ignored; service lives in system_server
3359 }
3360
Felipe Lemef0823852016-06-08 13:43:08 -07003361 updateNetworkEnabledNL();
3362 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003363 }
3364 }
3365 return true;
3366 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003367 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3368 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003369 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003370 final int length = mListeners.beginBroadcast();
3371 for (int i = 0; i < length; i++) {
3372 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003373 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003374 }
3375 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003376 final Intent intent =
3377 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3378 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3379 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3380 return true;
3381 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003382 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003383 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003384 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003385 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003386 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003387 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003388 final int length = mListeners.beginBroadcast();
3389 for (int i = 0; i < length; i++) {
3390 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003391 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003392 }
3393 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003394 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3395 if (notifyApp.booleanValue()) {
3396 broadcastRestrictBackgroundChanged(uid, notifyApp);
3397 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003398 return true;
3399 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003400 case MSG_ADVISE_PERSIST_THRESHOLD: {
3401 final long lowestRule = (Long) msg.obj;
3402 try {
3403 // make sure stats are recorded frequently enough; we aim
3404 // for 2MB threshold for 2GB/month rules.
3405 final long persistThreshold = lowestRule / 1000;
3406 mNetworkStats.advisePersistThreshold(persistThreshold);
3407 } catch (RemoteException e) {
3408 // ignored; service lives in system_server
3409 }
3410 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003411 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003412 case MSG_UPDATE_INTERFACE_QUOTA: {
3413 removeInterfaceQuota((String) msg.obj);
3414 // int params need to be stitched back into a long
3415 setInterfaceQuota((String) msg.obj,
3416 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3417 return true;
3418 }
3419 case MSG_REMOVE_INTERFACE_QUOTA: {
3420 removeInterfaceQuota((String) msg.obj);
3421 return true;
3422 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003423 case MSG_SET_FIREWALL_RULES: {
3424 final int chain = msg.arg1;
3425 final int toggle = msg.arg2;
3426 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3427 if (uidRules != null) {
3428 setUidFirewallRules(chain, uidRules);
3429 }
3430 if (toggle != CHAIN_TOGGLE_NONE) {
3431 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3432 }
3433 return true;
3434 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003435 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3436 resetUidFirewallRules(msg.arg1);
3437 return true;
3438 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003439 default: {
3440 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003441 }
3442 }
3443 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003444
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003445 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003446
Felipe Leme57e3d312016-08-23 14:42:52 -07003447 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3448 final PackageManager pm = mContext.getPackageManager();
3449 final String[] packages = pm.getPackagesForUid(uid);
3450 if (packages != null) {
3451 final int userId = UserHandle.getUserId(uid);
3452 for (String packageName : packages) {
3453 final Intent intent =
3454 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3455 intent.setPackage(packageName);
3456 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3457 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3458 }
3459 }
3460 }
3461
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003462 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003463 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003464 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003465 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003466 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003467 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003468 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003469 }
3470 }
3471
3472 private void removeInterfaceQuota(String iface) {
3473 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003474 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003475 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003476 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003477 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003478 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003479 }
3480 }
3481
Felipe Leme70c57c22016-03-29 10:45:13 -07003482 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3483 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003484 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003485 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003486 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003487 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3488 } catch (RemoteException e) {
3489 // ignored; service lives in system_server
3490 }
3491 }
3492
3493 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3494 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3495 try {
3496 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3497 } catch (IllegalStateException e) {
3498 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003499 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003500 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003501 }
3502 }
3503
Felipe Lemebc853dd2016-09-08 13:26:55 -07003504 private static final int CHAIN_TOGGLE_NONE = 0;
3505 private static final int CHAIN_TOGGLE_ENABLE = 1;
3506 private static final int CHAIN_TOGGLE_DISABLE = 2;
3507 @Retention(RetentionPolicy.SOURCE)
3508 @IntDef(flag = false, value = {
3509 CHAIN_TOGGLE_NONE,
3510 CHAIN_TOGGLE_ENABLE,
3511 CHAIN_TOGGLE_DISABLE
3512 })
3513 public @interface ChainToggleType {
3514 }
3515
3516 /**
3517 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3518 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3519 *
3520 * @param chain firewall chain.
3521 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3522 * @param toggle whether the chain should be enabled, disabled, or not changed.
3523 */
3524 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3525 @ChainToggleType int toggle) {
3526 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3527 }
3528
Amith Yamasani15e472352015-04-24 19:06:07 -07003529 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003530 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3531 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3532 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003533 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003534 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003535 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003536 int size = uidRules.size();
3537 int[] uids = new int[size];
3538 int[] rules = new int[size];
3539 for(int index = size - 1; index >= 0; --index) {
3540 uids[index] = uidRules.keyAt(index);
3541 rules[index] = uidRules.valueAt(index);
3542 }
3543 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003544 } catch (IllegalStateException e) {
3545 Log.wtf(TAG, "problem setting firewall uid rules", e);
3546 } catch (RemoteException e) {
3547 // ignored; service lives in system_server
3548 }
3549 }
3550
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003551 /**
3552 * Add or remove a uid to the firewall blacklist for all network ifaces.
3553 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003554 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003555 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3556 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3557 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003558 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003559 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003560 if (chain == FIREWALL_CHAIN_DOZABLE) {
3561 mUidFirewallDozableRules.put(uid, rule);
3562 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3563 mUidFirewallStandbyRules.put(uid, rule);
3564 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3565 mUidFirewallPowerSaveRules.put(uid, rule);
3566 }
3567
3568 try {
3569 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3570 } catch (IllegalStateException e) {
3571 Log.wtf(TAG, "problem setting firewall uid rules", e);
3572 } catch (RemoteException e) {
3573 // ignored; service lives in system_server
3574 }
3575 } finally {
3576 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003577 }
3578 }
3579
3580 /**
3581 * Add or remove a uid to the firewall blacklist for all network ifaces.
3582 */
Felipe Lemef0823852016-06-08 13:43:08 -07003583 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003584 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3585 mFirewallChainStates.get(chain) == enable) {
3586 // All is the same, nothing to do.
3587 return;
3588 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003589 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003590 try {
3591 mNetworkManager.setFirewallChainEnabled(chain, enable);
3592 } catch (IllegalStateException e) {
3593 Log.wtf(TAG, "problem enable firewall chain", e);
3594 } catch (RemoteException e) {
3595 // ignored; service lives in system_server
3596 }
3597 }
3598
Felipe Leme03e95e22016-09-09 09:25:31 -07003599 /**
3600 * Resets all firewall rules associated with an UID.
3601 */
3602 private void resetUidFirewallRules(int uid) {
3603 try {
3604 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3605 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3606 mNetworkManager
3607 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3608 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3609 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3610 } catch (IllegalStateException e) {
3611 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3612 } catch (RemoteException e) {
3613 // ignored; service lives in system_server
3614 }
3615 }
3616
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003617 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3618 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003619 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003620 } catch (RuntimeException e) {
3621 Slog.w(TAG, "problem reading network stats: " + e);
3622 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003623 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003624 // ignored; service lives in system_server
3625 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003626 }
3627 }
3628
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003629 private boolean isBandwidthControlEnabled() {
3630 final long token = Binder.clearCallingIdentity();
3631 try {
3632 return mNetworkManager.isBandwidthControlEnabled();
3633 } catch (RemoteException e) {
3634 // ignored; service lives in system_server
3635 return false;
3636 } finally {
3637 Binder.restoreCallingIdentity(token);
3638 }
3639 }
3640
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003641 /**
3642 * Try refreshing {@link #mTime} when stale.
3643 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003644 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003645 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003646 mTime.forceRefresh();
3647 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003648 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003649
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003650 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003651 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3652 }
3653
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003654 private static Intent buildAllowBackgroundDataIntent() {
3655 return new Intent(ACTION_ALLOW_BACKGROUND);
3656 }
3657
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003658 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3659 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3660 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3661 return intent;
3662 }
3663
Wei Liu546cb772016-07-21 16:19:01 -07003664 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003665 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003666 intent.setComponent(ComponentName.unflattenFromString(
3667 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003668 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3669 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3670 return intent;
3671 }
3672
Wei Liu546cb772016-07-21 16:19:01 -07003673 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003674 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003675 intent.setComponent(ComponentName.unflattenFromString(
3676 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003677 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3678 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3679 return intent;
3680 }
3681
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003682 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003683 public void addIdleHandler(IdleHandler handler) {
3684 mHandler.getLooper().getQueue().addIdleHandler(handler);
3685 }
3686
jackqdyulei29c82ab2017-03-10 14:09:16 -08003687 @VisibleForTesting
3688 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
3689 mRestrictBackgroundPowerState = result;
3690
3691 boolean restrictBackground = result.batterySaverEnabled;
3692 boolean shouldInvokeRestrictBackground;
3693 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
3694 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
3695
3696 if (result.globalBatterySaverEnabled) {
3697 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
3698 // turn it on.
3699 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
3700 mRestrictBackgroundBeforeBsm = mRestrictBackground;
3701 localRestrictBgChangedInBsm = false;
3702 } else {
3703 // Try to restore the restrictBackground if it doesn't change in bsm
3704 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
3705 restrictBackground = mRestrictBackgroundBeforeBsm;
3706 }
3707
3708 if (shouldInvokeRestrictBackground) {
3709 setRestrictBackground(restrictBackground);
3710 }
3711
3712 // Change it at last so setRestrictBackground() won't affect this variable
3713 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
3714 }
3715
Jeff Sharkey1b861272011-05-22 00:34:52 -07003716 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3717 final int size = source.size();
3718 for (int i = 0; i < size; i++) {
3719 target.put(source.keyAt(i), true);
3720 }
3721 }
3722
Stuart Scottf1fb3972015-04-02 18:00:02 -07003723 @Override
3724 public void factoryReset(String subscriber) {
3725 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3726
Stuart Scotte3e314d2015-04-20 14:07:45 -07003727 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3728 return;
3729 }
3730
Stuart Scottf1fb3972015-04-02 18:00:02 -07003731 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003732 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003733 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3734 for (NetworkPolicy policy : policies) {
3735 if (policy.template.equals(template)) {
3736 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3737 policy.inferred = false;
3738 policy.clearSnooze();
3739 }
3740 }
3741 setNetworkPolicies(policies);
3742
3743 // Turn restrict background data off
3744 setRestrictBackground(false);
3745
Stuart Scotte3e314d2015-04-20 14:07:45 -07003746 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3747 // Remove app's "restrict background data" flag
3748 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3749 setUidPolicy(uid, POLICY_NONE);
3750 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003751 }
3752 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003753
Felipe Lemed17fda42016-04-29 11:12:45 -07003754 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3755
3756 @Override
3757 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003758 synchronized (mUidRulesFirstLock) {
3759 boolean changed = removeUserStateUL(userId, false);
3760 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003761 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003762 synchronized (mNetworkPoliciesSecondLock) {
3763 writePolicyAL();
3764 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003765 }
3766 }
3767 }
3768 }
Sudheer Shankae7361852017-03-07 11:51:46 -08003769
3770 /**
3771 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
3772 * (uid, procStateSeq) pairs.
3773 */
3774 @VisibleForTesting
3775 public static final class ProcStateSeqHistory {
3776 private static final int INVALID_UID = -1;
3777
3778 /**
3779 * Denotes maximum number of items this history can hold.
3780 */
3781 private final int mMaxCapacity;
3782 /**
3783 * Used for storing the uid information.
3784 */
3785 private final int[] mUids;
3786 /**
3787 * Used for storing the sequence numbers associated with {@link #mUids}.
3788 */
3789 private final long[] mProcStateSeqs;
3790 /**
3791 * Points to the next available slot for writing (uid, procStateSeq) pair.
3792 */
3793 private int mHistoryNext;
3794
3795 public ProcStateSeqHistory(int maxCapacity) {
3796 mMaxCapacity = maxCapacity;
3797 mUids = new int[mMaxCapacity];
3798 Arrays.fill(mUids, INVALID_UID);
3799 mProcStateSeqs = new long[mMaxCapacity];
3800 }
3801
3802 @GuardedBy("mUidRulesFirstLock")
3803 public void addProcStateSeqUL(int uid, long procStateSeq) {
3804 mUids[mHistoryNext] = uid;
3805 mProcStateSeqs[mHistoryNext] = procStateSeq;
3806 mHistoryNext = increaseNext(mHistoryNext, 1);
3807 }
3808
3809 @GuardedBy("mUidRulesFirstLock")
3810 public void dumpUL(IndentingPrintWriter fout) {
3811 if (mUids[0] == INVALID_UID) {
3812 fout.println("NONE");
3813 return;
3814 }
3815 int index = mHistoryNext;
3816 do {
3817 index = increaseNext(index, -1);
3818 if (mUids[index] == INVALID_UID) {
3819 break;
3820 }
3821 fout.println(getString(mUids[index], mProcStateSeqs[index]));
3822 } while (index != mHistoryNext);
3823 }
3824
3825 public static String getString(int uid, long procStateSeq) {
3826 return "UID=" + uid + " procStateSeq=" + procStateSeq;
3827 }
3828
3829 private int increaseNext(int next, int increment) {
3830 next += increment;
3831 if (next >= mMaxCapacity) {
3832 next = 0;
3833 } else if (next < 0) {
3834 next = mMaxCapacity - 1;
3835 }
3836 return next;
3837 }
3838 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003839}