blob: 507899836ee24bc42f60f800309e0a06c26b1eb0 [file] [log] [blame]
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.net;
18
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070019import static android.Manifest.permission.ACCESS_NETWORK_STATE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070020import static android.Manifest.permission.CONNECTIVITY_INTERNAL;
Jeff Sharkey1b861272011-05-22 00:34:52 -070021import static android.Manifest.permission.DUMP;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070022import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
36import static android.net.ConnectivityManager.TYPE_WIMAX;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070037import static android.net.ConnectivityManager.isNetworkTypeMobile;
38import static android.net.NetworkPolicy.CYCLE_NONE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070039import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070040import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070041import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070042import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080044import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070045import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
46import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070047import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070048import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
55import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
56import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070057import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070058import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070059import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070060import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080061import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
62import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Felipe Lemeb146f762016-08-19 09:52:16 -070063import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070064import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
66import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070067import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
68import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070069import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080070import static android.net.TrafficStats.MB_IN_BYTES;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -070071import static android.net.wifi.WifiManager.CHANGE_REASON_ADDED;
72import static android.net.wifi.WifiManager.CHANGE_REASON_REMOVED;
73import static android.net.wifi.WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION;
74import static android.net.wifi.WifiManager.EXTRA_CHANGE_REASON;
75import static android.net.wifi.WifiManager.EXTRA_NETWORK_INFO;
76import static android.net.wifi.WifiManager.EXTRA_WIFI_CONFIGURATION;
77import static android.net.wifi.WifiManager.EXTRA_WIFI_INFO;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070078import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080079
Jeff Sharkey854b2b12012-04-13 16:03:40 -070080import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070081import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070082import static com.android.internal.util.XmlUtils.readBooleanAttribute;
83import static com.android.internal.util.XmlUtils.readIntAttribute;
84import static com.android.internal.util.XmlUtils.readLongAttribute;
85import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
86import static com.android.internal.util.XmlUtils.writeIntAttribute;
87import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070088import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070089import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060090
Jeff Sharkey21c9c452011-06-07 12:26:43 -070091import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080092import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070093import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070094
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070096import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070097import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070098import android.app.ActivityManager;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070099import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700100import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700101import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700102import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700103import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700104import android.app.Notification;
105import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700106import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700108import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700109import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700110import android.content.Intent;
111import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700112import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700113import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700114import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700115import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700116import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700117import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700118import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700119import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700120import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700121import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700122import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700123import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700124import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700126import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700128import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700129import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700130import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700131import android.net.wifi.WifiConfiguration;
132import android.net.wifi.WifiInfo;
133import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700134import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700135import android.os.Environment;
136import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700137import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700139import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700140import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700141import android.os.MessageQueue.IdleHandler;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700142import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700143import android.os.PowerManagerInternal;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800144import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700145import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700146import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600147import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700148import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700149import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700150import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700151import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700152import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700153import android.provider.Settings;
Jeff Sharkey32566012014-12-02 18:30:14 -0800154import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700155import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400156import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700157import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700158import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700159import android.util.ArrayMap;
160import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700161import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700162import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700164import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700165import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700166import android.util.SparseBooleanArray;
167import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700168import android.util.TrustedTime;
169import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700170
Jeff Sharkey497e4432011-06-14 17:27:29 -0700171import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700172import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800173import com.android.internal.annotations.VisibleForTesting;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500174import com.android.internal.notification.SystemNotificationChannels;
Jeff Sharkey32566012014-12-02 18:30:14 -0800175import com.android.internal.util.ArrayUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700176import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700177import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700178import com.android.server.DeviceIdleController;
179import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700180import com.android.server.LocalServices;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800181import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600182
183import libcore.io.IoUtils;
184
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186
187import org.xmlpull.v1.XmlPullParser;
188import org.xmlpull.v1.XmlPullParserException;
189import org.xmlpull.v1.XmlSerializer;
190
191import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700192import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193import java.io.FileInputStream;
194import java.io.FileNotFoundException;
195import java.io.FileOutputStream;
196import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700197import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700198import java.lang.annotation.Retention;
199import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100200import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import java.util.ArrayList;
202import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700203import java.util.List;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800204import java.util.concurrent.CountDownLatch;
205import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700206
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700207/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700208 * Service that maintains low-level network policy rules, using
209 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 * <p>
211 * Derives active rules by combining a given policy with other system status,
212 * and delivers to listeners, such as {@link ConnectivityManager}, for
213 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700214 *
215 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000216 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700217 * <ul>
218 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
219 * rules).
220 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
221 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000222 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
223 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700224 * </ul>
225 *
226 * <p>
227 * As such, methods that require synchronization have the following prefixes:
228 * <ul>
229 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
230 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000231 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
232 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700233 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700234 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700235public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800236 static final String TAG = "NetworkPolicy";
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -0700237 private static final boolean LOGD = false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700238 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700239
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700240 private static final int VERSION_INIT = 1;
241 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700242 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800243 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800244 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800245 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700246 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700247 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700248 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700249 private static final int VERSION_SWITCH_UID = 10;
250 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700251
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800252 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 public static final int TYPE_WARNING = 0x1;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800254 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700255 public static final int TYPE_LIMIT = 0x2;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800256 @VisibleForTesting
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700257 public static final int TYPE_LIMIT_SNOOZED = 0x3;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700258
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700259 private static final String TAG_POLICY_LIST = "policy-list";
260 private static final String TAG_NETWORK_POLICY = "network-policy";
261 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700262 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800263 private static final String TAG_WHITELIST = "whitelist";
264 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800265 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700266
267 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700268 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700269 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
270 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700271 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700272 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800273 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700274 private static final String ATTR_WARNING_BYTES = "warningBytes";
275 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700276 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800277 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
278 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800279 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700280 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700281 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700282 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String ATTR_POLICY = "policy";
284
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800285 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800286 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800287 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800288 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700289
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
291
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700292 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700293 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800294 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800295 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700296 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700297 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
298 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700299 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700300 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700301 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700302
Jeff Sharkey75279902011-05-24 18:39:45 -0700303 private final Context mContext;
304 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700305 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700306 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700307 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700308 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700309 private final UserManager mUserManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700310
311 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700312 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700313 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700314 private IDeviceIdleController mDeviceIdleController;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700315
Felipe Lemef0823852016-06-08 13:43:08 -0700316 // See main javadoc for instructions on how to use these locks.
317 final Object mUidRulesFirstLock = new Object();
318 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700319
Felipe Lemef0823852016-06-08 13:43:08 -0700320 @GuardedBy("allLocks") volatile boolean mSystemReady;
321
Felipe Lemef0823852016-06-08 13:43:08 -0700322 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
323 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
324 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700325
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700326 private final boolean mSuppressDefaultPolicy;
327
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700328 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800329 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800331 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700332
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700333 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700334 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700335 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700336 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700337
Felipe Lemef0823852016-06-08 13:43:08 -0700338 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700339 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700340 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700341 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700342 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800343 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700344
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700345 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700346 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700347 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
348
Jeff Sharkey32566012014-12-02 18:30:14 -0800349 /**
350 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700351 * in power save mode, except device idle (doze) still applies.
352 * TODO: An int array might be sufficient
353 */
Felipe Lemef0823852016-06-08 13:43:08 -0700354 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700355 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
356
357 /**
358 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800359 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700360 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800361 */
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700363 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700364
Felipe Lemef0823852016-06-08 13:43:08 -0700365 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700366 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
367
Felipe Lemeb85a6372016-01-14 16:16:16 -0800368 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800369 * UIDs that have been initially white-listed by system to avoid restricted background.
370 */
Felipe Lemef0823852016-06-08 13:43:08 -0700371 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800372 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
373 new SparseBooleanArray();
374
375 /**
376 * UIDs that have been initially white-listed by system to avoid restricted background,
377 * but later revoked by user.
378 */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800380 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
381 new SparseBooleanArray();
382
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700383 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700384 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800385 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700386 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800388 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700389
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700390 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mNetworkPoliciesSecondLock")
Dianne Hackborn497175b2014-07-01 12:56:08 -0700392 private final ArraySet<String> mActiveNotifs = new ArraySet<String>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700393
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700394 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800396 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700397
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600398 /** Higher priority listener before general event dispatch */
399 private INetworkPolicyListener mConnectivityListener;
400
Jeff Sharkey32566012014-12-02 18:30:14 -0800401 private final RemoteCallbackList<INetworkPolicyListener>
402 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700403
Dianne Hackborn497175b2014-07-01 12:56:08 -0700404 final Handler mHandler;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700405
Felipe Lemef0823852016-06-08 13:43:08 -0700406 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700407 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700408
Svet Ganov16a16892015-04-16 10:32:04 -0700409 private final AppOpsManager mAppOps;
410
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800411 private final IPackageManager mIPm;
412
Felipe Lemeb85a6372016-01-14 16:16:16 -0800413
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700414 // TODO: keep whitelist of system-critical services that should never have
415 // rules enforced, such as system, phone, and radio UIDs.
416
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700417 // TODO: migrate notifications to SystemUI
418
Jeff Sharkey75279902011-05-24 18:39:45 -0700419 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700420 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
421 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700422 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
423 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700424 }
425
426 private static File getSystemDir() {
427 return new File(Environment.getDataDirectory(), "system");
428 }
429
430 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700431 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700432 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700433 mContext = checkNotNull(context, "missing context");
434 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700435 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700436 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700437 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700438 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700440 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700441 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700442
Amith Yamasani450a16b2013-09-18 16:28:50 -0700443 HandlerThread thread = new HandlerThread(TAG);
444 thread.start();
445 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700446
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700447 mSuppressDefaultPolicy = suppressDefaultPolicy;
448
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700449 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700450
451 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800452
Felipe Lemed17fda42016-04-29 11:12:45 -0700453 // Expose private service for system components to use.
454 LocalServices.addService(NetworkPolicyManagerInternal.class,
455 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700456 }
457
458 public void bindConnectivityManager(IConnectivityManager connManager) {
459 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700460 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700461
Jeff Sharkey497e4432011-06-14 17:27:29 -0700462 public void bindNotificationManager(INotificationManager notifManager) {
463 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
464 }
465
Felipe Lemef0823852016-06-08 13:43:08 -0700466 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700467 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700468 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
469 mPowerSaveWhitelistExceptIdleAppIds.clear();
470 if (whitelist != null) {
471 for (int uid : whitelist) {
472 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
473 }
474 }
475 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700476 mPowerSaveWhitelistAppIds.clear();
477 if (whitelist != null) {
478 for (int uid : whitelist) {
479 mPowerSaveWhitelistAppIds.put(uid, true);
480 }
481 }
482 } catch (RemoteException e) {
483 }
484 }
485
Felipe Lemea9505cc2016-02-26 10:28:41 -0800486 /**
487 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
488 * revoke the whitelist.
489 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700490 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800491 */
Felipe Lemef0823852016-06-08 13:43:08 -0700492 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800493 final List<UserInfo> users = mUserManager.getUsers();
494 final int numberUsers = users.size();
495
Felipe Lemea110eec2016-04-29 09:58:06 -0700496 boolean changed = false;
497 for (int i = 0; i < numberUsers; i++) {
498 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700499 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700500 }
501 return changed;
502 }
503
Felipe Lemef0823852016-06-08 13:43:08 -0700504 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700505 final SystemConfig sysConfig = SystemConfig.getInstance();
506 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800507 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
508 boolean changed = false;
509 for (int i = 0; i < allowDataUsage.size(); i++) {
510 final String pkg = allowDataUsage.valueAt(i);
511 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700512 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
513 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800514 final ApplicationInfo app;
515 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700516 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800517 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700518 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
519 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800520 continue;
521 }
522 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700523 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
524 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800525 continue;
526 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700527 final int uid = UserHandle.getUid(userId, app.uid);
528 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
529 if (LOGD)
530 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
531 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800532 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700533 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700534 if (LOGD)
535 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
536 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700537 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700538 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800539 }
540 }
541 return changed;
542 }
543
Felipe Lemef0823852016-06-08 13:43:08 -0700544 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700545 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700546 // Clear the states of the current whitelist
547 final int N = mPowerSaveTempWhitelistAppIds.size();
548 for (int i = 0; i < N; i++) {
549 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
550 }
551 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700552 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700553 if (whitelist != null) {
554 for (int uid : whitelist) {
555 mPowerSaveTempWhitelistAppIds.put(uid, true);
556 }
557 }
558 } catch (RemoteException e) {
559 }
560 }
561
Amith Yamasani06f08062015-06-12 13:23:33 -0700562 /**
563 * Remove unnecessary entries in the temp whitelist
564 */
Felipe Lemef0823852016-06-08 13:43:08 -0700565 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700566 final int N = mPowerSaveTempWhitelistAppIds.size();
567 for (int i = N - 1; i >= 0; i--) {
568 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
569 mPowerSaveTempWhitelistAppIds.removeAt(i);
570 }
571 }
572 }
573
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800574 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700575 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800576 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700577 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800578 // Boost thread's priority during system server init
579 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700580 if (!isBandwidthControlEnabled()) {
581 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
582 return;
583 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700584
Felipe Leme873a83a2016-09-07 11:34:10 -0700585 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700586
Felipe Leme873a83a2016-09-07 11:34:10 -0700587 synchronized (mUidRulesFirstLock) {
588 synchronized (mNetworkPoliciesSecondLock) {
589 updatePowerSaveWhitelistUL();
590 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
591 mPowerManagerInternal.registerLowPowerModeObserver(
592 new PowerManagerInternal.LowPowerModeListener() {
593 @Override
594 public void onLowPowerModeChanged(boolean enabled) {
595 if (LOGD) Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
596 synchronized (mUidRulesFirstLock) {
597 if (mRestrictPower != enabled) {
598 mRestrictPower = enabled;
599 updateRulesForRestrictPowerUL();
600 }
Felipe Lemef0823852016-06-08 13:43:08 -0700601 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700602 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700603 });
604 mRestrictPower = mPowerManagerInternal.getLowPowerModeEnabled();
605
606 mSystemReady = true;
607
608 // read policy from disk
609 readPolicyAL();
610
611 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
612 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700613 }
Felipe Lemef0823852016-06-08 13:43:08 -0700614
Felipe Leme873a83a2016-09-07 11:34:10 -0700615 setRestrictBackgroundUL(mRestrictBackground);
616 updateRulesForGlobalChangeAL(false);
617 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700618 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800619 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700620
621 try {
622 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000623 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800624 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 mNetworkManager.registerObserver(mAlertObserver);
626 } catch (RemoteException e) {
627 // ignored; both services live in system_server
628 }
629
630 // listen for changes to power save whitelist
631 final IntentFilter whitelistFilter = new IntentFilter(
632 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
633 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
634
635 DeviceIdleController.LocalService deviceIdleService
636 = LocalServices.getService(DeviceIdleController.LocalService.class);
637 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
638
639 // watch for network interfaces to be claimed
640 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
641 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
642
643 // listen for package changes to update policy
644 final IntentFilter packageFilter = new IntentFilter();
645 packageFilter.addAction(ACTION_PACKAGE_ADDED);
646 packageFilter.addDataScheme("package");
647 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
648
649 // listen for UID changes to update policy
650 mContext.registerReceiver(
651 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
652
653 // listen for user changes to update policy
654 final IntentFilter userFilter = new IntentFilter();
655 userFilter.addAction(ACTION_USER_ADDED);
656 userFilter.addAction(ACTION_USER_REMOVED);
657 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
658
659 // listen for stats update events
660 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
661 mContext.registerReceiver(
662 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
663
664 // listen for restrict background changes from notifications
665 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
666 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
667
668 // listen for snooze warning from notifications
669 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
670 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
671 MANAGE_NETWORK_POLICY, mHandler);
672
673 // listen for configured wifi networks to be removed
674 final IntentFilter wifiConfigFilter =
675 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
676 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
677
678 // listen for wifi state changes to catch metered hint
679 final IntentFilter wifiStateFilter = new IntentFilter(
680 WifiManager.NETWORK_STATE_CHANGED_ACTION);
681 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
682
683 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800684 // tell systemReady() that the service has been initialized
685 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700686 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800687 // Restore the default priority after init is done
688 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700689 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700690 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700691 }
692
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800693 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
694 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
695 mHandler.post(() -> initService(initCompleteSignal));
696 return initCompleteSignal;
697 }
698
699 public void systemReady(CountDownLatch initCompleteSignal) {
700 // wait for initService to complete
701 try {
702 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
703 throw new IllegalStateException("Service " + TAG +" init timeout");
704 }
705 } catch (InterruptedException e) {
706 Thread.currentThread().interrupt();
707 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
708 }
709 }
710
Sudheer Shankac9d94072017-02-22 22:13:55 +0000711 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
712 @Override public void onUidStateChanged(int uid, int procState) throws RemoteException {
Felipe Leme873a83a2016-09-07 11:34:10 -0700713 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
714 try {
715 synchronized (mUidRulesFirstLock) {
Sudheer Shankac9d94072017-02-22 22:13:55 +0000716 updateUidStateUL(uid, procState);
Felipe Leme873a83a2016-09-07 11:34:10 -0700717 }
718 } finally {
719 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700720 }
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700721 }
722
Dianne Hackborne07641d2016-11-09 15:07:23 -0800723 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Felipe Lemef0823852016-06-08 13:43:08 -0700724 synchronized (mUidRulesFirstLock) {
725 removeUidStateUL(uid);
Dianne Hackborn497175b2014-07-01 12:56:08 -0700726 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700727 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700728
729 @Override public void onUidActive(int uid) throws RemoteException {
730 }
731
Dianne Hackborne07641d2016-11-09 15:07:23 -0800732 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700733 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700734 };
735
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700736 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700737 @Override
738 public void onReceive(Context context, Intent intent) {
739 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700740 synchronized (mUidRulesFirstLock) {
741 updatePowerSaveWhitelistUL();
742 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700743 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700744 }
745 }
746 };
747
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700748 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
749 @Override
750 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700751 synchronized (mUidRulesFirstLock) {
752 updatePowerSaveTempWhitelistUL();
753 updateRulesForTempWhitelistChangeUL();
754 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700755 }
756 }
757 };
758
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700759 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700760 @Override
761 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700762 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700763
764 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700765 final int uid = intent.getIntExtra(EXTRA_UID, -1);
766 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700767
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700768 if (ACTION_PACKAGE_ADDED.equals(action)) {
769 // update rules for UID, since it might be subject to
770 // global background data policy
771 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700772 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700773 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700774 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700775 }
776 }
777 };
778
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700779 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700780 @Override
781 public void onReceive(Context context, Intent intent) {
782 // on background handler thread, and UID_REMOVED is protected
783
784 final int uid = intent.getIntExtra(EXTRA_UID, -1);
785 if (uid == -1) return;
786
787 // remove any policy and update rules to clean up
788 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700789 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700790 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700791 synchronized (mNetworkPoliciesSecondLock) {
792 writePolicyAL();
793 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700794 }
795 }
796 };
797
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700798 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700799 @Override
800 public void onReceive(Context context, Intent intent) {
801 // on background handler thread, and USER_ADDED and USER_REMOVED
802 // broadcasts are protected
803
804 final String action = intent.getAction();
805 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
806 if (userId == -1) return;
807
Amith Yamasani15e472352015-04-24 19:06:07 -0700808 switch (action) {
809 case ACTION_USER_REMOVED:
810 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700811 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800812 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700813 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700814 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700815 if (action == ACTION_USER_ADDED) {
816 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700817 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700818 }
819 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700820 synchronized (mNetworkPoliciesSecondLock) {
821 updateRulesForGlobalChangeAL(true);
822 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700823 }
824 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700825 }
826 }
827 };
828
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700829 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700830 * Receiver that watches for {@link INetworkStatsService} updates, which we
831 * use to check against {@link NetworkPolicy#warningBytes}.
832 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700833 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700834 @Override
835 public void onReceive(Context context, Intent intent) {
836 // on background handler thread, and verified
837 // READ_NETWORK_USAGE_HISTORY permission above.
838
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800839 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700840 synchronized (mNetworkPoliciesSecondLock) {
841 updateNetworkEnabledNL();
842 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700843 }
844 }
845 };
846
847 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700848 * Receiver that watches for {@link Notification} control of
849 * {@link #mRestrictBackground}.
850 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700851 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700852 @Override
853 public void onReceive(Context context, Intent intent) {
854 // on background handler thread, and verified MANAGE_NETWORK_POLICY
855 // permission above.
856
857 setRestrictBackground(false);
858 }
859 };
860
861 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800862 * Receiver that watches for {@link Notification} control of
863 * {@link NetworkPolicy#lastWarningSnooze}.
864 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700865 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800866 @Override
867 public void onReceive(Context context, Intent intent) {
868 // on background handler thread, and verified MANAGE_NETWORK_POLICY
869 // permission above.
870
871 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
872 performSnooze(template, TYPE_WARNING);
873 }
874 };
875
876 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700877 * Receiver that watches for {@link WifiConfiguration} to be changed.
878 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700879 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700880 @Override
881 public void onReceive(Context context, Intent intent) {
882 // on background handler thread, and verified CONNECTIVITY_INTERNAL
883 // permission above.
884
885 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
886 if (reason == CHANGE_REASON_REMOVED) {
887 final WifiConfiguration config = intent.getParcelableExtra(
888 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700889 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800890 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700891 synchronized (mUidRulesFirstLock) {
892 synchronized (mNetworkPoliciesSecondLock) {
893 if (mNetworkPolicy.containsKey(template)) {
894 mNetworkPolicy.remove(template);
895 writePolicyAL();
896 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700897 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700898 }
899 }
900 }
901 }
902 };
903
904 /**
905 * Receiver that watches {@link WifiInfo} state changes to infer metered
906 * state. Ignores hints when policy is user-defined.
907 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700908 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700909 @Override
910 public void onReceive(Context context, Intent intent) {
911 // on background handler thread, and verified CONNECTIVITY_INTERNAL
912 // permission above.
913
914 // ignore when not connected
915 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
916 if (!netInfo.isConnected()) return;
917
918 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
919 final boolean meteredHint = info.getMeteredHint();
920
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800921 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -0700922 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700923 NetworkPolicy policy = mNetworkPolicy.get(template);
924 if (policy == null && meteredHint) {
925 // policy doesn't exist, and AP is hinting that it's
926 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800927 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -0700928 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700929
930 } else if (policy != null && policy.inferred) {
931 // policy exists, and was inferred: update its current
932 // metered state.
933 policy.metered = meteredHint;
934
935 // since this is inferred for each wifi session, just update
936 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -0700937 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700938 }
939 }
940 }
941 };
942
Felipe Lemeb1a65ee2016-02-08 10:12:01 -0800943 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
944 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
945 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
946 metered, true);
947 }
948
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700949 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700950 * Observer that watches for {@link INetworkManagementService} alerts.
951 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700952 final private INetworkManagementEventObserver mAlertObserver
953 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700954 @Override
955 public void limitReached(String limitName, String iface) {
956 // only someone like NMS should be calling us
957 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
958
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800959 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
960 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700961 }
962 }
963 };
964
965 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700966 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
967 * to show visible notifications as needed.
968 */
Felipe Lemef0823852016-06-08 13:43:08 -0700969 void updateNotificationsNL() {
970 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700971
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700972 // keep track of previously active notifications
Dianne Hackborn497175b2014-07-01 12:56:08 -0700973 final ArraySet<String> beforeNotifs = new ArraySet<String>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700974 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700975
976 // TODO: when switching to kernel notifications, compute next future
977 // cycle boundary to recompute notifications.
978
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700979 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800980 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700981 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
982 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700983 // ignore policies that aren't relevant to user
984 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700985 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700986
Jeff Sharkey497e4432011-06-14 17:27:29 -0700987 final long start = computeLastCycleBoundary(currentTime, policy);
988 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700989 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -0700990
Jeff Sharkey50e7e512011-10-10 16:50:35 -0700991 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800992 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700993 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
994 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700995 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -0700996 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700997 }
998
Jeff Sharkey497e4432011-06-14 17:27:29 -0700999 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001000 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001001
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001002 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001003 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001004 }
1005 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001006 }
1007
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001008 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001009 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
1010 final String tag = beforeNotifs.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 if (!mActiveNotifs.contains(tag)) {
1012 cancelNotification(tag);
1013 }
1014 }
1015 }
1016
1017 /**
1018 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001019 * current device state, such as when
1020 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1021 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001022 */
1023 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001024 if (template.isMatchRuleMobile()) {
1025 final TelephonyManager tele = TelephonyManager.from(mContext);
1026 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001027
Jeff Sharkey32566012014-12-02 18:30:14 -08001028 // Mobile template is relevant when any active subscriber matches
1029 final int[] subIds = sub.getActiveSubscriptionIdList();
1030 for (int subId : subIds) {
1031 final String subscriberId = tele.getSubscriberId(subId);
1032 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001033 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001034 if (template.matches(probeIdent)) {
1035 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001036 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001037 }
1038 return false;
1039 } else {
1040 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001041 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001042 }
1043
1044 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 * Notify that given {@link NetworkTemplate} is over
1046 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1047 */
Felipe Lemef0823852016-06-08 13:43:08 -07001048 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001049 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001050 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001051 mOverLimitNotified.add(template);
1052 }
1053 }
1054
Felipe Lemef0823852016-06-08 13:43:08 -07001055 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001056 mOverLimitNotified.remove(template);
1057 }
1058
1059 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001060 * Build unique tag that identifies an active {@link NetworkPolicy}
1061 * notification of a specific type, like {@link #TYPE_LIMIT}.
1062 */
1063 private String buildNotificationTag(NetworkPolicy policy, int type) {
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001064 return TAG + ":" + policy.template.hashCode() + ":" + type;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001065 }
1066
1067 /**
1068 * Show notification for combined {@link NetworkPolicy} and specific type,
1069 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1070 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 final String tag = buildNotificationTag(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001073 final Notification.Builder builder =
1074 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001076 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001077 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001078 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001079
1080 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001081 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082 switch (type) {
1083 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001084 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001085 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001086
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001087 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 builder.setTicker(title);
1089 builder.setContentTitle(title);
1090 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001091 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001092 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001093
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001094 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1095 builder.setDeleteIntent(PendingIntent.getBroadcast(
1096 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1097
Wei Liu546cb772016-07-21 16:19:01 -07001098 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001099 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001100 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1101
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 break;
1103 }
1104 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001105 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001106
1107 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001108 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001109 switch (policy.template.getMatchRule()) {
1110 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001111 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001112 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001113 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001114 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001115 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001116 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001117 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001118 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001119 case MATCH_WIFI:
1120 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001121 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001122 break;
1123 default:
1124 title = null;
1125 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001126 }
1127
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001128 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001129 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130 builder.setTicker(title);
1131 builder.setContentTitle(title);
1132 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001133
Wei Liu546cb772016-07-21 16:19:01 -07001134 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001135 builder.setContentIntent(PendingIntent.getActivity(
1136 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1137 break;
1138 }
1139 case TYPE_LIMIT_SNOOZED: {
1140 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001141 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 Formatter.formatFileSize(mContext, overBytes));
1143
1144 final CharSequence title;
1145 switch (policy.template.getMatchRule()) {
1146 case MATCH_MOBILE_3G_LOWER:
1147 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1148 break;
1149 case MATCH_MOBILE_4G:
1150 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1151 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001152 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001153 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1154 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001155 case MATCH_WIFI:
1156 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1157 break;
1158 default:
1159 title = null;
1160 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001161 }
1162
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001163 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001164 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001165 builder.setTicker(title);
1166 builder.setContentTitle(title);
1167 builder.setContentText(body);
1168
Wei Liu546cb772016-07-21 16:19:01 -07001169 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001170 builder.setContentIntent(PendingIntent.getActivity(
1171 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001172 break;
1173 }
1174 }
1175
1176 // TODO: move to NotificationManager once we can mock it
1177 try {
1178 final String packageName = mContext.getPackageName();
1179 final int[] idReceived = new int[1];
Chris Wren8a3d56c2016-08-01 15:52:52 -04001180 if(!TextUtils.isEmpty(body)) {
1181 builder.setStyle(new Notification.BigTextStyle()
1182 .bigText(body));
1183 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 mNotifManager.enqueueNotificationWithTag(
Chris Wren8a3d56c2016-08-01 15:52:52 -04001185 packageName, packageName, tag, 0x0, builder.build(), idReceived,
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001186 UserHandle.USER_ALL);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001187 mActiveNotifs.add(tag);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001189 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001190 }
1191 }
1192
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001193 private void cancelNotification(String tag) {
1194 // TODO: move to NotificationManager once we can mock it
1195 try {
1196 final String packageName = mContext.getPackageName();
1197 mNotifManager.cancelNotificationWithTag(
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001198 packageName, tag, 0x0, UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001199 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001200 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001201 }
1202 }
1203
1204 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001205 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001206 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001207 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001208 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001209 @Override
1210 public void onReceive(Context context, Intent intent) {
1211 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1212 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001213
1214 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001215 synchronized (mNetworkPoliciesSecondLock) {
1216 ensureActiveMobilePolicyNL();
1217 normalizePoliciesNL();
1218 updateNetworkEnabledNL();
1219 updateNetworkRulesNL();
1220 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001221 }
1222 }
1223 };
1224
1225 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001226 * Proactively control network data connections when they exceed
1227 * {@link NetworkPolicy#limitBytes}.
1228 */
Felipe Lemef0823852016-06-08 13:43:08 -07001229 void updateNetworkEnabledNL() {
1230 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001231
1232 // TODO: reset any policy-disabled networks when any policy is removed
1233 // completely, which is currently rare case.
1234
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001235 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001236 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1237 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001238 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001239 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001240 setNetworkTemplateEnabled(policy.template, true);
1241 continue;
1242 }
1243
1244 final long start = computeLastCycleBoundary(currentTime, policy);
1245 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001246 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001247
1248 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001249 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1250 && policy.lastLimitSnooze < start;
1251 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001252
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001253 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001254 }
1255 }
1256
1257 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001258 * Proactively disable networks that match the given
1259 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001260 */
1261 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001262 // TODO: reach into ConnectivityManager to proactively disable bringing
1263 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001264
1265 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1266 // If mobile data usage hits the limit or if the user resumes the data, we need to
1267 // notify telephony.
1268 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1269 final TelephonyManager tm = TelephonyManager.from(mContext);
1270
1271 final int[] subIds = sm.getActiveSubscriptionIdList();
1272 for (int subId : subIds) {
1273 final String subscriberId = tm.getSubscriberId(subId);
1274 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1275 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1276 // Template is matched when subscriber id matches.
1277 if (template.matches(probeIdent)) {
1278 tm.setPolicyDataEnabled(enabled, subId);
1279 }
1280 }
1281 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001282 }
1283
1284 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285 * Examine all connected {@link NetworkState}, looking for
1286 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1287 * remaining quota based on usage cycle and historical stats.
1288 */
Felipe Lemef0823852016-06-08 13:43:08 -07001289 void updateNetworkRulesNL() {
1290 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001291
1292 final NetworkState[] states;
1293 try {
1294 states = mConnManager.getAllNetworkState();
1295 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001296 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001297 return;
1298 }
1299
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001300 // First, generate identities of all connected networks so we can
1301 // quickly compare them against all defined policies below.
1302 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001303 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001304 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001305 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001306 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001307
1308 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001309 if (baseIface != null) {
1310 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001311 }
1312
1313 // Stacked interfaces are considered to have same identity as
1314 // their parent network.
1315 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1316 for (LinkProperties stackedLink : stackedLinks) {
1317 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001318 if (stackedIface != null) {
1319 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001320 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001321 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001322 }
1323 }
1324
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001325 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001326 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001327 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001328 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001329 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001330
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001331 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001332 for (int j = connIdents.size() - 1; j >= 0; j--) {
1333 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1334 if (policy.template.matches(ident.second)) {
1335 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001336 }
1337 }
1338
1339 if (ifaceList.size() > 0) {
1340 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001341 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001342 }
1343 }
1344
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001345 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001346 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001347
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001348 // apply each policy that we found ifaces for; compute remaining data
1349 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001350 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001351 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1352 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1353 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001354
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001355 final long start;
1356 final long totalBytes;
1357 if (policy.hasCycle()) {
1358 start = computeLastCycleBoundary(currentTime, policy);
1359 totalBytes = getTotalBytes(policy.template, start, currentTime);
1360 } else {
1361 start = Long.MAX_VALUE;
1362 totalBytes = 0;
1363 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001364
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001365 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001366 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001367 }
1368
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001369 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001370 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001371 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001372 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001373 if (!hasLimit) {
1374 // metered network, but no policy limit; we still need to
1375 // restrict apps, so push really high quota.
1376 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001377 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001378 // snoozing past quota, but we still need to restrict apps,
1379 // so push really high quota.
1380 quotaBytes = Long.MAX_VALUE;
1381 } else {
1382 // remaining "quota" bytes are based on total usage in
1383 // current cycle. kernel doesn't like 0-byte rules, so we
1384 // set 1-byte quota and disable the radio later.
1385 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1386 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001387
1388 if (ifaces.length > 1) {
1389 // TODO: switch to shared quota once NMS supports
1390 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001391 }
1392
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001394 // long quotaBytes split up into two ints to fit in message
1395 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1396 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1397 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001398 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001399 }
1400 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001401
1402 // keep track of lowest warning or limit of active policies
1403 if (hasWarning && policy.warningBytes < lowestRule) {
1404 lowestRule = policy.warningBytes;
1405 }
1406 if (hasLimit && policy.limitBytes < lowestRule) {
1407 lowestRule = policy.limitBytes;
1408 }
1409 }
1410
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001411 for (int i = connIfaces.size()-1; i >= 0; i--) {
1412 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001413 // long quotaBytes split up into two ints to fit in message
1414 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1415 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1416 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001417 newMeteredIfaces.add(iface);
1418 }
1419
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001420 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001421
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001422 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001423 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1424 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001425 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001426 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1427 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001428 }
1429 }
1430 mMeteredIfaces = newMeteredIfaces;
1431
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001432 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001433 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001434 }
1435
1436 /**
1437 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1438 * have at least a default mobile policy defined.
1439 */
Felipe Lemef0823852016-06-08 13:43:08 -07001440 private void ensureActiveMobilePolicyNL() {
1441 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001442 if (mSuppressDefaultPolicy) return;
1443
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001444 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001445 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001446
Jeff Sharkey32566012014-12-02 18:30:14 -08001447 final int[] subIds = sub.getActiveSubscriptionIdList();
1448 for (int subId : subIds) {
1449 final String subscriberId = tele.getSubscriberId(subId);
Felipe Lemef0823852016-06-08 13:43:08 -07001450 ensureActiveMobilePolicyNL(subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001451 }
1452 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001453
Felipe Lemef0823852016-06-08 13:43:08 -07001454 private void ensureActiveMobilePolicyNL(String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001455 // Poke around to see if we already have a policy
1456 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001457 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001458 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1459 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1460 if (template.matches(probeIdent)) {
1461 if (LOGD) {
1462 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1463 + NetworkIdentity.scrubSubscriberId(subscriberId));
1464 }
1465 return;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001466 }
1467 }
1468
Jeff Sharkey32566012014-12-02 18:30:14 -08001469 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1470 + "; generating default policy");
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001471
Jeff Sharkey32566012014-12-02 18:30:14 -08001472 // Build default mobile policy, and assume usage cycle starts today
Fan Zhangda71ca02016-09-12 17:36:22 -07001473 final int dataWarningConfig = mContext.getResources().getInteger(
1474 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
1475 final long warningBytes;
1476 if (dataWarningConfig == WARNING_DISABLED) {
1477 warningBytes = WARNING_DISABLED;
1478 } else {
1479 warningBytes = dataWarningConfig * MB_IN_BYTES;
1480 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001481
Jeff Sharkey32566012014-12-02 18:30:14 -08001482 final Time time = new Time();
1483 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001484
Jeff Sharkey32566012014-12-02 18:30:14 -08001485 final int cycleDay = time.monthDay;
1486 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001487
Jeff Sharkey32566012014-12-02 18:30:14 -08001488 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1489 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
1490 warningBytes, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
Felipe Lemef0823852016-06-08 13:43:08 -07001491 addNetworkPolicyNL(policy);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001492 }
1493
Felipe Lemef0823852016-06-08 13:43:08 -07001494 private void readPolicyAL() {
1495 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001496
1497 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001498 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001499 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001500
1501 FileInputStream fis = null;
1502 try {
1503 fis = mPolicyFile.openRead();
1504 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001505 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001506
Felipe Leme46b451f2016-08-19 08:46:17 -07001507 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1508 // to skip UIDs that were explicitly blacklisted.
1509 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1510
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001511 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001512 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001513 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001514 while ((type = in.next()) != END_DOCUMENT) {
1515 final String tag = in.getName();
1516 if (type == START_TAG) {
1517 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001518 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001519 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001520 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1521 mRestrictBackground = readBooleanAttribute(
1522 in, ATTR_RESTRICT_BACKGROUND);
1523 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001524 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001525 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001526 if (mRestrictBackground != oldValue) {
1527 // Some early services may have read the default value,
1528 // so notify them that it's changed
1529 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1530 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1531 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001532
1533 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1534 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1535 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001536 final String networkId;
1537 if (version >= VERSION_ADDED_NETWORK_ID) {
1538 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1539 } else {
1540 networkId = null;
1541 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001543 final String cycleTimezone;
1544 if (version >= VERSION_ADDED_TIMEZONE) {
1545 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1546 } else {
1547 cycleTimezone = Time.TIMEZONE_UTC;
1548 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001549 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1550 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001551 final long lastLimitSnooze;
1552 if (version >= VERSION_SPLIT_SNOOZE) {
1553 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1554 } else if (version >= VERSION_ADDED_SNOOZE) {
1555 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001556 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001557 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001558 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001559 final boolean metered;
1560 if (version >= VERSION_ADDED_METERED) {
1561 metered = readBooleanAttribute(in, ATTR_METERED);
1562 } else {
1563 switch (networkTemplate) {
1564 case MATCH_MOBILE_3G_LOWER:
1565 case MATCH_MOBILE_4G:
1566 case MATCH_MOBILE_ALL:
1567 metered = true;
1568 break;
1569 default:
1570 metered = false;
1571 }
1572 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001573 final long lastWarningSnooze;
1574 if (version >= VERSION_SPLIT_SNOOZE) {
1575 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1576 } else {
1577 lastWarningSnooze = SNOOZE_NEVER;
1578 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001579 final boolean inferred;
1580 if (version >= VERSION_ADDED_INFERRED) {
1581 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1582 } else {
1583 inferred = false;
1584 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585
Jeff Sharkey32566012014-12-02 18:30:14 -08001586 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1587 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001588 if (template.isPersistable()) {
1589 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1590 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1591 lastLimitSnooze, metered, inferred));
1592 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001594 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001595 final int uid = readIntAttribute(in, ATTR_UID);
1596 final int policy = readIntAttribute(in, ATTR_POLICY);
1597
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001598 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001599 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001600 } else {
1601 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1602 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001603 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001604 final int appId = readIntAttribute(in, ATTR_APP_ID);
1605 final int policy = readIntAttribute(in, ATTR_POLICY);
1606
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001607 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001608 // app policy is deprecated so this is only used in pre system user split.
1609 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001610 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001611 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001612 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001613 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001614 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001615 } else if (TAG_WHITELIST.equals(tag)) {
1616 insideWhitelist = true;
1617 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1618 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001619 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001620 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1621 final int uid = readIntAttribute(in, ATTR_UID);
1622 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001623 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001624 } else if (type == END_TAG) {
1625 if (TAG_WHITELIST.equals(tag)) {
1626 insideWhitelist = false;
1627 }
1628
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001629 }
1630 }
1631
Felipe Leme46b451f2016-08-19 08:46:17 -07001632 final int size = whitelistedRestrictBackground.size();
1633 for (int i = 0; i < size; i++) {
1634 final int uid = whitelistedRestrictBackground.keyAt(i);
1635 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1636 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1637 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1638 + " because its policy is " + uidPoliciesToString(policy));
1639 continue;
1640 }
1641 if (UserHandle.isApp(uid)) {
1642 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1643 if (LOGV)
1644 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1645 setUidPolicyUncheckedUL(uid, newPolicy, false);
1646 } else {
1647 Slog.w(TAG, "unable to update policy on UID " + uid);
1648 }
1649 }
1650
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 } catch (FileNotFoundException e) {
1652 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001653 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001655 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001657 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001658 } finally {
1659 IoUtils.closeQuietly(fis);
1660 }
1661 }
1662
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001663 /**
1664 * Upgrade legacy background data flags, notifying listeners of one last
1665 * change to always-true.
1666 */
Felipe Lemef0823852016-06-08 13:43:08 -07001667 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001668 mRestrictBackground = Settings.Secure.getInt(
1669 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1670
1671 // kick off one last broadcast if restricted
1672 if (mRestrictBackground) {
1673 final Intent broadcast = new Intent(
1674 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001675 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001676 }
1677 }
1678
Felipe Lemef0823852016-06-08 13:43:08 -07001679 void writePolicyAL() {
1680 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001681
1682 FileOutputStream fos = null;
1683 try {
1684 fos = mPolicyFile.startWrite();
1685
1686 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001687 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001688 out.startDocument(null, true);
1689
1690 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001691 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001692 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001693
1694 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001695 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1696 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001697 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001698 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001699
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001700 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001701 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1702 final String subscriberId = template.getSubscriberId();
1703 if (subscriberId != null) {
1704 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001705 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001706 final String networkId = template.getNetworkId();
1707 if (networkId != null) {
1708 out.attribute(null, ATTR_NETWORK_ID, networkId);
1709 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001710 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001711 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001712 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1713 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001714 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1715 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001716 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001717 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001718 out.endTag(null, TAG_NETWORK_POLICY);
1719 }
1720
1721 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001722 for (int i = 0; i < mUidPolicy.size(); i++) {
1723 final int uid = mUidPolicy.keyAt(i);
1724 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001725
Jeff Sharkey497e4432011-06-14 17:27:29 -07001726 // skip writing empty policies
1727 if (policy == POLICY_NONE) continue;
1728
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001729 out.startTag(null, TAG_UID_POLICY);
1730 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001731 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001732 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001733 }
1734
1735 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08001736
1737 // write all whitelists
1738 out.startTag(null, TAG_WHITELIST);
1739
Felipe Lemea9505cc2016-02-26 10:28:41 -08001740 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07001741 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08001742 for (int i = 0; i < size; i++) {
1743 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1744 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1745 writeIntAttribute(out, ATTR_UID, uid);
1746 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
1747 }
1748
Felipe Lemeb85a6372016-01-14 16:16:16 -08001749 out.endTag(null, TAG_WHITELIST);
1750
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751 out.endDocument();
1752
1753 mPolicyFile.finishWrite(fos);
1754 } catch (IOException e) {
1755 if (fos != null) {
1756 mPolicyFile.failWrite(fos);
1757 }
1758 }
1759 }
1760
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001761 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001762 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001763 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001764
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001765 if (!UserHandle.isApp(uid)) {
1766 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001767 }
Felipe Lemef0823852016-06-08 13:43:08 -07001768 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04001769 final long token = Binder.clearCallingIdentity();
1770 try {
1771 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1772 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001773 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04001774 }
1775 } finally {
1776 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001777 }
1778 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001779 }
1780
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001781 @Override
1782 public void addUidPolicy(int uid, int policy) {
1783 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001784
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001785 if (!UserHandle.isApp(uid)) {
1786 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1787 }
1788
Felipe Lemef0823852016-06-08 13:43:08 -07001789 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001790 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1791 policy |= oldPolicy;
1792 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001793 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001794 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001795 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001796 }
1797
1798 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001799 public void removeUidPolicy(int uid, int policy) {
1800 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1801
1802 if (!UserHandle.isApp(uid)) {
1803 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
1804 }
1805
Felipe Lemef0823852016-06-08 13:43:08 -07001806 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001807 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
1808 policy = oldPolicy & ~policy;
1809 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07001810 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001811 }
1812 }
1813 }
1814
Felipe Lemef0823852016-06-08 13:43:08 -07001815 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
1816 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08001817
Felipe Leme57e3d312016-08-23 14:42:52 -07001818 final boolean notifyApp;
1819 if (!isUidValidForWhitelistRules(uid)) {
1820 notifyApp = false;
1821 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001822 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
1823 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
1824 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
1825 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07001826 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
1827 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07001828 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
1829 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
1830 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
1831 if (LOGD)
1832 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
1833 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
1834 }
Felipe Leme57e3d312016-08-23 14:42:52 -07001835 notifyApp = wasBlocked != isBlocked;
1836 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001837 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
1838 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08001839 }
1840
Felipe Lemef0823852016-06-08 13:43:08 -07001841 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07001842 if (policy == POLICY_NONE) {
1843 mUidPolicy.delete(uid);
1844 } else {
1845 mUidPolicy.put(uid, policy);
1846 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001847
1848 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00001849 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001850 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07001851 synchronized (mNetworkPoliciesSecondLock) {
1852 writePolicyAL();
1853 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001854 }
1855 }
1856
1857 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001858 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001859 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1860
Felipe Lemef0823852016-06-08 13:43:08 -07001861 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001862 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07001863 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07001864 }
1865
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001866 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001867 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001868 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1869
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001870 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07001871 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001872 for (int i = 0; i < mUidPolicy.size(); i++) {
1873 final int uid = mUidPolicy.keyAt(i);
1874 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07001875 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
1876 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001877 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001878 }
1879 }
1880 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001881 return uids;
1882 }
1883
1884 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07001885 * Removes any persistable state associated with given {@link UserHandle}, persisting
1886 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001887 */
Felipe Lemef0823852016-06-08 13:43:08 -07001888 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07001889
Felipe Lemef0823852016-06-08 13:43:08 -07001890 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07001891 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001892
Felipe Lemea110eec2016-04-29 09:58:06 -07001893 // Remove entries from revoked default restricted background UID whitelist
1894 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
1895 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
1896 if (UserHandle.getUserId(uid) == userId) {
1897 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07001898 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07001899 }
1900 }
1901
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001902 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001903 int[] uids = new int[0];
1904 for (int i = 0; i < mUidPolicy.size(); i++) {
1905 final int uid = mUidPolicy.keyAt(i);
1906 if (UserHandle.getUserId(uid) == userId) {
1907 uids = appendInt(uids, uid);
1908 }
1909 }
1910
1911 if (uids.length > 0) {
1912 for (int uid : uids) {
1913 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001914 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001915 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08001916 }
Felipe Lemef0823852016-06-08 13:43:08 -07001917 synchronized (mNetworkPoliciesSecondLock) {
1918 updateRulesForGlobalChangeAL(true);
1919 if (writePolicy && changed) {
1920 writePolicyAL();
1921 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001922 }
Felipe Lemed17fda42016-04-29 11:12:45 -07001923 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07001924 }
1925
1926 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001927 public void setConnectivityListener(INetworkPolicyListener listener) {
1928 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1929 if (mConnectivityListener != null) {
1930 throw new IllegalStateException("Connectivity listener already registered");
1931 }
1932 mConnectivityListener = listener;
1933 }
1934
1935 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001936 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001937 // TODO: create permission for observing network policy
1938 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001939 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001940 }
1941
1942 @Override
1943 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07001944 // TODO: create permission for observing network policy
1945 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001946 mListeners.unregister(listener);
1947 }
1948
Jeff Sharkey1b861272011-05-22 00:34:52 -07001949 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001950 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001951 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
1952
Felipe Leme6a05eee2016-02-19 14:43:51 -08001953 final long token = Binder.clearCallingIdentity();
1954 try {
1955 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001956 synchronized (mUidRulesFirstLock) {
1957 synchronized (mNetworkPoliciesSecondLock) {
1958 normalizePoliciesNL(policies);
1959 updateNetworkEnabledNL();
1960 updateNetworkRulesNL();
1961 updateNotificationsNL();
1962 writePolicyAL();
1963 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08001964 }
1965 } finally {
1966 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001967 }
1968 }
1969
Felipe Lemef0823852016-06-08 13:43:08 -07001970 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07001971 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08001972 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
1973 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001974 }
1975
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001976 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07001977 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001978 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001979 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07001980 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
1981 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
1982 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001983 } catch (SecurityException e) {
1984 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001985
Amit Mahajan7c5befa2015-07-14 10:26:00 -07001986 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
1987 callingPackage) != AppOpsManager.MODE_ALLOWED) {
1988 return new NetworkPolicy[0];
1989 }
Svet Ganov16a16892015-04-16 10:32:04 -07001990 }
1991
Felipe Lemef0823852016-06-08 13:43:08 -07001992 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001993 final int size = mNetworkPolicy.size();
1994 final NetworkPolicy[] policies = new NetworkPolicy[size];
1995 for (int i = 0; i < size; i++) {
1996 policies[i] = mNetworkPolicy.valueAt(i);
1997 }
1998 return policies;
1999 }
2000 }
2001
Felipe Lemef0823852016-06-08 13:43:08 -07002002 private void normalizePoliciesNL() {
2003 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002004 }
2005
Felipe Lemef0823852016-06-08 13:43:08 -07002006 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002007 final TelephonyManager tele = TelephonyManager.from(mContext);
2008 final String[] merged = tele.getMergedSubscriberIds();
2009
2010 mNetworkPolicy.clear();
2011 for (NetworkPolicy policy : policies) {
2012 // When two normalized templates conflict, prefer the most
2013 // restrictive policy
2014 policy.template = NetworkTemplate.normalize(policy.template, merged);
2015 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2016 if (existing == null || existing.compareTo(policy) > 0) {
2017 if (existing != null) {
2018 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2019 }
2020 mNetworkPolicy.put(policy.template, policy);
2021 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002022 }
2023 }
2024
2025 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002026 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002027 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002028
2029 final long token = Binder.clearCallingIdentity();
2030 try {
2031 performSnooze(template, TYPE_LIMIT);
2032 } finally {
2033 Binder.restoreCallingIdentity(token);
2034 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002035 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002036
Dianne Hackborn497175b2014-07-01 12:56:08 -07002037 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002038 maybeRefreshTrustedTime();
2039 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002040 synchronized (mUidRulesFirstLock) {
2041 synchronized (mNetworkPoliciesSecondLock) {
2042 // find and snooze local policy that matches
2043 final NetworkPolicy policy = mNetworkPolicy.get(template);
2044 if (policy == null) {
2045 throw new IllegalArgumentException("unable to find policy for " + template);
2046 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002047
Felipe Lemef0823852016-06-08 13:43:08 -07002048 switch (type) {
2049 case TYPE_WARNING:
2050 policy.lastWarningSnooze = currentTime;
2051 break;
2052 case TYPE_LIMIT:
2053 policy.lastLimitSnooze = currentTime;
2054 break;
2055 default:
2056 throw new IllegalArgumentException("unexpected type");
2057 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002058
Felipe Lemef0823852016-06-08 13:43:08 -07002059 normalizePoliciesNL();
2060 updateNetworkEnabledNL();
2061 updateNetworkRulesNL();
2062 updateNotificationsNL();
2063 writePolicyAL();
2064 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002065 }
2066 }
2067
2068 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002069 public void onTetheringChanged(String iface, boolean tethering) {
2070 // No need to enforce permission because setRestrictBackground() will do it.
2071 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002072 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002073 if (mRestrictBackground && tethering) {
2074 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2075 setRestrictBackground(false);
2076 }
2077 }
2078 }
2079
2080 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002081 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002082 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002083 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002084 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2085 final long token = Binder.clearCallingIdentity();
2086 try {
2087 maybeRefreshTrustedTime();
2088 synchronized (mUidRulesFirstLock) {
2089 if (restrictBackground == mRestrictBackground) {
2090 // Ideally, UI should never allow this scenario...
2091 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2092 return;
2093 }
2094 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002095 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002096
2097 } finally {
2098 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002099 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002100
Felipe Leme29e72ea2016-09-08 13:26:55 -07002101 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2102 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002103 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002104 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002105 }
2106 }
2107
Felipe Lemef0823852016-06-08 13:43:08 -07002108 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002109 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002110 final boolean oldRestrictBackground = mRestrictBackground;
2111 mRestrictBackground = restrictBackground;
2112 // Must whitelist foreground apps before turning data saver mode on.
2113 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2114 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002115 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002116 try {
2117 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2118 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2119 mRestrictBackground = oldRestrictBackground;
2120 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002121 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002122 return;
2123 }
2124 } catch (RemoteException e) {
2125 // ignored; service lives in system_server
2126 }
Felipe Lemef0823852016-06-08 13:43:08 -07002127 synchronized (mNetworkPoliciesSecondLock) {
2128 updateNotificationsNL();
2129 writePolicyAL();
2130 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002131 }
2132
Felipe Lemeb85a6372016-01-14 16:16:16 -08002133 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002134 public int getRestrictBackgroundByCaller() {
2135 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2136 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002137
Felipe Lemef0823852016-06-08 13:43:08 -07002138 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002139 // Must clear identity because getUidPolicy() is restricted to system.
2140 final long token = Binder.clearCallingIdentity();
2141 final int policy;
2142 try {
2143 policy = getUidPolicy(uid);
2144 } finally {
2145 Binder.restoreCallingIdentity(token);
2146 }
2147 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2148 // App is blacklisted.
2149 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2150 }
Felipe Leme1b103232016-01-22 09:44:57 -08002151 if (!mRestrictBackground) {
2152 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2153 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002154 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002155 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2156 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2157 }
2158 }
2159
2160 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002161 public boolean getRestrictBackground() {
2162 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2163
Felipe Lemef0823852016-06-08 13:43:08 -07002164 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002165 return mRestrictBackground;
2166 }
2167 }
2168
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002169 @Override
2170 public void setDeviceIdleMode(boolean enabled) {
2171 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002172 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2173 try {
2174 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002175 if (mDeviceIdleMode == enabled) {
2176 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002177 }
Felipe Lemeea014392016-09-06 13:59:54 -07002178 mDeviceIdleMode = enabled;
2179 if (mSystemReady) {
2180 // Device idle change means we need to rebuild rules for all
2181 // known apps, so do a global refresh.
2182 updateRulesForRestrictPowerUL();
2183 }
2184 }
2185 if (enabled) {
2186 EventLogTags.writeDeviceIdleOnPhase("net");
2187 } else {
2188 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002189 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002190 } finally {
2191 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002192 }
2193 }
2194
Felipe Lemef0823852016-06-08 13:43:08 -07002195 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002196 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2197 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002198 if (policy.template.matches(ident)) {
2199 return policy;
2200 }
2201 }
2202 return null;
2203 }
2204
2205 @Override
2206 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2207 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2208
2209 // only returns usage summary, so we don't require caller to have
2210 // READ_NETWORK_USAGE_HISTORY.
2211 final long token = Binder.clearCallingIdentity();
2212 try {
2213 return getNetworkQuotaInfoUnchecked(state);
2214 } finally {
2215 Binder.restoreCallingIdentity(token);
2216 }
2217 }
2218
2219 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2220 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2221
2222 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002223 synchronized (mNetworkPoliciesSecondLock) {
2224 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002225 }
2226
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002227 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002228 // missing policy means we can't derive useful quota info
2229 return null;
2230 }
2231
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002232 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002233
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002234 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002235 final long start = computeLastCycleBoundary(currentTime, policy);
2236 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002237 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002238
2239 // report soft and hard limits under policy
2240 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2241 : NetworkQuotaInfo.NO_LIMIT;
2242 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2243 : NetworkQuotaInfo.NO_LIMIT;
2244
2245 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2246 }
2247
Jeff Sharkey46645002011-07-27 21:11:21 -07002248 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002249 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002250 if (state.networkInfo == null) {
2251 return false;
2252 }
2253
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002254 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2255
2256 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002257 synchronized (mNetworkPoliciesSecondLock) {
2258 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002259 }
2260
2261 if (policy != null) {
2262 return policy.metered;
2263 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002264 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002265 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002266 return true;
2267 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002268 return false;
2269 }
2270 }
2271
2272 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002273 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkey75279902011-05-24 18:39:45 -07002274 mContext.enforceCallingOrSelfPermission(DUMP, TAG);
Jeff Sharkey1b861272011-05-22 00:34:52 -07002275
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002276 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2277
Dianne Hackborn497175b2014-07-01 12:56:08 -07002278 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002279 for (String arg : args) {
2280 argSet.add(arg);
2281 }
2282
Felipe Lemef0823852016-06-08 13:43:08 -07002283 synchronized (mUidRulesFirstLock) {
2284 synchronized (mNetworkPoliciesSecondLock) {
2285 if (argSet.contains("--unsnooze")) {
2286 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2287 mNetworkPolicy.valueAt(i).clearSnooze();
2288 }
2289
2290 normalizePoliciesNL();
2291 updateNetworkEnabledNL();
2292 updateNetworkRulesNL();
2293 updateNotificationsNL();
2294 writePolicyAL();
2295
2296 fout.println("Cleared snooze timestamps");
2297 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002298 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002299
Felipe Lemef0823852016-06-08 13:43:08 -07002300 fout.print("System ready: "); fout.println(mSystemReady);
2301 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2302 fout.print("Restrict power: "); fout.println(mRestrictPower);
2303 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2304 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002305 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002306 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2307 fout.println(mNetworkPolicy.valueAt(i).toString());
2308 }
2309 fout.decreaseIndent();
2310
2311 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2312
2313 fout.println("Policy for UIDs:");
2314 fout.increaseIndent();
2315 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002316 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002317 final int uid = mUidPolicy.keyAt(i);
2318 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002319 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002320 fout.print(uid);
2321 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002322 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002323 fout.println();
2324 }
2325 fout.decreaseIndent();
2326
2327 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2328 if (size > 0) {
2329 fout.println("Power save whitelist (except idle) app ids:");
2330 fout.increaseIndent();
2331 for (int i = 0; i < size; i++) {
2332 fout.print("UID=");
2333 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2334 fout.print(": ");
2335 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2336 fout.println();
2337 }
2338 fout.decreaseIndent();
2339 }
2340
2341 size = mPowerSaveWhitelistAppIds.size();
2342 if (size > 0) {
2343 fout.println("Power save whitelist app ids:");
2344 fout.increaseIndent();
2345 for (int i = 0; i < size; i++) {
2346 fout.print("UID=");
2347 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2348 fout.print(": ");
2349 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2350 fout.println();
2351 }
2352 fout.decreaseIndent();
2353 }
2354
Felipe Lemef0823852016-06-08 13:43:08 -07002355 size = mDefaultRestrictBackgroundWhitelistUids.size();
2356 if (size > 0) {
2357 fout.println("Default restrict background whitelist uids:");
2358 fout.increaseIndent();
2359 for (int i = 0; i < size; i++) {
2360 fout.print("UID=");
2361 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2362 fout.println();
2363 }
2364 fout.decreaseIndent();
2365 }
2366
2367 size = mRestrictBackgroundWhitelistRevokedUids.size();
2368 if (size > 0) {
2369 fout.println("Default restrict background whitelist uids revoked by users:");
2370 fout.increaseIndent();
2371 for (int i = 0; i < size; i++) {
2372 fout.print("UID=");
2373 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2374 fout.println();
2375 }
2376 fout.decreaseIndent();
2377 }
2378
2379 final SparseBooleanArray knownUids = new SparseBooleanArray();
2380 collectKeys(mUidState, knownUids);
2381 collectKeys(mUidRules, knownUids);
2382
2383 fout.println("Status for all known UIDs:");
2384 fout.increaseIndent();
2385 size = knownUids.size();
2386 for (int i = 0; i < size; i++) {
2387 final int uid = knownUids.keyAt(i);
2388 fout.print("UID=");
2389 fout.print(uid);
2390
2391 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2392 fout.print(" state=");
2393 fout.print(state);
2394 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2395 fout.print(" (fg)");
2396 } else {
2397 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2398 ? " (fg svc)" : " (bg)");
2399 }
2400
2401 final int uidRules = mUidRules.get(uid, RULE_NONE);
2402 fout.print(" rules=");
2403 fout.print(uidRulesToString(uidRules));
2404 fout.println();
2405 }
2406 fout.decreaseIndent();
2407
2408 fout.println("Status for just UIDs with rules:");
2409 fout.increaseIndent();
2410 size = mUidRules.size();
2411 for (int i = 0; i < size; i++) {
2412 final int uid = mUidRules.keyAt(i);
2413 fout.print("UID=");
2414 fout.print(uid);
2415 final int uidRules = mUidRules.get(uid, RULE_NONE);
2416 fout.print(" rules=");
2417 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002418 fout.println();
2419 }
2420 fout.decreaseIndent();
2421 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002422 }
2423 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002424
2425 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002426 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002427 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002428 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002429 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002430 }
2431
2432 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002433 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002434 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2435
Felipe Lemef0823852016-06-08 13:43:08 -07002436 synchronized (mUidRulesFirstLock) {
2437 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002438 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002439 }
2440
Felipe Lemef0823852016-06-08 13:43:08 -07002441 private boolean isUidForegroundUL(int uid) {
2442 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002443 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2444 }
2445
Felipe Lemef0823852016-06-08 13:43:08 -07002446 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002447 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002448 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002449 }
2450
Felipe Lemef0823852016-06-08 13:43:08 -07002451 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002452 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2453 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2454 }
2455
Felipe Lemef0823852016-06-08 13:43:08 -07002456 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002457 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002458 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002459 }
2460
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002461 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002462 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002463 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2464 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002465 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002466 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002467 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2468 try {
2469 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2470 if (oldUidState != uidState) {
2471 // state changed, push updated rules
2472 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002473 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2474 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2475 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2476 if (isUidIdle(uid)) {
2477 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002478 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002479 if (mDeviceIdleMode) {
2480 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002481 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002482 if (mRestrictPower) {
2483 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002484 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002485 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002486 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002487 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002488 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002489 } finally {
2490 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002491 }
2492 }
2493
Felipe Lemef0823852016-06-08 13:43:08 -07002494 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002495 final int index = mUidState.indexOfKey(uid);
2496 if (index >= 0) {
2497 final int oldUidState = mUidState.valueAt(index);
2498 mUidState.removeAt(index);
2499 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002500 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002501 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002502 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002503 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002504 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002505 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002506 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002507 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002508 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002509 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002510 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002511 }
2512 }
2513
Felipe Lemef28983d2016-03-25 12:18:23 -07002514 // adjust stats accounting based on foreground status
2515 private void updateNetworkStats(int uid, boolean uidForeground) {
2516 try {
2517 mNetworkStats.setUidForeground(uid, uidForeground);
2518 } catch (RemoteException e) {
2519 // ignored; service lives in system_server
2520 }
2521 }
2522
Sudheer Shankac9d94072017-02-22 22:13:55 +00002523 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2524 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002525 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002526 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002527 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002528 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002529 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002530 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002531 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002532 }
2533
Felipe Lemef0823852016-06-08 13:43:08 -07002534 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002535 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2536 try {
2537 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2538 mUidFirewallPowerSaveRules);
2539 } finally {
2540 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2541 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002542 }
2543
Felipe Lemef0823852016-06-08 13:43:08 -07002544 void updateRuleForRestrictPowerUL(int uid) {
2545 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002546 }
2547
Felipe Lemef0823852016-06-08 13:43:08 -07002548 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002549 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2550 try {
2551 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2552 mUidFirewallDozableRules);
2553 } finally {
2554 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2555 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002556 }
2557
Felipe Lemef0823852016-06-08 13:43:08 -07002558 void updateRuleForDeviceIdleUL(int uid) {
2559 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002560 }
2561
Felipe Lemef28983d2016-03-25 12:18:23 -07002562 // NOTE: since both fw_dozable and fw_powersave uses the same map
2563 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002564 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002565 SparseIntArray rules) {
2566 if (enabled) {
2567 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002568 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002569 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002570 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002571 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002572 for (int ui = users.size() - 1; ui >= 0; ui--) {
2573 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002574 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002575 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2576 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2577 int uid = UserHandle.getUid(user.id, appId);
2578 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2579 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002580 }
2581 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2582 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2583 int uid = UserHandle.getUid(user.id, appId);
2584 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2585 }
2586 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002587 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002588 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002589 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2590 }
2591 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002592 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2593 } else {
2594 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002595 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002596 }
2597
Felipe Lemef0823852016-06-08 13:43:08 -07002598 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002599 final int appId = UserHandle.getAppId(uid);
2600 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2601 }
2602
Felipe Lemef28983d2016-03-25 12:18:23 -07002603 // NOTE: since both fw_dozable and fw_powersave uses the same map
2604 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002605 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002606 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002607 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002608 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002609 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002610 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002611 }
2612 }
2613 }
2614
Felipe Lemef0823852016-06-08 13:43:08 -07002615 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002616 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2617 try {
2618 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2619 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002620
Felipe Leme873a83a2016-09-07 11:34:10 -07002621 // Fully update the app idle firewall chain.
2622 final List<UserInfo> users = mUserManager.getUsers();
2623 for (int ui = users.size() - 1; ui >= 0; ui--) {
2624 UserInfo user = users.get(ui);
2625 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2626 for (int uid : idleUids) {
2627 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2628 // quick check: if this uid doesn't have INTERNET permission, it
2629 // doesn't have network access anyway, so it is a waste to mess
2630 // with it here.
2631 if (hasInternetPermissions(uid)) {
2632 uidRules.put(uid, FIREWALL_RULE_DENY);
2633 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002634 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002635 }
2636 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002637
Felipe Lemebc853dd2016-09-08 13:26:55 -07002638 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002639 } finally {
2640 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2641 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002642 }
2643
Felipe Lemef0823852016-06-08 13:43:08 -07002644 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002645 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002646
2647 int appId = UserHandle.getAppId(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002648 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
Felipe Lemef0823852016-06-08 13:43:08 -07002649 && !isUidForegroundOnRestrictPowerUL(uid)) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002650 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2651 } else {
2652 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2653 }
2654 }
2655
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002656 /**
2657 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2658 * changed.
2659 */
Felipe Lemef0823852016-06-08 13:43:08 -07002660 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002661 boolean paroled = mUsageStats.isAppIdleParoleOn();
2662 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002663 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002664
2665 int ruleCount = mUidFirewallStandbyRules.size();
2666 for (int i = 0; i < ruleCount; i++) {
2667 int uid = mUidFirewallStandbyRules.keyAt(i);
2668 int oldRules = mUidRules.get(uid);
2669 if (enableChain) {
2670 // Chain wasn't enabled before and the other power-related
2671 // chains are whitelists, so we can clear the
2672 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2673 // the effective rules result in blocking network access.
2674 oldRules &= MASK_METERED_NETWORKS;
2675 } else {
2676 // Skip if it had no restrictions to begin with
2677 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2678 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002679 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002680 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002681 }
2682
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002683 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002684 * Update rules that might be changed by {@link #mRestrictBackground},
2685 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002686 */
Felipe Lemef0823852016-06-08 13:43:08 -07002687 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002688 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForGlobalChangeAL");
2689 try {
Felipe Leme09700462016-09-08 09:33:48 -07002690 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002691 updateRulesForRestrictPowerUL();
2692 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002693
Felipe Leme873a83a2016-09-07 11:34:10 -07002694 // If the set of restricted networks may have changed, re-evaluate those.
2695 if (restrictedNetworksChanged) {
2696 normalizePoliciesNL();
2697 updateNetworkRulesNL();
2698 }
2699 } finally {
2700 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002701 }
2702 }
2703
Felipe Leme09700462016-09-08 09:33:48 -07002704 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002705 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002706 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2707 try {
2708 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002709 updateRulesForPowerSaveUL();
2710 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2711 } finally {
2712 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2713 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002714 }
2715
Felipe Lemef0823852016-06-08 13:43:08 -07002716 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002717 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2718 try {
2719 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2720 } finally {
2721 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2722 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002723 }
2724
2725 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2726 private static final int TYPE_RESTRICT_POWER = 2;
2727 @Retention(RetentionPolicy.SOURCE)
2728 @IntDef(flag = false, value = {
2729 TYPE_RESTRICT_BACKGROUND,
2730 TYPE_RESTRICT_POWER,
2731 })
2732 public @interface RestrictType {
2733 }
2734
2735 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002736 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002737 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2738 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2739 }
2740 try {
2741 final PackageManager pm = mContext.getPackageManager();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002742
Felipe Leme873a83a2016-09-07 11:34:10 -07002743 // update rules for all installed applications
2744 final List<UserInfo> users = mUserManager.getUsers();
2745 final List<ApplicationInfo> apps = pm.getInstalledApplications(
Amith Yamasani0d1fd8d2016-10-12 14:21:51 -07002746 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
Felipe Leme873a83a2016-09-07 11:34:10 -07002747 | PackageManager.MATCH_DIRECT_BOOT_AWARE
2748 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002749
Felipe Leme873a83a2016-09-07 11:34:10 -07002750 final int usersSize = users.size();
2751 final int appsSize = apps.size();
2752 for (int i = 0; i < usersSize; i++) {
2753 final UserInfo user = users.get(i);
2754 for (int j = 0; j < appsSize; j++) {
2755 final ApplicationInfo app = apps.get(j);
2756 final int uid = UserHandle.getUid(user.id, app.uid);
2757 switch (type) {
2758 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002759 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002760 break;
2761 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00002762 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002763 break;
2764 default:
2765 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
2766 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002767 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002768 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002769 } finally {
2770 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2771 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2772 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002773 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002774 }
2775
Felipe Lemef0823852016-06-08 13:43:08 -07002776 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002777 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08002778 for (int i = 0; i < users.size(); i++) {
2779 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08002780 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08002781 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002782 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07002783 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07002784 updateRuleForAppIdleUL(uid);
2785 updateRuleForDeviceIdleUL(uid);
2786 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002787 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002788 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002789 }
2790 }
2791 }
2792
Felipe Leme70c57c22016-03-29 10:45:13 -07002793 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
2794 // methods below could be merged into a isUidValidForRules() method.
2795 private boolean isUidValidForBlacklistRules(int uid) {
2796 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002797 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07002798 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07002799 return true;
2800 }
2801
2802 return false;
2803 }
2804
Felipe Leme70c57c22016-03-29 10:45:13 -07002805 private boolean isUidValidForWhitelistRules(int uid) {
2806 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
2807 }
2808
Amith Yamasani15e472352015-04-24 19:06:07 -07002809 private boolean isUidIdle(int uid) {
2810 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
2811 final int userId = UserHandle.getUserId(uid);
2812
songjinshi0655edd2016-05-18 19:55:32 +08002813 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07002814 for (String packageName : packages) {
2815 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
2816 return false;
2817 }
Amith Yamasani15e472352015-04-24 19:06:07 -07002818 }
2819 }
2820 return true;
2821 }
2822
2823 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08002824 * Checks if an uid has INTERNET permissions.
2825 * <p>
2826 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07002827 */
Felipe Leme47585ba2016-02-09 16:56:32 -08002828 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002829 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08002830 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002831 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08002832 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002833 }
2834 } catch (RemoteException e) {
2835 }
Felipe Leme47585ba2016-02-09 16:56:32 -08002836 return true;
2837 }
2838
2839 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07002840 * Clears all state - internal and external - associated with an UID.
2841 */
2842 private void onUidDeletedUL(int uid) {
2843 // First cleanup in-memory state synchronously...
2844 mUidRules.delete(uid);
2845 mUidPolicy.delete(uid);
2846 mUidFirewallStandbyRules.delete(uid);
2847 mUidFirewallDozableRules.delete(uid);
2848 mUidFirewallPowerSaveRules.delete(uid);
2849 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
2850 mPowerSaveWhitelistAppIds.delete(uid);
2851 mPowerSaveTempWhitelistAppIds.delete(uid);
2852
2853 // ...then update iptables asynchronously.
2854 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
2855 }
2856
2857 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07002858 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07002859 *
Felipe Leme781ba142016-05-09 16:24:48 -07002860 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07002861 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002862 * <li>Doze mode
2863 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07002864 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07002865 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07002866 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07002867 *
2868 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08002869 */
Felipe Leme03e95e22016-09-09 09:25:31 -07002870 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002871 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07002872 updateRuleForDeviceIdleUL(uid);
2873 updateRuleForAppIdleUL(uid);
2874 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002875
2876 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002877 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002878
2879 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002880 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002881 }
2882
Felipe Leme70c57c22016-03-29 10:45:13 -07002883 /**
2884 * Applies network rules to bandwidth controllers based on process state and user-defined
2885 * restrictions (blacklist / whitelist).
2886 *
2887 * <p>
2888 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
2889 * networks:
2890 * <ul>
2891 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
2892 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
2893 * also blacklisted.
2894 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
2895 * no UIDs other those whitelisted will have access.
2896 * <ul>
2897 *
2898 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
2899 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
2900 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
2901 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07002902 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07002903 * {@link INetworkManagementService}, but this method should also be called in events (like
2904 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
2905 * following rules should also be applied:
2906 *
2907 * <ul>
2908 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
2909 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
2910 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
2911 * {@code bw_penalty_box}.
2912 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
2913 * </ul>
2914 *
2915 * <p>For optimization, the rules are only applied on user apps that have internet access
2916 * permission, since there is no need to change the {@code iptables} rule if the app does not
2917 * have permission to use the internet.
2918 *
2919 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07002920 *
Felipe Leme70c57c22016-03-29 10:45:13 -07002921 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002922 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07002923 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002924 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002925 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07002926 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002927
Dianne Hackborn497175b2014-07-01 12:56:08 -07002928 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002929 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07002930 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002931
Felipe Leme781ba142016-05-09 16:24:48 -07002932 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07002933 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07002934 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
2935 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07002936
Felipe Leme70c57c22016-03-29 10:45:13 -07002937 // First step: define the new rule based on user restrictions and foreground state.
2938 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07002939 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
2940 newRule = RULE_TEMPORARY_ALLOW_METERED;
2941 } else if (isWhitelisted) {
2942 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002943 }
2944 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07002945 if (isBlacklisted) {
2946 newRule = RULE_REJECT_METERED;
2947 } else if (mRestrictBackground && isWhitelisted) {
2948 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07002949 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002950 }
Felipe Leme781ba142016-05-09 16:24:48 -07002951 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07002952
Felipe Lemef28983d2016-03-25 12:18:23 -07002953 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07002954 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07002955 + ": isForeground=" +isForeground
2956 + ", isBlacklisted=" + isBlacklisted
2957 + ", isWhitelisted=" + isWhitelisted
2958 + ", oldRule=" + uidRulesToString(oldRule)
2959 + ", newRule=" + uidRulesToString(newRule)
2960 + ", newUidRules=" + uidRulesToString(newUidRules)
2961 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07002962 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002963
Felipe Leme46c4fc32016-05-04 09:21:43 -07002964 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07002965 mUidRules.delete(uid);
2966 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002967 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07002968 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002969
Felipe Leme70c57c22016-03-29 10:45:13 -07002970 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07002971 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07002972 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002973 // Temporarily whitelist foreground app, removing from blacklist if necessary
2974 // (since bw_penalty_box prevails over bw_happy_box).
2975
2976 setMeteredNetworkWhitelist(uid, true);
2977 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
2978 // but ideally it should be just:
2979 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002980 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002981 setMeteredNetworkBlacklist(uid, false);
2982 }
Felipe Leme781ba142016-05-09 16:24:48 -07002983 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002984 // Remove temporary whitelist from app that is not on foreground anymore.
2985
2986 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
2987 // but ideally they should be just:
2988 // setMeteredNetworkWhitelist(uid, isWhitelisted);
2989 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07002990 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002991 setMeteredNetworkWhitelist(uid, false);
2992 }
Felipe Leme781ba142016-05-09 16:24:48 -07002993 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002994 setMeteredNetworkBlacklist(uid, true);
2995 }
Felipe Leme781ba142016-05-09 16:24:48 -07002996 } else if ((newRule & RULE_REJECT_METERED) != 0
2997 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002998 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07002999 setMeteredNetworkBlacklist(uid, isBlacklisted);
3000 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003001 // Since blacklist prevails over whitelist, we need to handle the special case
3002 // where app is whitelisted and blacklisted at the same time (although such
3003 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003004 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003005 }
Felipe Leme781ba142016-05-09 16:24:48 -07003006 } else if ((newRule & RULE_ALLOW_METERED) != 0
3007 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003008 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003009 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003010 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003011 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003012 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3013 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003014 + ", whitelisted=" + isWhitelisted
3015 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003016 + ", newRule=" + uidRulesToString(newUidRules)
3017 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003018 }
Felipe Leme781ba142016-05-09 16:24:48 -07003019
Sudheer Shankac9d94072017-02-22 22:13:55 +00003020 // Dispatch changed rule to existing listeners.
3021 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003022 }
3023 }
3024
3025 /**
3026 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3027 * listeners in case of change.
3028 * <p>
3029 * There are 3 power-related rules that affects whether an app has background access on
3030 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3031 * restriction, it's added to the equivalent firewall chain:
3032 * <ul>
3033 * <li>App is idle: {@code fw_standby} firewall chain.
3034 * <li>Device is idle: {@code fw_dozable} firewall chain.
3035 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3036 * </ul>
3037 * <p>
3038 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3039 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3040 * <p>
3041 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3042 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003043 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003044 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3045
Sudheer Shankac9d94072017-02-22 22:13:55 +00003046 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003047
Sudheer Shankac9d94072017-02-22 22:13:55 +00003048 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003049 mUidRules.delete(uid);
3050 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003051 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003052 }
3053 }
3054
3055 /**
3056 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3057 *
3058 * @param uid the uid of the app to update rules for
3059 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3060 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3061 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003062 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003063 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003064 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003065 if (!isUidValidForBlacklistRules(uid)) {
3066 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003067 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003068 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003069
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003070 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003071 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003072 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003073
Felipe Lemef0823852016-06-08 13:43:08 -07003074 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003075 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3076 int newRule = RULE_NONE;
3077
3078 // First step: define the new rule based on user restrictions and foreground state.
3079
3080 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3081 // by considering the foreground and non-foreground states.
3082 if (isForeground) {
3083 if (restrictMode) {
3084 newRule = RULE_ALLOW_ALL;
3085 }
3086 } else if (restrictMode) {
3087 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3088 }
3089
3090 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3091
3092 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003093 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003094 + ", isIdle: " + isIdle
3095 + ", mRestrictPower: " + mRestrictPower
3096 + ", mDeviceIdleMode: " + mDeviceIdleMode
3097 + ", isForeground=" + isForeground
3098 + ", isWhitelisted=" + isWhitelisted
3099 + ", oldRule=" + uidRulesToString(oldRule)
3100 + ", newRule=" + uidRulesToString(newRule)
3101 + ", newUidRules=" + uidRulesToString(newUidRules)
3102 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3103 }
3104
Felipe Leme781ba142016-05-09 16:24:48 -07003105 // Second step: notify listeners if state changed.
3106 if (newRule != oldRule) {
3107 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003108 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003109 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003110 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3111 } else {
3112 // All scenarios should have been covered above
3113 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3114 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003115 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003116 + ", newRule=" + uidRulesToString(newUidRules)
3117 + ", oldRule=" + uidRulesToString(oldUidRules));
3118 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003119 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003120 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003121
Sudheer Shankac9d94072017-02-22 22:13:55 +00003122 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003123 }
3124
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003125 private class AppIdleStateChangeListener
3126 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3127
3128 @Override
3129 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3130 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003131 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3132 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003133 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003134 synchronized (mUidRulesFirstLock) {
3135 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003136 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003137 }
3138 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003139 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003140 }
3141
3142 @Override
3143 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003144 synchronized (mUidRulesFirstLock) {
3145 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003146 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003147 }
3148 }
3149
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003150 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3151 if (listener != null) {
3152 try {
3153 listener.onUidRulesChanged(uid, uidRules);
3154 } catch (RemoteException ignored) {
3155 }
3156 }
3157 }
3158
3159 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3160 String[] meteredIfaces) {
3161 if (listener != null) {
3162 try {
3163 listener.onMeteredIfacesChanged(meteredIfaces);
3164 } catch (RemoteException ignored) {
3165 }
3166 }
3167 }
3168
3169 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3170 boolean restrictBackground) {
3171 if (listener != null) {
3172 try {
3173 listener.onRestrictBackgroundChanged(restrictBackground);
3174 } catch (RemoteException ignored) {
3175 }
3176 }
3177 }
3178
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003179 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3180 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003181 if (listener != null) {
3182 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003183 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003184 } catch (RemoteException ignored) {
3185 }
3186 }
3187 }
3188
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003189 private Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003190 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003191 public boolean handleMessage(Message msg) {
3192 switch (msg.what) {
3193 case MSG_RULES_CHANGED: {
3194 final int uid = msg.arg1;
3195 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003196 dispatchUidRulesChanged(mConnectivityListener, uid, uidRules);
3197 final int length = mListeners.beginBroadcast();
3198 for (int i = 0; i < length; i++) {
3199 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3200 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003201 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003202 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003203 return true;
3204 }
3205 case MSG_METERED_IFACES_CHANGED: {
3206 final String[] meteredIfaces = (String[]) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003207 dispatchMeteredIfacesChanged(mConnectivityListener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003208 final int length = mListeners.beginBroadcast();
3209 for (int i = 0; i < length; i++) {
3210 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003211 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003212 }
3213 mListeners.finishBroadcast();
3214 return true;
3215 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003216 case MSG_LIMIT_REACHED: {
3217 final String iface = (String) msg.obj;
3218
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003219 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003220 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003221 if (mMeteredIfaces.contains(iface)) {
3222 try {
3223 // force stats update to make sure we have
3224 // numbers that caused alert to trigger.
3225 mNetworkStats.forceUpdate();
3226 } catch (RemoteException e) {
3227 // ignored; service lives in system_server
3228 }
3229
Felipe Lemef0823852016-06-08 13:43:08 -07003230 updateNetworkEnabledNL();
3231 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003232 }
3233 }
3234 return true;
3235 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003236 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3237 final boolean restrictBackground = msg.arg1 != 0;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003238 dispatchRestrictBackgroundChanged(mConnectivityListener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003239 final int length = mListeners.beginBroadcast();
3240 for (int i = 0; i < length; i++) {
3241 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003242 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003243 }
3244 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003245 final Intent intent =
3246 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3247 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3248 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3249 return true;
3250 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003251 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003252 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003253 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003254 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003255 // First notify internal listeners...
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003256 dispatchUidPoliciesChanged(mConnectivityListener, uid, policy);
Felipe Leme57e3d312016-08-23 14:42:52 -07003257 final int length = mListeners.beginBroadcast();
3258 for (int i = 0; i < length; i++) {
3259 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003260 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003261 }
3262 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003263 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3264 if (notifyApp.booleanValue()) {
3265 broadcastRestrictBackgroundChanged(uid, notifyApp);
3266 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003267 return true;
3268 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003269 case MSG_ADVISE_PERSIST_THRESHOLD: {
3270 final long lowestRule = (Long) msg.obj;
3271 try {
3272 // make sure stats are recorded frequently enough; we aim
3273 // for 2MB threshold for 2GB/month rules.
3274 final long persistThreshold = lowestRule / 1000;
3275 mNetworkStats.advisePersistThreshold(persistThreshold);
3276 } catch (RemoteException e) {
3277 // ignored; service lives in system_server
3278 }
3279 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003280 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003281 case MSG_UPDATE_INTERFACE_QUOTA: {
3282 removeInterfaceQuota((String) msg.obj);
3283 // int params need to be stitched back into a long
3284 setInterfaceQuota((String) msg.obj,
3285 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3286 return true;
3287 }
3288 case MSG_REMOVE_INTERFACE_QUOTA: {
3289 removeInterfaceQuota((String) msg.obj);
3290 return true;
3291 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003292 case MSG_SET_FIREWALL_RULES: {
3293 final int chain = msg.arg1;
3294 final int toggle = msg.arg2;
3295 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3296 if (uidRules != null) {
3297 setUidFirewallRules(chain, uidRules);
3298 }
3299 if (toggle != CHAIN_TOGGLE_NONE) {
3300 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3301 }
3302 return true;
3303 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003304 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3305 resetUidFirewallRules(msg.arg1);
3306 return true;
3307 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003308 default: {
3309 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003310 }
3311 }
3312 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003313
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003314 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003315
Felipe Leme57e3d312016-08-23 14:42:52 -07003316 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3317 final PackageManager pm = mContext.getPackageManager();
3318 final String[] packages = pm.getPackagesForUid(uid);
3319 if (packages != null) {
3320 final int userId = UserHandle.getUserId(uid);
3321 for (String packageName : packages) {
3322 final Intent intent =
3323 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3324 intent.setPackage(packageName);
3325 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3326 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3327 }
3328 }
3329 }
3330
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003331 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003332 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003333 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003334 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003335 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003336 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003337 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003338 }
3339 }
3340
3341 private void removeInterfaceQuota(String iface) {
3342 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003343 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003344 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003345 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003346 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003347 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003348 }
3349 }
3350
Felipe Leme70c57c22016-03-29 10:45:13 -07003351 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3352 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003353 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003354 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003355 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003356 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3357 } catch (RemoteException e) {
3358 // ignored; service lives in system_server
3359 }
3360 }
3361
3362 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3363 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3364 try {
3365 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3366 } catch (IllegalStateException e) {
3367 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003368 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003369 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003370 }
3371 }
3372
Felipe Lemebc853dd2016-09-08 13:26:55 -07003373 private static final int CHAIN_TOGGLE_NONE = 0;
3374 private static final int CHAIN_TOGGLE_ENABLE = 1;
3375 private static final int CHAIN_TOGGLE_DISABLE = 2;
3376 @Retention(RetentionPolicy.SOURCE)
3377 @IntDef(flag = false, value = {
3378 CHAIN_TOGGLE_NONE,
3379 CHAIN_TOGGLE_ENABLE,
3380 CHAIN_TOGGLE_DISABLE
3381 })
3382 public @interface ChainToggleType {
3383 }
3384
3385 /**
3386 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3387 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3388 *
3389 * @param chain firewall chain.
3390 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3391 * @param toggle whether the chain should be enabled, disabled, or not changed.
3392 */
3393 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3394 @ChainToggleType int toggle) {
3395 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3396 }
3397
Amith Yamasani15e472352015-04-24 19:06:07 -07003398 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003399 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3400 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3401 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003402 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003403 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003404 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003405 int size = uidRules.size();
3406 int[] uids = new int[size];
3407 int[] rules = new int[size];
3408 for(int index = size - 1; index >= 0; --index) {
3409 uids[index] = uidRules.keyAt(index);
3410 rules[index] = uidRules.valueAt(index);
3411 }
3412 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003413 } catch (IllegalStateException e) {
3414 Log.wtf(TAG, "problem setting firewall uid rules", e);
3415 } catch (RemoteException e) {
3416 // ignored; service lives in system_server
3417 }
3418 }
3419
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003420 /**
3421 * Add or remove a uid to the firewall blacklist for all network ifaces.
3422 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003423 private void setUidFirewallRule(int chain, int uid, int rule) {
Jeff Sharkeydc988062015-09-14 10:09:47 -07003424 if (chain == FIREWALL_CHAIN_DOZABLE) {
3425 mUidFirewallDozableRules.put(uid, rule);
3426 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3427 mUidFirewallStandbyRules.put(uid, rule);
Felipe Leme011b98f2016-02-10 17:28:31 -08003428 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3429 mUidFirewallPowerSaveRules.put(uid, rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003430 }
3431
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003432 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003433 mNetworkManager.setFirewallUidRule(chain, uid, rule);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003434 } catch (IllegalStateException e) {
3435 Log.wtf(TAG, "problem setting firewall uid rules", e);
3436 } catch (RemoteException e) {
3437 // ignored; service lives in system_server
3438 }
3439 }
3440
3441 /**
3442 * Add or remove a uid to the firewall blacklist for all network ifaces.
3443 */
Felipe Lemef0823852016-06-08 13:43:08 -07003444 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003445 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3446 mFirewallChainStates.get(chain) == enable) {
3447 // All is the same, nothing to do.
3448 return;
3449 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003450 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003451 try {
3452 mNetworkManager.setFirewallChainEnabled(chain, enable);
3453 } catch (IllegalStateException e) {
3454 Log.wtf(TAG, "problem enable firewall chain", e);
3455 } catch (RemoteException e) {
3456 // ignored; service lives in system_server
3457 }
3458 }
3459
Felipe Leme03e95e22016-09-09 09:25:31 -07003460 /**
3461 * Resets all firewall rules associated with an UID.
3462 */
3463 private void resetUidFirewallRules(int uid) {
3464 try {
3465 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3466 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3467 mNetworkManager
3468 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3469 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3470 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3471 } catch (IllegalStateException e) {
3472 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3473 } catch (RemoteException e) {
3474 // ignored; service lives in system_server
3475 }
3476 }
3477
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003478 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3479 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003480 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003481 } catch (RuntimeException e) {
3482 Slog.w(TAG, "problem reading network stats: " + e);
3483 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003484 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003485 // ignored; service lives in system_server
3486 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003487 }
3488 }
3489
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003490 private boolean isBandwidthControlEnabled() {
3491 final long token = Binder.clearCallingIdentity();
3492 try {
3493 return mNetworkManager.isBandwidthControlEnabled();
3494 } catch (RemoteException e) {
3495 // ignored; service lives in system_server
3496 return false;
3497 } finally {
3498 Binder.restoreCallingIdentity(token);
3499 }
3500 }
3501
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003502 /**
3503 * Try refreshing {@link #mTime} when stale.
3504 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003505 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003506 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003507 mTime.forceRefresh();
3508 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003509 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003510
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003511 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003512 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3513 }
3514
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003515 private static Intent buildAllowBackgroundDataIntent() {
3516 return new Intent(ACTION_ALLOW_BACKGROUND);
3517 }
3518
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003519 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3520 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3521 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3522 return intent;
3523 }
3524
Wei Liu546cb772016-07-21 16:19:01 -07003525 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003526 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003527 intent.setComponent(ComponentName.unflattenFromString(
3528 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003529 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3530 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3531 return intent;
3532 }
3533
Wei Liu546cb772016-07-21 16:19:01 -07003534 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003535 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003536 intent.setComponent(ComponentName.unflattenFromString(
3537 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003538 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3539 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3540 return intent;
3541 }
3542
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003543 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003544 public void addIdleHandler(IdleHandler handler) {
3545 mHandler.getLooper().getQueue().addIdleHandler(handler);
3546 }
3547
Jeff Sharkey1b861272011-05-22 00:34:52 -07003548 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3549 final int size = source.size();
3550 for (int i = 0; i < size; i++) {
3551 target.put(source.keyAt(i), true);
3552 }
3553 }
3554
Stuart Scottf1fb3972015-04-02 18:00:02 -07003555 @Override
3556 public void factoryReset(String subscriber) {
3557 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3558
Stuart Scotte3e314d2015-04-20 14:07:45 -07003559 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3560 return;
3561 }
3562
Stuart Scottf1fb3972015-04-02 18:00:02 -07003563 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003564 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003565 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3566 for (NetworkPolicy policy : policies) {
3567 if (policy.template.equals(template)) {
3568 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3569 policy.inferred = false;
3570 policy.clearSnooze();
3571 }
3572 }
3573 setNetworkPolicies(policies);
3574
3575 // Turn restrict background data off
3576 setRestrictBackground(false);
3577
Stuart Scotte3e314d2015-04-20 14:07:45 -07003578 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3579 // Remove app's "restrict background data" flag
3580 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3581 setUidPolicy(uid, POLICY_NONE);
3582 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003583 }
3584 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003585
Felipe Lemed17fda42016-04-29 11:12:45 -07003586 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3587
3588 @Override
3589 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003590 synchronized (mUidRulesFirstLock) {
3591 boolean changed = removeUserStateUL(userId, false);
3592 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003593 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003594 synchronized (mNetworkPoliciesSecondLock) {
3595 writePolicyAL();
3596 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003597 }
3598 }
3599 }
3600 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003601}