blob: 6e8ecd9c2b4adbd47a6faf4cb607dd29f791c42e [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;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070078import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
79import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
80import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070081import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080082
Jeff Sharkey854b2b12012-04-13 16:03:40 -070083import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070085import static com.android.internal.util.XmlUtils.readBooleanAttribute;
86import static com.android.internal.util.XmlUtils.readIntAttribute;
87import static com.android.internal.util.XmlUtils.readLongAttribute;
88import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
89import static com.android.internal.util.XmlUtils.writeIntAttribute;
90import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070091import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070092import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060093
Jeff Sharkey21c9c452011-06-07 12:26:43 -070094import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080095import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070096import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070097
Dianne Hackborn88e98df2015-03-23 13:29:14 -070098import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070099import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700100import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -0700101import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -0800102import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700103import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -0700104import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700106import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700107import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700108import android.app.Notification;
109import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700111import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700112import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700113import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700114import android.content.Intent;
115import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700116import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700117import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700118import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700119import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700120import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700121import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700122import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700123import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700124import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700125import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700126import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700127import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700128import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700129import android.net.NetworkIdentity;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700130import android.net.NetworkInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700132import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700133import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700134import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700135import android.net.wifi.WifiConfiguration;
136import android.net.wifi.WifiInfo;
137import android.net.wifi.WifiManager;
jackqdyulei455e90a2017-02-09 15:29:16 -0800138import android.os.PowerSaveState;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700139import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700140import android.os.Environment;
141import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700142import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700143import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700144import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700145import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700146import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700147import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700148import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700149import android.os.PowerManagerInternal;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800150import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700151import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700152import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600153import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700154import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700155import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700156import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700157import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700158import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700159import android.provider.Settings;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700160import android.telephony.CarrierConfigManager;
Jeff Sharkey32566012014-12-02 18:30:14 -0800161import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700162import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400163import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700164import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700165import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700166import android.util.ArrayMap;
167import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700168import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700169import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700171import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700172import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700173import android.util.SparseBooleanArray;
174import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700175import android.util.TrustedTime;
176import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700177
Jeff Sharkey497e4432011-06-14 17:27:29 -0700178import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700179import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800180import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400181import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500182import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700183import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800184import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600185import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700187import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700188import com.android.server.DeviceIdleController;
189import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700190import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700191import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800192import com.android.server.SystemConfig;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600193
jackqdyulei455e90a2017-02-09 15:29:16 -0800194import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600195import libcore.io.IoUtils;
196
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700197import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198
199import org.xmlpull.v1.XmlPullParser;
200import org.xmlpull.v1.XmlPullParserException;
201import org.xmlpull.v1.XmlSerializer;
202
203import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700204import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205import java.io.FileInputStream;
206import java.io.FileNotFoundException;
207import java.io.FileOutputStream;
208import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700209import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700210import java.lang.annotation.Retention;
211import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100212import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700213import java.util.ArrayList;
214import java.util.Arrays;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700215import java.util.List;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700216import java.util.Calendar;
Chris Wren193ae6b2017-03-31 15:17:11 -0400217import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800218import java.util.concurrent.CountDownLatch;
219import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700220
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700221/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700222 * Service that maintains low-level network policy rules, using
223 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224 * <p>
225 * Derives active rules by combining a given policy with other system status,
226 * and delivers to listeners, such as {@link ConnectivityManager}, for
227 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700228 *
229 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000230 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700231 * <ul>
232 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
233 * rules).
234 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
235 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000236 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
237 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700238 * </ul>
239 *
240 * <p>
241 * As such, methods that require synchronization have the following prefixes:
242 * <ul>
243 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
244 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000245 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
246 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700247 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700248 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700249public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800250 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900251 private static final boolean LOGD = false;
252 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700253
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700254 private static final int VERSION_INIT = 1;
255 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700256 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800257 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800258 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800259 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700260 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700261 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700262 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700263 private static final int VERSION_SWITCH_UID = 10;
264 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265
Sudheer Shankae7361852017-03-07 11:51:46 -0800266 /**
267 * Max items written to {@link #ProcStateSeqHistory}.
268 */
269 @VisibleForTesting
270 public static final int MAX_PROC_STATE_SEQ_HISTORY =
271 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
272
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800273 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400274 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800275 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400276 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400278 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700279
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 private static final String TAG_POLICY_LIST = "policy-list";
281 private static final String TAG_NETWORK_POLICY = "network-policy";
282 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800284 private static final String TAG_WHITELIST = "whitelist";
285 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800286 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700289 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
291 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800294 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700295 private static final String ATTR_WARNING_BYTES = "warningBytes";
296 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800298 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
299 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800300 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700301 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700303 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 private static final String ATTR_POLICY = "policy";
305
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800306 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800307 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800308 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800309 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700310
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
312
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700313 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700314 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800315 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800316 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700317 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700318 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
319 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700320 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700321 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700322 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700323
Makoto Onuki8e777332017-03-28 11:25:47 -0700324 private static final int UID_MSG_STATE_CHANGED = 100;
325 private static final int UID_MSG_GONE = 101;
326
Jeff Sharkey75279902011-05-24 18:39:45 -0700327 private final Context mContext;
328 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700329 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700331 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700333 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700334 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335
336 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700337 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700338 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700339 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800340 @GuardedBy("mUidRulesFirstLock")
341 private PowerSaveState mRestrictBackgroundPowerState;
342
343 // Store the status of restrict background before turning on battery saver.
344 // Used to restore mRestrictBackground when battery saver is turned off.
345 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700346
Felipe Lemef0823852016-06-08 13:43:08 -0700347 // See main javadoc for instructions on how to use these locks.
348 final Object mUidRulesFirstLock = new Object();
349 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700350
Felipe Lemef0823852016-06-08 13:43:08 -0700351 @GuardedBy("allLocks") volatile boolean mSystemReady;
352
Felipe Lemef0823852016-06-08 13:43:08 -0700353 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
354 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
355 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800356 // Store whether user flipped restrict background in battery saver mode
357 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700358
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700359 private final boolean mSuppressDefaultPolicy;
360
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700361 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800362 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700363 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800364 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700365
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700366 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700368 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700369 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700370
Felipe Lemef0823852016-06-08 13:43:08 -0700371 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700372 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700373 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700374 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700375 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800376 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700377
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700378 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700380 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
381
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 /**
383 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700384 * in power save mode, except device idle (doze) still applies.
385 * TODO: An int array might be sufficient
386 */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700388 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
389
390 /**
391 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800392 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700393 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800394 */
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700396 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700397
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700399 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
400
Felipe Lemeb85a6372016-01-14 16:16:16 -0800401 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800402 * UIDs that have been initially white-listed by system to avoid restricted background.
403 */
Felipe Lemef0823852016-06-08 13:43:08 -0700404 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800405 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
406 new SparseBooleanArray();
407
408 /**
409 * UIDs that have been initially white-listed by system to avoid restricted background,
410 * but later revoked by user.
411 */
Felipe Lemef0823852016-06-08 13:43:08 -0700412 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800413 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
414 new SparseBooleanArray();
415
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700416 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800418 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800421 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700422
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700423 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400425 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700426
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700427 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800429 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700430
Jeff Sharkey32566012014-12-02 18:30:14 -0800431 private final RemoteCallbackList<INetworkPolicyListener>
432 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700433
Dianne Hackborn497175b2014-07-01 12:56:08 -0700434 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700435 @VisibleForTesting
436 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700437
438 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700441 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700442
Svet Ganov16a16892015-04-16 10:32:04 -0700443 private final AppOpsManager mAppOps;
444
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800445 private final IPackageManager mIPm;
446
Sudheer Shankae7361852017-03-07 11:51:46 -0800447 private ActivityManagerInternal mActivityManagerInternal;
448
449 /**
450 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
451 * the uid and procStateSeq will be written to this and will be printed as part of dump.
452 */
453 @VisibleForTesting
454 public ProcStateSeqHistory mObservedHistory
455 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800456
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700457 // TODO: keep whitelist of system-critical services that should never have
458 // rules enforced, such as system, phone, and radio UIDs.
459
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700460 // TODO: migrate notifications to SystemUI
461
Jeff Sharkey75279902011-05-24 18:39:45 -0700462 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700463 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
464 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700465 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
466 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700467 }
468
469 private static File getSystemDir() {
470 return new File(Environment.getDataDirectory(), "system");
471 }
472
473 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700474 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700475 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700476 mContext = checkNotNull(context, "missing context");
477 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700478 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700479 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700480 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700481 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700482 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700483 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700484 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700485 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700486
Amith Yamasani450a16b2013-09-18 16:28:50 -0700487 HandlerThread thread = new HandlerThread(TAG);
488 thread.start();
489 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700490
Makoto Onuki8e777332017-03-28 11:25:47 -0700491 // We create another thread for the UID events, which are more time-critical.
492 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
493 /*allowIo=*/ false);
494 mUidEventThread.start();
495 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
496
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700497 mSuppressDefaultPolicy = suppressDefaultPolicy;
498
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700499 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700500
501 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800502
Felipe Lemed17fda42016-04-29 11:12:45 -0700503 // Expose private service for system components to use.
504 LocalServices.addService(NetworkPolicyManagerInternal.class,
505 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 }
507
508 public void bindConnectivityManager(IConnectivityManager connManager) {
509 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700510 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700511
Jeff Sharkey497e4432011-06-14 17:27:29 -0700512 public void bindNotificationManager(INotificationManager notifManager) {
513 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
514 }
515
Felipe Lemef0823852016-06-08 13:43:08 -0700516 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700517 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700518 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
519 mPowerSaveWhitelistExceptIdleAppIds.clear();
520 if (whitelist != null) {
521 for (int uid : whitelist) {
522 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
523 }
524 }
525 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700526 mPowerSaveWhitelistAppIds.clear();
527 if (whitelist != null) {
528 for (int uid : whitelist) {
529 mPowerSaveWhitelistAppIds.put(uid, true);
530 }
531 }
532 } catch (RemoteException e) {
533 }
534 }
535
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 /**
537 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
538 * revoke the whitelist.
539 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700540 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800541 */
Felipe Lemef0823852016-06-08 13:43:08 -0700542 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800543 final List<UserInfo> users = mUserManager.getUsers();
544 final int numberUsers = users.size();
545
Felipe Lemea110eec2016-04-29 09:58:06 -0700546 boolean changed = false;
547 for (int i = 0; i < numberUsers; i++) {
548 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700549 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700550 }
551 return changed;
552 }
553
Felipe Lemef0823852016-06-08 13:43:08 -0700554 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700555 final SystemConfig sysConfig = SystemConfig.getInstance();
556 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800557 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
558 boolean changed = false;
559 for (int i = 0; i < allowDataUsage.size(); i++) {
560 final String pkg = allowDataUsage.valueAt(i);
561 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700562 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
563 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800564 final ApplicationInfo app;
565 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700566 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800567 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700568 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
569 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800570 continue;
571 }
572 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700573 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
574 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800575 continue;
576 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700577 final int uid = UserHandle.getUid(userId, app.uid);
578 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
579 if (LOGD)
580 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
581 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800582 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700583 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700584 if (LOGD)
585 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
586 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700587 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700588 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800589 }
590 }
591 return changed;
592 }
593
Felipe Lemef0823852016-06-08 13:43:08 -0700594 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700595 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700596 // Clear the states of the current whitelist
597 final int N = mPowerSaveTempWhitelistAppIds.size();
598 for (int i = 0; i < N; i++) {
599 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
600 }
601 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700602 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700603 if (whitelist != null) {
604 for (int uid : whitelist) {
605 mPowerSaveTempWhitelistAppIds.put(uid, true);
606 }
607 }
608 } catch (RemoteException e) {
609 }
610 }
611
Amith Yamasani06f08062015-06-12 13:23:33 -0700612 /**
613 * Remove unnecessary entries in the temp whitelist
614 */
Felipe Lemef0823852016-06-08 13:43:08 -0700615 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700616 final int N = mPowerSaveTempWhitelistAppIds.size();
617 for (int i = N - 1; i >= 0; i--) {
618 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
619 mPowerSaveTempWhitelistAppIds.removeAt(i);
620 }
621 }
622 }
623
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800624 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800626 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700627 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800628 // Boost thread's priority during system server init
629 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700630 if (!isBandwidthControlEnabled()) {
631 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
632 return;
633 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700634
Felipe Leme873a83a2016-09-07 11:34:10 -0700635 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700636
Felipe Leme873a83a2016-09-07 11:34:10 -0700637 synchronized (mUidRulesFirstLock) {
638 synchronized (mNetworkPoliciesSecondLock) {
639 updatePowerSaveWhitelistUL();
640 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
641 mPowerManagerInternal.registerLowPowerModeObserver(
642 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800643 @Override
644 public int getServiceType() {
645 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700646 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800647
648 @Override
649 public void onLowPowerModeChanged(PowerSaveState result) {
650 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800651 if (LOGD) {
652 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
653 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800654 synchronized (mUidRulesFirstLock) {
655 if (mRestrictPower != enabled) {
656 mRestrictPower = enabled;
657 updateRulesForRestrictPowerUL();
658 }
659 }
660 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800661 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800662 mRestrictPower = mPowerManagerInternal.getLowPowerState(
663 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700664
665 mSystemReady = true;
666
667 // read policy from disk
668 readPolicyAL();
669
jackqdyulei29c82ab2017-03-10 14:09:16 -0800670 // Update the restrictBackground if battery saver is turned on
671 mRestrictBackgroundBeforeBsm = mRestrictBackground;
672 mRestrictBackgroundPowerState = mPowerManagerInternal
673 .getLowPowerState(ServiceType.DATA_SAVER);
674 final boolean localRestrictBackground =
675 mRestrictBackgroundPowerState.batterySaverEnabled;
676 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
677 mRestrictBackground = localRestrictBackground;
678 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
679 mRestrictBackground ? 1 : 0, 0).sendToTarget();
680 }
681 mPowerManagerInternal.registerLowPowerModeObserver(
682 new PowerManagerInternal.LowPowerModeListener() {
683 @Override
684 public int getServiceType() {
685 return ServiceType.DATA_SAVER;
686 }
687
688 @Override
689 public void onLowPowerModeChanged(PowerSaveState result) {
690 synchronized (mUidRulesFirstLock) {
691 updateRestrictBackgroundByLowPowerModeUL(result);
692 }
693 }
694 });
695
Felipe Leme873a83a2016-09-07 11:34:10 -0700696 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
697 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700698 }
Felipe Lemef0823852016-06-08 13:43:08 -0700699
Felipe Leme873a83a2016-09-07 11:34:10 -0700700 setRestrictBackgroundUL(mRestrictBackground);
701 updateRulesForGlobalChangeAL(false);
702 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700703 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700705
Sudheer Shankae7361852017-03-07 11:51:46 -0800706 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700707 try {
708 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000709 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800710 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700711 mNetworkManager.registerObserver(mAlertObserver);
712 } catch (RemoteException e) {
713 // ignored; both services live in system_server
714 }
715
716 // listen for changes to power save whitelist
717 final IntentFilter whitelistFilter = new IntentFilter(
718 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
719 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
720
721 DeviceIdleController.LocalService deviceIdleService
722 = LocalServices.getService(DeviceIdleController.LocalService.class);
723 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
724
725 // watch for network interfaces to be claimed
726 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
727 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
728
729 // listen for package changes to update policy
730 final IntentFilter packageFilter = new IntentFilter();
731 packageFilter.addAction(ACTION_PACKAGE_ADDED);
732 packageFilter.addDataScheme("package");
733 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
734
735 // listen for UID changes to update policy
736 mContext.registerReceiver(
737 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
738
739 // listen for user changes to update policy
740 final IntentFilter userFilter = new IntentFilter();
741 userFilter.addAction(ACTION_USER_ADDED);
742 userFilter.addAction(ACTION_USER_REMOVED);
743 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
744
745 // listen for stats update events
746 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
747 mContext.registerReceiver(
748 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
749
750 // listen for restrict background changes from notifications
751 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
752 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
753
754 // listen for snooze warning from notifications
755 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
756 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
757 MANAGE_NETWORK_POLICY, mHandler);
758
759 // listen for configured wifi networks to be removed
760 final IntentFilter wifiConfigFilter =
761 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
762 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
763
764 // listen for wifi state changes to catch metered hint
765 final IntentFilter wifiStateFilter = new IntentFilter(
766 WifiManager.NETWORK_STATE_CHANGED_ACTION);
767 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
768
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700769 // listen for carrier config changes to update data cycle information
770 final IntentFilter carrierConfigFilter = new IntentFilter(
771 ACTION_CARRIER_CONFIG_CHANGED);
772 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
773
Felipe Leme873a83a2016-09-07 11:34:10 -0700774 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800775 // tell systemReady() that the service has been initialized
776 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700777 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800778 // Restore the default priority after init is done
779 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700780 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700781 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700782 }
783
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800784 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
785 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
786 mHandler.post(() -> initService(initCompleteSignal));
787 return initCompleteSignal;
788 }
789
790 public void systemReady(CountDownLatch initCompleteSignal) {
791 // wait for initService to complete
792 try {
793 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
794 throw new IllegalStateException("Service " + TAG +" init timeout");
795 }
796 } catch (InterruptedException e) {
797 Thread.currentThread().interrupt();
798 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
799 }
800 }
801
Sudheer Shankac9d94072017-02-22 22:13:55 +0000802 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800803 @Override public void onUidStateChanged(int uid, int procState,
804 long procStateSeq) throws RemoteException {
Makoto Onuki8e777332017-03-28 11:25:47 -0700805 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
806 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700807 }
808
Dianne Hackborne07641d2016-11-09 15:07:23 -0800809 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Makoto Onuki8e777332017-03-28 11:25:47 -0700810 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700811 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812
813 @Override public void onUidActive(int uid) throws RemoteException {
814 }
815
Dianne Hackborne07641d2016-11-09 15:07:23 -0800816 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700817 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700818 };
819
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700820 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700821 @Override
822 public void onReceive(Context context, Intent intent) {
823 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700824 synchronized (mUidRulesFirstLock) {
825 updatePowerSaveWhitelistUL();
826 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700827 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700828 }
829 }
830 };
831
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700832 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
833 @Override
834 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700835 synchronized (mUidRulesFirstLock) {
836 updatePowerSaveTempWhitelistUL();
837 updateRulesForTempWhitelistChangeUL();
838 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700839 }
840 }
841 };
842
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700843 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700844 @Override
845 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700846 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700847
848 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700849 final int uid = intent.getIntExtra(EXTRA_UID, -1);
850 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700851
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700852 if (ACTION_PACKAGE_ADDED.equals(action)) {
853 // update rules for UID, since it might be subject to
854 // global background data policy
855 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700856 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700857 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700858 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700859 }
860 }
861 };
862
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700863 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700864 @Override
865 public void onReceive(Context context, Intent intent) {
866 // on background handler thread, and UID_REMOVED is protected
867
868 final int uid = intent.getIntExtra(EXTRA_UID, -1);
869 if (uid == -1) return;
870
871 // remove any policy and update rules to clean up
872 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700873 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700874 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700875 synchronized (mNetworkPoliciesSecondLock) {
876 writePolicyAL();
877 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700878 }
879 }
880 };
881
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700882 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700883 @Override
884 public void onReceive(Context context, Intent intent) {
885 // on background handler thread, and USER_ADDED and USER_REMOVED
886 // broadcasts are protected
887
888 final String action = intent.getAction();
889 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
890 if (userId == -1) return;
891
Amith Yamasani15e472352015-04-24 19:06:07 -0700892 switch (action) {
893 case ACTION_USER_REMOVED:
894 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700895 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800896 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700897 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700898 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700899 if (action == ACTION_USER_ADDED) {
900 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700901 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700902 }
903 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700904 synchronized (mNetworkPoliciesSecondLock) {
905 updateRulesForGlobalChangeAL(true);
906 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700907 }
908 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700909 }
910 }
911 };
912
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700913 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700914 * Receiver that watches for {@link INetworkStatsService} updates, which we
915 * use to check against {@link NetworkPolicy#warningBytes}.
916 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700917 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700918 @Override
919 public void onReceive(Context context, Intent intent) {
920 // on background handler thread, and verified
921 // READ_NETWORK_USAGE_HISTORY permission above.
922
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800923 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700924 synchronized (mNetworkPoliciesSecondLock) {
925 updateNetworkEnabledNL();
926 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 }
928 }
929 };
930
931 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700932 * Receiver that watches for {@link Notification} control of
933 * {@link #mRestrictBackground}.
934 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700935 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700936 @Override
937 public void onReceive(Context context, Intent intent) {
938 // on background handler thread, and verified MANAGE_NETWORK_POLICY
939 // permission above.
940
941 setRestrictBackground(false);
942 }
943 };
944
945 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800946 * Receiver that watches for {@link Notification} control of
947 * {@link NetworkPolicy#lastWarningSnooze}.
948 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800950 @Override
951 public void onReceive(Context context, Intent intent) {
952 // on background handler thread, and verified MANAGE_NETWORK_POLICY
953 // permission above.
954
955 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
956 performSnooze(template, TYPE_WARNING);
957 }
958 };
959
960 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700961 * Receiver that watches for {@link WifiConfiguration} to be changed.
962 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700963 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700964 @Override
965 public void onReceive(Context context, Intent intent) {
966 // on background handler thread, and verified CONNECTIVITY_INTERNAL
967 // permission above.
968
969 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
970 if (reason == CHANGE_REASON_REMOVED) {
971 final WifiConfiguration config = intent.getParcelableExtra(
972 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700973 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800974 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700975 synchronized (mUidRulesFirstLock) {
976 synchronized (mNetworkPoliciesSecondLock) {
977 if (mNetworkPolicy.containsKey(template)) {
978 mNetworkPolicy.remove(template);
979 writePolicyAL();
980 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700981 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700982 }
983 }
984 }
985 }
986 };
987
988 /**
989 * Receiver that watches {@link WifiInfo} state changes to infer metered
990 * state. Ignores hints when policy is user-defined.
991 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700992 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700993 @Override
994 public void onReceive(Context context, Intent intent) {
995 // on background handler thread, and verified CONNECTIVITY_INTERNAL
996 // permission above.
997
998 // ignore when not connected
999 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
1000 if (!netInfo.isConnected()) return;
1001
1002 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
1003 final boolean meteredHint = info.getMeteredHint();
1004
Jeff Sharkey2e4dce02012-12-18 17:06:06 -08001005 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Felipe Lemef0823852016-06-08 13:43:08 -07001006 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001007 NetworkPolicy policy = mNetworkPolicy.get(template);
1008 if (policy == null && meteredHint) {
1009 // policy doesn't exist, and AP is hinting that it's
1010 // metered: create an inferred policy.
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08001011 policy = newWifiPolicy(template, meteredHint);
Felipe Lemef0823852016-06-08 13:43:08 -07001012 addNetworkPolicyNL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001013
1014 } else if (policy != null && policy.inferred) {
1015 // policy exists, and was inferred: update its current
1016 // metered state.
1017 policy.metered = meteredHint;
1018
1019 // since this is inferred for each wifi session, just update
1020 // rules without persisting.
Felipe Lemef0823852016-06-08 13:43:08 -07001021 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001022 }
1023 }
1024 }
1025 };
1026
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08001027 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
1028 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
1029 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
1030 metered, true);
1031 }
1032
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001033 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001034 * Observer that watches for {@link INetworkManagementService} alerts.
1035 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001036 final private INetworkManagementEventObserver mAlertObserver
1037 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 @Override
1039 public void limitReached(String limitName, String iface) {
1040 // only someone like NMS should be calling us
1041 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1042
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001043 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1044 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 }
1046 }
1047 };
1048
1049 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001050 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1051 * to show visible notifications as needed.
1052 */
Felipe Lemef0823852016-06-08 13:43:08 -07001053 void updateNotificationsNL() {
1054 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001056 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001057 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001058 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059
1060 // TODO: when switching to kernel notifications, compute next future
1061 // cycle boundary to recompute notifications.
1062
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001063 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001064 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001065 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1066 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001067 // ignore policies that aren't relevant to user
1068 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001069 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001070
Jeff Sharkey497e4432011-06-14 17:27:29 -07001071 final long start = computeLastCycleBoundary(currentTime, policy);
1072 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001073 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001075 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001076 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001077 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1078 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001080 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 }
1082
Jeff Sharkey497e4432011-06-14 17:27:29 -07001083 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001084 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001086 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001087 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001088 }
1089 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001090 }
1091
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001092 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001093 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001094 final NotificationId notificationId = beforeNotifs.valueAt(i);
1095 if (!mActiveNotifs.contains(notificationId)) {
1096 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001097 }
1098 }
1099 }
1100
1101 /**
1102 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001103 * current device state, such as when
1104 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1105 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001106 */
1107 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001108 if (template.isMatchRuleMobile()) {
1109 final TelephonyManager tele = TelephonyManager.from(mContext);
1110 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001111
Jeff Sharkey32566012014-12-02 18:30:14 -08001112 // Mobile template is relevant when any active subscriber matches
1113 final int[] subIds = sub.getActiveSubscriptionIdList();
1114 for (int subId : subIds) {
1115 final String subscriberId = tele.getSubscriberId(subId);
1116 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001117 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001118 if (template.matches(probeIdent)) {
1119 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001120 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001121 }
1122 return false;
1123 } else {
1124 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001125 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001126 }
1127
1128 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001129 * Notify that given {@link NetworkTemplate} is over
1130 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1131 */
Felipe Lemef0823852016-06-08 13:43:08 -07001132 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001133 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001134 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001135 mOverLimitNotified.add(template);
1136 }
1137 }
1138
Felipe Lemef0823852016-06-08 13:43:08 -07001139 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001140 mOverLimitNotified.remove(template);
1141 }
1142
1143 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001144 * Show notification for combined {@link NetworkPolicy} and specific type,
1145 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1146 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001148 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001149 final Notification.Builder builder =
1150 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001151 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001152 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001153 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001154 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001155
1156 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001157 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001158 switch (type) {
1159 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001160 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001161 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001162
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001163 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164 builder.setTicker(title);
1165 builder.setContentTitle(title);
1166 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001167 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001168 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001169
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001170 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1171 builder.setDeleteIntent(PendingIntent.getBroadcast(
1172 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1173
Wei Liu546cb772016-07-21 16:19:01 -07001174 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001175 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001176 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1177
Jeff Sharkey497e4432011-06-14 17:27:29 -07001178 break;
1179 }
1180 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001181 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001182
1183 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001184 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001185 switch (policy.template.getMatchRule()) {
1186 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001187 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001189 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001190 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001191 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001192 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001193 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001194 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001195 case MATCH_WIFI:
1196 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001197 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001198 break;
1199 default:
1200 title = null;
1201 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001202 }
1203
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001204 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001205 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 builder.setTicker(title);
1207 builder.setContentTitle(title);
1208 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001209
Wei Liu546cb772016-07-21 16:19:01 -07001210 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001211 builder.setContentIntent(PendingIntent.getActivity(
1212 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1213 break;
1214 }
1215 case TYPE_LIMIT_SNOOZED: {
1216 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001217 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001218 Formatter.formatFileSize(mContext, overBytes));
1219
1220 final CharSequence title;
1221 switch (policy.template.getMatchRule()) {
1222 case MATCH_MOBILE_3G_LOWER:
1223 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1224 break;
1225 case MATCH_MOBILE_4G:
1226 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1227 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001228 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001229 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1230 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001231 case MATCH_WIFI:
1232 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1233 break;
1234 default:
1235 title = null;
1236 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001237 }
1238
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001239 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001240 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001241 builder.setTicker(title);
1242 builder.setContentTitle(title);
1243 builder.setContentText(body);
1244
Wei Liu546cb772016-07-21 16:19:01 -07001245 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001246 builder.setContentIntent(PendingIntent.getActivity(
1247 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001248 break;
1249 }
1250 }
1251
1252 // TODO: move to NotificationManager once we can mock it
1253 try {
1254 final String packageName = mContext.getPackageName();
1255 final int[] idReceived = new int[1];
Chris Wren193ae6b2017-03-31 15:17:11 -04001256 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001257 builder.setStyle(new Notification.BigTextStyle()
1258 .bigText(body));
1259 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001260 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001261 packageName, packageName, notificationId.getTag(), notificationId.getId(),
1262 builder.build(), idReceived, UserHandle.USER_ALL);
1263 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001264 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001265 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001266 }
1267 }
1268
Chris Wren193ae6b2017-03-31 15:17:11 -04001269 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001270 // TODO: move to NotificationManager once we can mock it
1271 try {
1272 final String packageName = mContext.getPackageName();
1273 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001274 packageName, notificationId.getTag(), notificationId.getId(),
1275 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001276 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001277 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001278 }
1279 }
1280
1281 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001282 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001283 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001285 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001286 @Override
1287 public void onReceive(Context context, Intent intent) {
1288 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1289 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001290
1291 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07001292 synchronized (mNetworkPoliciesSecondLock) {
1293 ensureActiveMobilePolicyNL();
1294 normalizePoliciesNL();
1295 updateNetworkEnabledNL();
1296 updateNetworkRulesNL();
1297 updateNotificationsNL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001298 }
1299 }
1300 };
1301
1302 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001303 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1304 * if necessary.
1305 *
1306 * @param subId that has its associated NetworkPolicy updated if necessary
1307 * @return if any policies were updated
1308 */
1309 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1310 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1311 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1312
1313 if (config == null) {
1314 return false;
1315 }
1316
1317 boolean policyUpdated = false;
1318 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1319
1320 // find and update the mobile NetworkPolicy for this subscriber id
1321 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1322 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1323 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1324 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1325 if (template.matches(probeIdent)) {
1326 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1327
1328 // only update the policy if the user didn't change any of the defaults.
1329 if (!policy.inferred) {
1330 // TODO: inferred could be split, so that if a user changes their data limit or
1331 // warning, it doesn't prevent their cycle date from being updated.
1332 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1333 continue;
1334 }
1335
1336 final int cycleDay = getCycleDayFromCarrierConfig(config, policy.cycleDay);
1337 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1338 policy.warningBytes);
1339 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1340 policy.limitBytes);
1341
1342 if (policy.cycleDay == cycleDay &&
1343 policy.warningBytes == warningBytes &&
1344 policy.limitBytes == limitBytes) {
1345 continue;
1346 }
1347
1348 policyUpdated = true;
1349 policy.cycleDay = cycleDay;
1350 policy.warningBytes = warningBytes;
1351 policy.limitBytes = limitBytes;
1352
1353 if (LOGD) {
1354 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1355 + NetworkIdentity.scrubSubscriberId(subscriberId)
1356 + " from CarrierConfigManager");
1357 }
1358 }
1359 }
1360
1361 return policyUpdated;
1362 }
1363
1364 /**
1365 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1366 *
1367 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1368 * to do so, it returns the fallback value.
1369 *
1370 * @param config The CarrierConfig to read the value from.
1371 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1372 * @return cycleDay to use in the mobile NetworkPolicy.
1373 */
1374 @VisibleForTesting
1375 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1376 int fallbackCycleDay) {
1377 if (config == null) {
1378 return fallbackCycleDay;
1379 }
1380 int cycleDay =
1381 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1382 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1383 return fallbackCycleDay;
1384 }
1385 // validate cycleDay value
1386 final Calendar cal = Calendar.getInstance();
1387 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1388 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1389 Slog.e(TAG, "Invalid date in "
1390 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1391 return fallbackCycleDay;
1392 }
1393 return cycleDay;
1394 }
1395
1396 /**
1397 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1398 *
1399 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1400 * to do so, it returns the fallback value.
1401 *
1402 * @param config The CarrierConfig to read the value from.
1403 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1404 * @return warningBytes to use in the mobile NetworkPolicy.
1405 */
1406 @VisibleForTesting
1407 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1408 long fallbackWarningBytes) {
1409 if (config == null) {
1410 return fallbackWarningBytes;
1411 }
1412 long warningBytes =
1413 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1414
1415 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1416 return WARNING_DISABLED;
1417 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1418 return getPlatformDefaultWarningBytes();
1419 } else if (warningBytes < 0) {
1420 Slog.e(TAG, "Invalid value in "
1421 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1422 + "non-negative value but got: " + warningBytes);
1423 return fallbackWarningBytes;
1424 }
1425
1426 return warningBytes;
1427 }
1428
1429 /**
1430 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1431 *
1432 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1433 * to do so, it returns the fallback value.
1434 *
1435 * @param config The CarrierConfig to read the value from.
1436 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1437 * @return limitBytes to use in the mobile NetworkPolicy.
1438 */
1439 @VisibleForTesting
1440 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1441 long fallbackLimitBytes) {
1442 if (config == null) {
1443 return fallbackLimitBytes;
1444 }
1445 long limitBytes =
1446 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1447
1448 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1449 return LIMIT_DISABLED;
1450 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1451 return getPlatformDefaultLimitBytes();
1452 } else if (limitBytes < 0) {
1453 Slog.e(TAG, "Invalid value in "
1454 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1455 + "non-negative value but got: " + limitBytes);
1456 return fallbackLimitBytes;
1457 }
1458 return limitBytes;
1459 }
1460
1461 /**
1462 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1463 */
1464 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1465 @Override
1466 public void onReceive(Context context, Intent intent) {
1467 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1468 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1469
1470 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1471 return;
1472 }
1473 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1474 final TelephonyManager tele = TelephonyManager.from(mContext);
1475 final String subscriberId = tele.getSubscriberId(subId);
1476
1477 maybeRefreshTrustedTime();
1478 synchronized (mUidRulesFirstLock) {
1479 synchronized (mNetworkPoliciesSecondLock) {
1480 final boolean added = ensureActiveMobilePolicyNL(subId, subscriberId);
1481 if (added) return;
1482 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1483 if (!updated) return;
1484 // update network and notification rules, as the data cycle changed and it's
1485 // possible that we should be triggering warnings/limits now
1486 handleNetworkPoliciesUpdateAL(true);
1487 }
1488 }
1489 }
1490 };
1491
1492 /**
1493 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1494 * one has been updated.
1495 *
1496 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1497 * update.
1498 */
1499 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1500 if (shouldNormalizePolicies) {
1501 normalizePoliciesNL();
1502 }
1503 updateNetworkEnabledNL();
1504 updateNetworkRulesNL();
1505 updateNotificationsNL();
1506 writePolicyAL();
1507 }
1508
1509 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001510 * Proactively control network data connections when they exceed
1511 * {@link NetworkPolicy#limitBytes}.
1512 */
Felipe Lemef0823852016-06-08 13:43:08 -07001513 void updateNetworkEnabledNL() {
1514 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001515
1516 // TODO: reset any policy-disabled networks when any policy is removed
1517 // completely, which is currently rare case.
1518
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001519 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001520 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1521 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001522 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001523 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001524 setNetworkTemplateEnabled(policy.template, true);
1525 continue;
1526 }
1527
1528 final long start = computeLastCycleBoundary(currentTime, policy);
1529 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001530 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001531
1532 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001533 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1534 && policy.lastLimitSnooze < start;
1535 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001536
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001537 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001538 }
1539 }
1540
1541 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001542 * Proactively disable networks that match the given
1543 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001544 */
1545 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001546 // TODO: reach into ConnectivityManager to proactively disable bringing
1547 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001548
1549 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1550 // If mobile data usage hits the limit or if the user resumes the data, we need to
1551 // notify telephony.
1552 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1553 final TelephonyManager tm = TelephonyManager.from(mContext);
1554
1555 final int[] subIds = sm.getActiveSubscriptionIdList();
1556 for (int subId : subIds) {
1557 final String subscriberId = tm.getSubscriberId(subId);
1558 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1559 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1560 // Template is matched when subscriber id matches.
1561 if (template.matches(probeIdent)) {
1562 tm.setPolicyDataEnabled(enabled, subId);
1563 }
1564 }
1565 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001566 }
1567
1568 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001569 * Examine all connected {@link NetworkState}, looking for
1570 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1571 * remaining quota based on usage cycle and historical stats.
1572 */
Felipe Lemef0823852016-06-08 13:43:08 -07001573 void updateNetworkRulesNL() {
1574 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001575
1576 final NetworkState[] states;
1577 try {
1578 states = mConnManager.getAllNetworkState();
1579 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001580 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 return;
1582 }
1583
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001584 // First, generate identities of all connected networks so we can
1585 // quickly compare them against all defined policies below.
1586 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001587 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001588 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001589 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001590 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001591
1592 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001593 if (baseIface != null) {
1594 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001595 }
1596
1597 // Stacked interfaces are considered to have same identity as
1598 // their parent network.
1599 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1600 for (LinkProperties stackedLink : stackedLinks) {
1601 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001602 if (stackedIface != null) {
1603 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001604 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001605 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001606 }
1607 }
1608
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001609 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001610 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001612 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001613 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001614
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001615 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001616 for (int j = connIdents.size() - 1; j >= 0; j--) {
1617 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1618 if (policy.template.matches(ident.second)) {
1619 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 }
1621 }
1622
1623 if (ifaceList.size() > 0) {
1624 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001625 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001626 }
1627 }
1628
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001629 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001630 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001631
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001632 // apply each policy that we found ifaces for; compute remaining data
1633 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001634 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001635 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1636 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1637 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001638
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001639 final long start;
1640 final long totalBytes;
1641 if (policy.hasCycle()) {
1642 start = computeLastCycleBoundary(currentTime, policy);
1643 totalBytes = getTotalBytes(policy.template, start, currentTime);
1644 } else {
1645 start = Long.MAX_VALUE;
1646 totalBytes = 0;
1647 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001648
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001649 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001650 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001651 }
1652
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001653 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001654 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001655 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001656 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001657 if (!hasLimit) {
1658 // metered network, but no policy limit; we still need to
1659 // restrict apps, so push really high quota.
1660 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001661 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001662 // snoozing past quota, but we still need to restrict apps,
1663 // so push really high quota.
1664 quotaBytes = Long.MAX_VALUE;
1665 } else {
1666 // remaining "quota" bytes are based on total usage in
1667 // current cycle. kernel doesn't like 0-byte rules, so we
1668 // set 1-byte quota and disable the radio later.
1669 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1670 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001671
1672 if (ifaces.length > 1) {
1673 // TODO: switch to shared quota once NMS supports
1674 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001675 }
1676
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001677 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001678 // long quotaBytes split up into two ints to fit in message
1679 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1680 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1681 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001682 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001683 }
1684 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001685
1686 // keep track of lowest warning or limit of active policies
1687 if (hasWarning && policy.warningBytes < lowestRule) {
1688 lowestRule = policy.warningBytes;
1689 }
1690 if (hasLimit && policy.limitBytes < lowestRule) {
1691 lowestRule = policy.limitBytes;
1692 }
1693 }
1694
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001695 for (int i = connIfaces.size()-1; i >= 0; i--) {
1696 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001697 // long quotaBytes split up into two ints to fit in message
1698 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1699 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1700 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001701 newMeteredIfaces.add(iface);
1702 }
1703
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001704 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001705
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001706 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001707 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1708 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001709 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001710 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1711 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001712 }
1713 }
1714 mMeteredIfaces = newMeteredIfaces;
1715
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001716 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001717 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001718 }
1719
1720 /**
1721 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1722 * have at least a default mobile policy defined.
1723 */
Felipe Lemef0823852016-06-08 13:43:08 -07001724 private void ensureActiveMobilePolicyNL() {
1725 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001726 if (mSuppressDefaultPolicy) return;
1727
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001728 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001729 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001730
Jeff Sharkey32566012014-12-02 18:30:14 -08001731 final int[] subIds = sub.getActiveSubscriptionIdList();
1732 for (int subId : subIds) {
1733 final String subscriberId = tele.getSubscriberId(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001734 ensureActiveMobilePolicyNL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001735 }
1736 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001737
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001738 /**
1739 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1740 * have at least a default mobile policy defined.
1741 *
1742 * @param subId to build a default policy for
1743 * @param subscriberId that we check for an existing policy
1744 * @return true if a mobile network policy was added, or false one already existed.
1745 */
1746 private boolean ensureActiveMobilePolicyNL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001747 // Poke around to see if we already have a policy
1748 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001749 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001750 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1751 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1752 if (template.matches(probeIdent)) {
1753 if (LOGD) {
1754 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1755 + NetworkIdentity.scrubSubscriberId(subscriberId));
1756 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001757 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001758 }
1759 }
1760
Jeff Sharkey32566012014-12-02 18:30:14 -08001761 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1762 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001763 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
1764 addNetworkPolicyNL(policy);
1765 return true;
1766 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001767
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001768 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001769 final int dataWarningConfig = mContext.getResources().getInteger(
1770 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001771 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001772 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001773 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001774 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001775 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001776 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001777
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001778 private long getPlatformDefaultLimitBytes() {
1779 return LIMIT_DISABLED;
1780 }
1781
1782 @VisibleForTesting
1783 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1784 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1785
1786 // assume usage cycle starts today
Jeff Sharkey32566012014-12-02 18:30:14 -08001787 final Time time = new Time();
1788 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001789
Jeff Sharkey32566012014-12-02 18:30:14 -08001790 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001791
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001792 final int cycleDay = getCycleDayFromCarrierConfig(config, time.monthDay);
1793 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1794 getPlatformDefaultWarningBytes());
1795 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1796 getPlatformDefaultLimitBytes());
1797
Jeff Sharkey32566012014-12-02 18:30:14 -08001798 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1799 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001800 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1801 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802 }
1803
Felipe Lemef0823852016-06-08 13:43:08 -07001804 private void readPolicyAL() {
1805 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001806
1807 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001808 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001809 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001810
1811 FileInputStream fis = null;
1812 try {
1813 fis = mPolicyFile.openRead();
1814 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001815 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001816
Felipe Leme46b451f2016-08-19 08:46:17 -07001817 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1818 // to skip UIDs that were explicitly blacklisted.
1819 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1820
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001822 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001823 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001824 while ((type = in.next()) != END_DOCUMENT) {
1825 final String tag = in.getName();
1826 if (type == START_TAG) {
1827 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001828 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001829 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001830 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1831 mRestrictBackground = readBooleanAttribute(
1832 in, ATTR_RESTRICT_BACKGROUND);
1833 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001834 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001835 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001836 if (mRestrictBackground != oldValue) {
1837 // Some early services may have read the default value,
1838 // so notify them that it's changed
1839 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1840 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1841 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001842
1843 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1844 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1845 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001846 final String networkId;
1847 if (version >= VERSION_ADDED_NETWORK_ID) {
1848 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1849 } else {
1850 networkId = null;
1851 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001852 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001853 final String cycleTimezone;
1854 if (version >= VERSION_ADDED_TIMEZONE) {
1855 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1856 } else {
1857 cycleTimezone = Time.TIMEZONE_UTC;
1858 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001859 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1860 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001861 final long lastLimitSnooze;
1862 if (version >= VERSION_SPLIT_SNOOZE) {
1863 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1864 } else if (version >= VERSION_ADDED_SNOOZE) {
1865 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001866 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001867 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001868 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001869 final boolean metered;
1870 if (version >= VERSION_ADDED_METERED) {
1871 metered = readBooleanAttribute(in, ATTR_METERED);
1872 } else {
1873 switch (networkTemplate) {
1874 case MATCH_MOBILE_3G_LOWER:
1875 case MATCH_MOBILE_4G:
1876 case MATCH_MOBILE_ALL:
1877 metered = true;
1878 break;
1879 default:
1880 metered = false;
1881 }
1882 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001883 final long lastWarningSnooze;
1884 if (version >= VERSION_SPLIT_SNOOZE) {
1885 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1886 } else {
1887 lastWarningSnooze = SNOOZE_NEVER;
1888 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001889 final boolean inferred;
1890 if (version >= VERSION_ADDED_INFERRED) {
1891 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1892 } else {
1893 inferred = false;
1894 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001895
Jeff Sharkey32566012014-12-02 18:30:14 -08001896 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1897 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001898 if (template.isPersistable()) {
1899 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1900 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1901 lastLimitSnooze, metered, inferred));
1902 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001903
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001904 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001905 final int uid = readIntAttribute(in, ATTR_UID);
1906 final int policy = readIntAttribute(in, ATTR_POLICY);
1907
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001908 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001909 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001910 } else {
1911 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1912 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001913 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001914 final int appId = readIntAttribute(in, ATTR_APP_ID);
1915 final int policy = readIntAttribute(in, ATTR_POLICY);
1916
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001917 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001918 // app policy is deprecated so this is only used in pre system user split.
1919 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001920 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001921 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001922 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001923 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001924 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001925 } else if (TAG_WHITELIST.equals(tag)) {
1926 insideWhitelist = true;
1927 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1928 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001929 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001930 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1931 final int uid = readIntAttribute(in, ATTR_UID);
1932 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001933 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001934 } else if (type == END_TAG) {
1935 if (TAG_WHITELIST.equals(tag)) {
1936 insideWhitelist = false;
1937 }
1938
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001939 }
1940 }
1941
Felipe Leme46b451f2016-08-19 08:46:17 -07001942 final int size = whitelistedRestrictBackground.size();
1943 for (int i = 0; i < size; i++) {
1944 final int uid = whitelistedRestrictBackground.keyAt(i);
1945 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1946 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1947 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1948 + " because its policy is " + uidPoliciesToString(policy));
1949 continue;
1950 }
1951 if (UserHandle.isApp(uid)) {
1952 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1953 if (LOGV)
1954 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1955 setUidPolicyUncheckedUL(uid, newPolicy, false);
1956 } else {
1957 Slog.w(TAG, "unable to update policy on UID " + uid);
1958 }
1959 }
1960
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 } catch (FileNotFoundException e) {
1962 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001963 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001964 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001965 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001966 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001967 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001968 } finally {
1969 IoUtils.closeQuietly(fis);
1970 }
1971 }
1972
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001973 /**
1974 * Upgrade legacy background data flags, notifying listeners of one last
1975 * change to always-true.
1976 */
Felipe Lemef0823852016-06-08 13:43:08 -07001977 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001978 mRestrictBackground = Settings.Secure.getInt(
1979 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1980
1981 // kick off one last broadcast if restricted
1982 if (mRestrictBackground) {
1983 final Intent broadcast = new Intent(
1984 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001985 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001986 }
1987 }
1988
Felipe Lemef0823852016-06-08 13:43:08 -07001989 void writePolicyAL() {
1990 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001991
1992 FileOutputStream fos = null;
1993 try {
1994 fos = mPolicyFile.startWrite();
1995
1996 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001997 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998 out.startDocument(null, true);
1999
2000 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002001 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002002 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002003
2004 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002005 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2006 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002007 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002008 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002009
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002010 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002011 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2012 final String subscriberId = template.getSubscriberId();
2013 if (subscriberId != null) {
2014 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002015 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002016 final String networkId = template.getNetworkId();
2017 if (networkId != null) {
2018 out.attribute(null, ATTR_NETWORK_ID, networkId);
2019 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002021 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002022 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2023 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002024 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2025 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002026 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002027 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002028 out.endTag(null, TAG_NETWORK_POLICY);
2029 }
2030
2031 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002032 for (int i = 0; i < mUidPolicy.size(); i++) {
2033 final int uid = mUidPolicy.keyAt(i);
2034 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002035
Jeff Sharkey497e4432011-06-14 17:27:29 -07002036 // skip writing empty policies
2037 if (policy == POLICY_NONE) continue;
2038
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002039 out.startTag(null, TAG_UID_POLICY);
2040 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002041 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002042 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002043 }
2044
2045 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002046
2047 // write all whitelists
2048 out.startTag(null, TAG_WHITELIST);
2049
Felipe Lemea9505cc2016-02-26 10:28:41 -08002050 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002051 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002052 for (int i = 0; i < size; i++) {
2053 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2054 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2055 writeIntAttribute(out, ATTR_UID, uid);
2056 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2057 }
2058
Felipe Lemeb85a6372016-01-14 16:16:16 -08002059 out.endTag(null, TAG_WHITELIST);
2060
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002061 out.endDocument();
2062
2063 mPolicyFile.finishWrite(fos);
2064 } catch (IOException e) {
2065 if (fos != null) {
2066 mPolicyFile.failWrite(fos);
2067 }
2068 }
2069 }
2070
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002071 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002072 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002073 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002074
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002075 if (!UserHandle.isApp(uid)) {
2076 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002077 }
Felipe Lemef0823852016-06-08 13:43:08 -07002078 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002079 final long token = Binder.clearCallingIdentity();
2080 try {
2081 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2082 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002083 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002084 }
2085 } finally {
2086 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002087 }
2088 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002089 }
2090
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002091 @Override
2092 public void addUidPolicy(int uid, int policy) {
2093 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002094
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002095 if (!UserHandle.isApp(uid)) {
2096 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2097 }
2098
Felipe Lemef0823852016-06-08 13:43:08 -07002099 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002100 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2101 policy |= oldPolicy;
2102 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002103 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002104 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002105 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002106 }
2107
2108 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002109 public void removeUidPolicy(int uid, int policy) {
2110 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2111
2112 if (!UserHandle.isApp(uid)) {
2113 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2114 }
2115
Felipe Lemef0823852016-06-08 13:43:08 -07002116 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002117 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2118 policy = oldPolicy & ~policy;
2119 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002120 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002121 }
2122 }
2123 }
2124
Felipe Lemef0823852016-06-08 13:43:08 -07002125 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2126 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002127
Felipe Leme57e3d312016-08-23 14:42:52 -07002128 final boolean notifyApp;
2129 if (!isUidValidForWhitelistRules(uid)) {
2130 notifyApp = false;
2131 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002132 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2133 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2134 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2135 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002136 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2137 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002138 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2139 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2140 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2141 if (LOGD)
2142 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2143 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2144 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002145 notifyApp = wasBlocked != isBlocked;
2146 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002147 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2148 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002149 }
2150
Felipe Lemef0823852016-06-08 13:43:08 -07002151 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002152 if (policy == POLICY_NONE) {
2153 mUidPolicy.delete(uid);
2154 } else {
2155 mUidPolicy.put(uid, policy);
2156 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002157
2158 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002159 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002160 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002161 synchronized (mNetworkPoliciesSecondLock) {
2162 writePolicyAL();
2163 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002164 }
2165 }
2166
2167 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002168 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002169 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2170
Felipe Lemef0823852016-06-08 13:43:08 -07002171 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002172 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002173 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002174 }
2175
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002176 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002177 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002178 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2179
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002180 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002181 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002182 for (int i = 0; i < mUidPolicy.size(); i++) {
2183 final int uid = mUidPolicy.keyAt(i);
2184 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002185 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2186 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002187 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002188 }
2189 }
2190 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002191 return uids;
2192 }
2193
2194 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002195 * Removes any persistable state associated with given {@link UserHandle}, persisting
2196 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002197 */
Felipe Lemef0823852016-06-08 13:43:08 -07002198 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002199
Felipe Lemef0823852016-06-08 13:43:08 -07002200 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002201 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002202
Felipe Lemea110eec2016-04-29 09:58:06 -07002203 // Remove entries from revoked default restricted background UID whitelist
2204 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2205 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2206 if (UserHandle.getUserId(uid) == userId) {
2207 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002208 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002209 }
2210 }
2211
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002212 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002213 int[] uids = new int[0];
2214 for (int i = 0; i < mUidPolicy.size(); i++) {
2215 final int uid = mUidPolicy.keyAt(i);
2216 if (UserHandle.getUserId(uid) == userId) {
2217 uids = appendInt(uids, uid);
2218 }
2219 }
2220
2221 if (uids.length > 0) {
2222 for (int uid : uids) {
2223 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002224 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002225 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002226 }
Felipe Lemef0823852016-06-08 13:43:08 -07002227 synchronized (mNetworkPoliciesSecondLock) {
2228 updateRulesForGlobalChangeAL(true);
2229 if (writePolicy && changed) {
2230 writePolicyAL();
2231 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002232 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002233 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002234 }
2235
2236 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002237 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002238 // TODO: create permission for observing network policy
2239 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002240 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002241 }
2242
2243 @Override
2244 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002245 // TODO: create permission for observing network policy
2246 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002247 mListeners.unregister(listener);
2248 }
2249
Jeff Sharkey1b861272011-05-22 00:34:52 -07002250 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002251 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002252 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2253
Felipe Leme6a05eee2016-02-19 14:43:51 -08002254 final long token = Binder.clearCallingIdentity();
2255 try {
2256 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002257 synchronized (mUidRulesFirstLock) {
2258 synchronized (mNetworkPoliciesSecondLock) {
2259 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002260 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002261 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002262 }
2263 } finally {
2264 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002265 }
2266 }
2267
Felipe Lemef0823852016-06-08 13:43:08 -07002268 void addNetworkPolicyNL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002269 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002270 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2271 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002272 }
2273
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002274 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002275 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002276 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002277 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002278 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2279 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2280 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002281 } catch (SecurityException e) {
2282 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002283
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002284 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2285 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2286 return new NetworkPolicy[0];
2287 }
Svet Ganov16a16892015-04-16 10:32:04 -07002288 }
2289
Felipe Lemef0823852016-06-08 13:43:08 -07002290 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002291 final int size = mNetworkPolicy.size();
2292 final NetworkPolicy[] policies = new NetworkPolicy[size];
2293 for (int i = 0; i < size; i++) {
2294 policies[i] = mNetworkPolicy.valueAt(i);
2295 }
2296 return policies;
2297 }
2298 }
2299
Felipe Lemef0823852016-06-08 13:43:08 -07002300 private void normalizePoliciesNL() {
2301 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002302 }
2303
Felipe Lemef0823852016-06-08 13:43:08 -07002304 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002305 final TelephonyManager tele = TelephonyManager.from(mContext);
2306 final String[] merged = tele.getMergedSubscriberIds();
2307
2308 mNetworkPolicy.clear();
2309 for (NetworkPolicy policy : policies) {
2310 // When two normalized templates conflict, prefer the most
2311 // restrictive policy
2312 policy.template = NetworkTemplate.normalize(policy.template, merged);
2313 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2314 if (existing == null || existing.compareTo(policy) > 0) {
2315 if (existing != null) {
2316 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2317 }
2318 mNetworkPolicy.put(policy.template, policy);
2319 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002320 }
2321 }
2322
2323 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002324 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002325 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002326
2327 final long token = Binder.clearCallingIdentity();
2328 try {
2329 performSnooze(template, TYPE_LIMIT);
2330 } finally {
2331 Binder.restoreCallingIdentity(token);
2332 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002333 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002334
Dianne Hackborn497175b2014-07-01 12:56:08 -07002335 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002336 maybeRefreshTrustedTime();
2337 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002338 synchronized (mUidRulesFirstLock) {
2339 synchronized (mNetworkPoliciesSecondLock) {
2340 // find and snooze local policy that matches
2341 final NetworkPolicy policy = mNetworkPolicy.get(template);
2342 if (policy == null) {
2343 throw new IllegalArgumentException("unable to find policy for " + template);
2344 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002345
Felipe Lemef0823852016-06-08 13:43:08 -07002346 switch (type) {
2347 case TYPE_WARNING:
2348 policy.lastWarningSnooze = currentTime;
2349 break;
2350 case TYPE_LIMIT:
2351 policy.lastLimitSnooze = currentTime;
2352 break;
2353 default:
2354 throw new IllegalArgumentException("unexpected type");
2355 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002356
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002357 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002358 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002359 }
2360 }
2361
2362 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002363 public void onTetheringChanged(String iface, boolean tethering) {
2364 // No need to enforce permission because setRestrictBackground() will do it.
2365 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002366 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002367 if (mRestrictBackground && tethering) {
2368 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2369 setRestrictBackground(false);
2370 }
2371 }
2372 }
2373
2374 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002375 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002376 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002377 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002378 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2379 final long token = Binder.clearCallingIdentity();
2380 try {
2381 maybeRefreshTrustedTime();
2382 synchronized (mUidRulesFirstLock) {
2383 if (restrictBackground == mRestrictBackground) {
2384 // Ideally, UI should never allow this scenario...
2385 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2386 return;
2387 }
2388 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002389 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002390
2391 } finally {
2392 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002393 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002394
Felipe Leme29e72ea2016-09-08 13:26:55 -07002395 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2396 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002397 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002398 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002399 }
2400 }
2401
Felipe Lemef0823852016-06-08 13:43:08 -07002402 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002403 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002404 final boolean oldRestrictBackground = mRestrictBackground;
2405 mRestrictBackground = restrictBackground;
2406 // Must whitelist foreground apps before turning data saver mode on.
2407 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2408 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002409 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002410 try {
2411 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2412 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2413 mRestrictBackground = oldRestrictBackground;
2414 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002415 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002416 return;
2417 }
2418 } catch (RemoteException e) {
2419 // ignored; service lives in system_server
2420 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002421
2422 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2423 mRestrictBackgroundChangedInBsm = true;
2424 }
Felipe Lemef0823852016-06-08 13:43:08 -07002425 synchronized (mNetworkPoliciesSecondLock) {
2426 updateNotificationsNL();
2427 writePolicyAL();
2428 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002429 }
2430
Felipe Lemeb85a6372016-01-14 16:16:16 -08002431 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002432 public int getRestrictBackgroundByCaller() {
2433 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2434 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002435
Felipe Lemef0823852016-06-08 13:43:08 -07002436 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002437 // Must clear identity because getUidPolicy() is restricted to system.
2438 final long token = Binder.clearCallingIdentity();
2439 final int policy;
2440 try {
2441 policy = getUidPolicy(uid);
2442 } finally {
2443 Binder.restoreCallingIdentity(token);
2444 }
2445 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2446 // App is blacklisted.
2447 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2448 }
Felipe Leme1b103232016-01-22 09:44:57 -08002449 if (!mRestrictBackground) {
2450 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2451 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002452 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002453 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2454 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2455 }
2456 }
2457
2458 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002459 public boolean getRestrictBackground() {
2460 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2461
Felipe Lemef0823852016-06-08 13:43:08 -07002462 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002463 return mRestrictBackground;
2464 }
2465 }
2466
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002467 @Override
2468 public void setDeviceIdleMode(boolean enabled) {
2469 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002470 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2471 try {
2472 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002473 if (mDeviceIdleMode == enabled) {
2474 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002475 }
Felipe Lemeea014392016-09-06 13:59:54 -07002476 mDeviceIdleMode = enabled;
2477 if (mSystemReady) {
2478 // Device idle change means we need to rebuild rules for all
2479 // known apps, so do a global refresh.
2480 updateRulesForRestrictPowerUL();
2481 }
2482 }
2483 if (enabled) {
2484 EventLogTags.writeDeviceIdleOnPhase("net");
2485 } else {
2486 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002487 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002488 } finally {
2489 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002490 }
2491 }
2492
Felipe Lemef0823852016-06-08 13:43:08 -07002493 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002494 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2495 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002496 if (policy.template.matches(ident)) {
2497 return policy;
2498 }
2499 }
2500 return null;
2501 }
2502
2503 @Override
2504 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2505 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2506
2507 // only returns usage summary, so we don't require caller to have
2508 // READ_NETWORK_USAGE_HISTORY.
2509 final long token = Binder.clearCallingIdentity();
2510 try {
2511 return getNetworkQuotaInfoUnchecked(state);
2512 } finally {
2513 Binder.restoreCallingIdentity(token);
2514 }
2515 }
2516
2517 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2518 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2519
2520 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002521 synchronized (mNetworkPoliciesSecondLock) {
2522 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002523 }
2524
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002525 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002526 // missing policy means we can't derive useful quota info
2527 return null;
2528 }
2529
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002530 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002531
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002532 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002533 final long start = computeLastCycleBoundary(currentTime, policy);
2534 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002535 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002536
2537 // report soft and hard limits under policy
2538 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2539 : NetworkQuotaInfo.NO_LIMIT;
2540 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2541 : NetworkQuotaInfo.NO_LIMIT;
2542
2543 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2544 }
2545
Jeff Sharkey46645002011-07-27 21:11:21 -07002546 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002547 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002548 if (state.networkInfo == null) {
2549 return false;
2550 }
2551
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002552 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2553
2554 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002555 synchronized (mNetworkPoliciesSecondLock) {
2556 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002557 }
2558
2559 if (policy != null) {
2560 return policy.metered;
2561 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002562 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002563 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002564 return true;
2565 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002566 return false;
2567 }
2568 }
2569
2570 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002571 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002572 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002573
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002574 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2575
Dianne Hackborn497175b2014-07-01 12:56:08 -07002576 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002577 for (String arg : args) {
2578 argSet.add(arg);
2579 }
2580
Felipe Lemef0823852016-06-08 13:43:08 -07002581 synchronized (mUidRulesFirstLock) {
2582 synchronized (mNetworkPoliciesSecondLock) {
2583 if (argSet.contains("--unsnooze")) {
2584 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2585 mNetworkPolicy.valueAt(i).clearSnooze();
2586 }
2587
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002588 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002589
2590 fout.println("Cleared snooze timestamps");
2591 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002592 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002593
Felipe Lemef0823852016-06-08 13:43:08 -07002594 fout.print("System ready: "); fout.println(mSystemReady);
2595 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2596 fout.print("Restrict power: "); fout.println(mRestrictPower);
2597 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2598 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002599 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002600 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2601 fout.println(mNetworkPolicy.valueAt(i).toString());
2602 }
2603 fout.decreaseIndent();
2604
2605 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2606
2607 fout.println("Policy for UIDs:");
2608 fout.increaseIndent();
2609 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002610 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002611 final int uid = mUidPolicy.keyAt(i);
2612 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002613 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002614 fout.print(uid);
2615 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002616 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002617 fout.println();
2618 }
2619 fout.decreaseIndent();
2620
2621 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2622 if (size > 0) {
2623 fout.println("Power save whitelist (except idle) app ids:");
2624 fout.increaseIndent();
2625 for (int i = 0; i < size; i++) {
2626 fout.print("UID=");
2627 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2628 fout.print(": ");
2629 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2630 fout.println();
2631 }
2632 fout.decreaseIndent();
2633 }
2634
2635 size = mPowerSaveWhitelistAppIds.size();
2636 if (size > 0) {
2637 fout.println("Power save whitelist app ids:");
2638 fout.increaseIndent();
2639 for (int i = 0; i < size; i++) {
2640 fout.print("UID=");
2641 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2642 fout.print(": ");
2643 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2644 fout.println();
2645 }
2646 fout.decreaseIndent();
2647 }
2648
Felipe Lemef0823852016-06-08 13:43:08 -07002649 size = mDefaultRestrictBackgroundWhitelistUids.size();
2650 if (size > 0) {
2651 fout.println("Default restrict background whitelist uids:");
2652 fout.increaseIndent();
2653 for (int i = 0; i < size; i++) {
2654 fout.print("UID=");
2655 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2656 fout.println();
2657 }
2658 fout.decreaseIndent();
2659 }
2660
2661 size = mRestrictBackgroundWhitelistRevokedUids.size();
2662 if (size > 0) {
2663 fout.println("Default restrict background whitelist uids revoked by users:");
2664 fout.increaseIndent();
2665 for (int i = 0; i < size; i++) {
2666 fout.print("UID=");
2667 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2668 fout.println();
2669 }
2670 fout.decreaseIndent();
2671 }
2672
2673 final SparseBooleanArray knownUids = new SparseBooleanArray();
2674 collectKeys(mUidState, knownUids);
2675 collectKeys(mUidRules, knownUids);
2676
2677 fout.println("Status for all known UIDs:");
2678 fout.increaseIndent();
2679 size = knownUids.size();
2680 for (int i = 0; i < size; i++) {
2681 final int uid = knownUids.keyAt(i);
2682 fout.print("UID=");
2683 fout.print(uid);
2684
2685 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2686 fout.print(" state=");
2687 fout.print(state);
2688 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2689 fout.print(" (fg)");
2690 } else {
2691 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2692 ? " (fg svc)" : " (bg)");
2693 }
2694
2695 final int uidRules = mUidRules.get(uid, RULE_NONE);
2696 fout.print(" rules=");
2697 fout.print(uidRulesToString(uidRules));
2698 fout.println();
2699 }
2700 fout.decreaseIndent();
2701
2702 fout.println("Status for just UIDs with rules:");
2703 fout.increaseIndent();
2704 size = mUidRules.size();
2705 for (int i = 0; i < size; i++) {
2706 final int uid = mUidRules.keyAt(i);
2707 fout.print("UID=");
2708 fout.print(uid);
2709 final int uidRules = mUidRules.get(uid, RULE_NONE);
2710 fout.print(" rules=");
2711 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002712 fout.println();
2713 }
2714 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002715
2716 fout.println("Observed uid state changes:");
2717 fout.increaseIndent();
2718 mObservedHistory.dumpUL(fout);
2719 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002720 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002721 }
2722 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002723
2724 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002725 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002726 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002727 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002728 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002729 }
2730
2731 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002732 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002733 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2734
Felipe Lemef0823852016-06-08 13:43:08 -07002735 synchronized (mUidRulesFirstLock) {
2736 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002737 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002738 }
2739
Felipe Lemef0823852016-06-08 13:43:08 -07002740 private boolean isUidForegroundUL(int uid) {
2741 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002742 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2743 }
2744
Felipe Lemef0823852016-06-08 13:43:08 -07002745 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002746 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002747 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002748 }
2749
Felipe Lemef0823852016-06-08 13:43:08 -07002750 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002751 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2752 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2753 }
2754
Felipe Lemef0823852016-06-08 13:43:08 -07002755 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002756 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002757 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002758 }
2759
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002760 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002761 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002762 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2763 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002764 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002765 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002766 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2767 try {
2768 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2769 if (oldUidState != uidState) {
2770 // state changed, push updated rules
2771 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002772 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2773 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2774 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2775 if (isUidIdle(uid)) {
2776 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002777 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002778 if (mDeviceIdleMode) {
2779 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002780 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002781 if (mRestrictPower) {
2782 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002783 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002784 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002785 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002786 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002787 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002788 } finally {
2789 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002790 }
2791 }
2792
Felipe Lemef0823852016-06-08 13:43:08 -07002793 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002794 final int index = mUidState.indexOfKey(uid);
2795 if (index >= 0) {
2796 final int oldUidState = mUidState.valueAt(index);
2797 mUidState.removeAt(index);
2798 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002799 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002800 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002801 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002802 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002803 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002804 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002805 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002806 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002807 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002808 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002809 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002810 }
2811 }
2812
Felipe Lemef28983d2016-03-25 12:18:23 -07002813 // adjust stats accounting based on foreground status
2814 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002815 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2816 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2817 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2818 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002819 try {
2820 mNetworkStats.setUidForeground(uid, uidForeground);
2821 } catch (RemoteException e) {
2822 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002823 } finally {
2824 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002825 }
2826 }
2827
Sudheer Shankac9d94072017-02-22 22:13:55 +00002828 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2829 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002830 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002831 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002832 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002833 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002834 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002835 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002836 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002837 }
2838
Felipe Lemef0823852016-06-08 13:43:08 -07002839 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002840 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2841 try {
2842 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2843 mUidFirewallPowerSaveRules);
2844 } finally {
2845 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2846 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002847 }
2848
Felipe Lemef0823852016-06-08 13:43:08 -07002849 void updateRuleForRestrictPowerUL(int uid) {
2850 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002851 }
2852
Felipe Lemef0823852016-06-08 13:43:08 -07002853 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002854 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2855 try {
2856 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2857 mUidFirewallDozableRules);
2858 } finally {
2859 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2860 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002861 }
2862
Felipe Lemef0823852016-06-08 13:43:08 -07002863 void updateRuleForDeviceIdleUL(int uid) {
2864 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002865 }
2866
Felipe Lemef28983d2016-03-25 12:18:23 -07002867 // NOTE: since both fw_dozable and fw_powersave uses the same map
2868 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002869 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002870 SparseIntArray rules) {
2871 if (enabled) {
2872 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002873 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002874 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002875 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002876 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002877 for (int ui = users.size() - 1; ui >= 0; ui--) {
2878 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002879 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002880 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2881 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2882 int uid = UserHandle.getUid(user.id, appId);
2883 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2884 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002885 }
2886 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2887 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2888 int uid = UserHandle.getUid(user.id, appId);
2889 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2890 }
2891 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002892 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002893 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002894 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2895 }
2896 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002897 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2898 } else {
2899 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002900 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002901 }
2902
Felipe Lemef0823852016-06-08 13:43:08 -07002903 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002904 final int appId = UserHandle.getAppId(uid);
2905 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2906 }
2907
Felipe Lemef28983d2016-03-25 12:18:23 -07002908 // NOTE: since both fw_dozable and fw_powersave uses the same map
2909 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002910 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002911 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002912 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002913 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002914 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002915 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002916 }
2917 }
2918 }
2919
Felipe Lemef0823852016-06-08 13:43:08 -07002920 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002921 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2922 try {
2923 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2924 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002925
Felipe Leme873a83a2016-09-07 11:34:10 -07002926 // Fully update the app idle firewall chain.
2927 final List<UserInfo> users = mUserManager.getUsers();
2928 for (int ui = users.size() - 1; ui >= 0; ui--) {
2929 UserInfo user = users.get(ui);
2930 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2931 for (int uid : idleUids) {
2932 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2933 // quick check: if this uid doesn't have INTERNET permission, it
2934 // doesn't have network access anyway, so it is a waste to mess
2935 // with it here.
2936 if (hasInternetPermissions(uid)) {
2937 uidRules.put(uid, FIREWALL_RULE_DENY);
2938 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002939 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002940 }
2941 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002942
Felipe Lemebc853dd2016-09-08 13:26:55 -07002943 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002944 } finally {
2945 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2946 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002947 }
2948
Felipe Lemef0823852016-06-08 13:43:08 -07002949 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002950 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002951
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002952 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2953 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
2954 }
2955 try {
2956 int appId = UserHandle.getAppId(uid);
2957 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2958 && !isUidForegroundOnRestrictPowerUL(uid)) {
2959 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2960 } else {
2961 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2962 }
2963 } finally {
2964 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002965 }
2966 }
2967
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002968 /**
2969 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2970 * changed.
2971 */
Felipe Lemef0823852016-06-08 13:43:08 -07002972 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002973 boolean paroled = mUsageStats.isAppIdleParoleOn();
2974 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002975 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002976
2977 int ruleCount = mUidFirewallStandbyRules.size();
2978 for (int i = 0; i < ruleCount; i++) {
2979 int uid = mUidFirewallStandbyRules.keyAt(i);
2980 int oldRules = mUidRules.get(uid);
2981 if (enableChain) {
2982 // Chain wasn't enabled before and the other power-related
2983 // chains are whitelists, so we can clear the
2984 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2985 // the effective rules result in blocking network access.
2986 oldRules &= MASK_METERED_NETWORKS;
2987 } else {
2988 // Skip if it had no restrictions to begin with
2989 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2990 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002991 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002992 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002993 }
2994
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002995 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002996 * Update rules that might be changed by {@link #mRestrictBackground},
2997 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002998 */
Felipe Lemef0823852016-06-08 13:43:08 -07002999 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003000 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3001 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3002 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3003 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003004 try {
Felipe Leme09700462016-09-08 09:33:48 -07003005 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003006 updateRulesForRestrictPowerUL();
3007 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003008
Felipe Leme873a83a2016-09-07 11:34:10 -07003009 // If the set of restricted networks may have changed, re-evaluate those.
3010 if (restrictedNetworksChanged) {
3011 normalizePoliciesNL();
3012 updateNetworkRulesNL();
3013 }
3014 } finally {
3015 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003016 }
3017 }
3018
Felipe Leme09700462016-09-08 09:33:48 -07003019 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003020 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003021 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3022 try {
3023 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003024 updateRulesForPowerSaveUL();
3025 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3026 } finally {
3027 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3028 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003029 }
3030
Felipe Lemef0823852016-06-08 13:43:08 -07003031 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003032 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3033 try {
3034 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3035 } finally {
3036 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3037 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003038 }
3039
3040 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3041 private static final int TYPE_RESTRICT_POWER = 2;
3042 @Retention(RetentionPolicy.SOURCE)
3043 @IntDef(flag = false, value = {
3044 TYPE_RESTRICT_BACKGROUND,
3045 TYPE_RESTRICT_POWER,
3046 })
3047 public @interface RestrictType {
3048 }
3049
3050 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003051 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003052 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3053 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3054 }
3055 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003056 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003057
3058 final PackageManager pm = mContext.getPackageManager();
3059 final List<UserInfo> users;
3060 final List<ApplicationInfo> apps;
3061
3062 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3063 try {
3064 users = mUserManager.getUsers();
3065 } finally {
3066 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3067 }
3068 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3069 try {
3070 apps = pm.getInstalledApplications(
3071 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3072 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3073 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3074 } finally {
3075 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3076 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003077
Felipe Leme873a83a2016-09-07 11:34:10 -07003078 final int usersSize = users.size();
3079 final int appsSize = apps.size();
3080 for (int i = 0; i < usersSize; i++) {
3081 final UserInfo user = users.get(i);
3082 for (int j = 0; j < appsSize; j++) {
3083 final ApplicationInfo app = apps.get(j);
3084 final int uid = UserHandle.getUid(user.id, app.uid);
3085 switch (type) {
3086 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003087 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003088 break;
3089 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003090 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003091 break;
3092 default:
3093 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3094 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003095 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003096 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003097 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003098 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003099 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003100 }
3101
Felipe Lemef0823852016-06-08 13:43:08 -07003102 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003103 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003104 for (int i = 0; i < users.size(); i++) {
3105 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003106 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003107 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003108 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003109 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003110 updateRuleForAppIdleUL(uid);
3111 updateRuleForDeviceIdleUL(uid);
3112 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003113 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003114 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003115 }
3116 }
3117 }
3118
Felipe Leme70c57c22016-03-29 10:45:13 -07003119 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3120 // methods below could be merged into a isUidValidForRules() method.
3121 private boolean isUidValidForBlacklistRules(int uid) {
3122 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003123 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003124 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003125 return true;
3126 }
3127
3128 return false;
3129 }
3130
Felipe Leme70c57c22016-03-29 10:45:13 -07003131 private boolean isUidValidForWhitelistRules(int uid) {
3132 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3133 }
3134
Amith Yamasani15e472352015-04-24 19:06:07 -07003135 private boolean isUidIdle(int uid) {
3136 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3137 final int userId = UserHandle.getUserId(uid);
3138
songjinshi0655edd2016-05-18 19:55:32 +08003139 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003140 for (String packageName : packages) {
3141 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3142 return false;
3143 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003144 }
3145 }
3146 return true;
3147 }
3148
3149 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003150 * Checks if an uid has INTERNET permissions.
3151 * <p>
3152 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003153 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003154 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003155 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003156 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003157 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003158 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003159 }
3160 } catch (RemoteException e) {
3161 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003162 return true;
3163 }
3164
3165 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003166 * Clears all state - internal and external - associated with an UID.
3167 */
3168 private void onUidDeletedUL(int uid) {
3169 // First cleanup in-memory state synchronously...
3170 mUidRules.delete(uid);
3171 mUidPolicy.delete(uid);
3172 mUidFirewallStandbyRules.delete(uid);
3173 mUidFirewallDozableRules.delete(uid);
3174 mUidFirewallPowerSaveRules.delete(uid);
3175 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3176 mPowerSaveWhitelistAppIds.delete(uid);
3177 mPowerSaveTempWhitelistAppIds.delete(uid);
3178
3179 // ...then update iptables asynchronously.
3180 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3181 }
3182
3183 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003184 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003185 *
Felipe Leme781ba142016-05-09 16:24:48 -07003186 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003187 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003188 * <li>Doze mode
3189 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003190 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003191 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003192 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003193 *
3194 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003195 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003196 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003197 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003198 updateRuleForDeviceIdleUL(uid);
3199 updateRuleForAppIdleUL(uid);
3200 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003201
3202 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003203 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003204
3205 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003206 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003207 }
3208
Felipe Leme70c57c22016-03-29 10:45:13 -07003209 /**
3210 * Applies network rules to bandwidth controllers based on process state and user-defined
3211 * restrictions (blacklist / whitelist).
3212 *
3213 * <p>
3214 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3215 * networks:
3216 * <ul>
3217 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3218 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3219 * also blacklisted.
3220 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3221 * no UIDs other those whitelisted will have access.
3222 * <ul>
3223 *
3224 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3225 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3226 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3227 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003228 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003229 * {@link INetworkManagementService}, but this method should also be called in events (like
3230 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3231 * following rules should also be applied:
3232 *
3233 * <ul>
3234 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3235 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3236 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3237 * {@code bw_penalty_box}.
3238 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3239 * </ul>
3240 *
3241 * <p>For optimization, the rules are only applied on user apps that have internet access
3242 * permission, since there is no need to change the {@code iptables} rule if the app does not
3243 * have permission to use the internet.
3244 *
3245 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003246 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003247 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003248 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003249 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3250 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3251 "updateRulesForDataUsageRestrictionsUL: " + uid);
3252 }
3253 try {
3254 updateRulesForDataUsageRestrictionsULInner(uid);
3255 } finally {
3256 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3257 }
3258 }
3259
3260 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003261 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003262 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003263 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003264 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003265
Dianne Hackborn497175b2014-07-01 12:56:08 -07003266 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003267 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003268 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003269
Felipe Leme781ba142016-05-09 16:24:48 -07003270 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003271 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003272 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3273 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003274
Felipe Leme70c57c22016-03-29 10:45:13 -07003275 // First step: define the new rule based on user restrictions and foreground state.
3276 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003277 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3278 newRule = RULE_TEMPORARY_ALLOW_METERED;
3279 } else if (isWhitelisted) {
3280 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003281 }
3282 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003283 if (isBlacklisted) {
3284 newRule = RULE_REJECT_METERED;
3285 } else if (mRestrictBackground && isWhitelisted) {
3286 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003287 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003288 }
Felipe Leme781ba142016-05-09 16:24:48 -07003289 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003290
Felipe Lemef28983d2016-03-25 12:18:23 -07003291 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003292 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003293 + ": isForeground=" +isForeground
3294 + ", isBlacklisted=" + isBlacklisted
3295 + ", isWhitelisted=" + isWhitelisted
3296 + ", oldRule=" + uidRulesToString(oldRule)
3297 + ", newRule=" + uidRulesToString(newRule)
3298 + ", newUidRules=" + uidRulesToString(newUidRules)
3299 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003300 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003301
Felipe Leme46c4fc32016-05-04 09:21:43 -07003302 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003303 mUidRules.delete(uid);
3304 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003305 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003306 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003307
Felipe Leme70c57c22016-03-29 10:45:13 -07003308 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003309 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003310 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003311 // Temporarily whitelist foreground app, removing from blacklist if necessary
3312 // (since bw_penalty_box prevails over bw_happy_box).
3313
3314 setMeteredNetworkWhitelist(uid, true);
3315 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3316 // but ideally it should be just:
3317 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003318 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003319 setMeteredNetworkBlacklist(uid, false);
3320 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003321 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003322 // Remove temporary whitelist from app that is not on foreground anymore.
3323
3324 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3325 // but ideally they should be just:
3326 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3327 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003328 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003329 setMeteredNetworkWhitelist(uid, false);
3330 }
Felipe Leme781ba142016-05-09 16:24:48 -07003331 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003332 setMeteredNetworkBlacklist(uid, true);
3333 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003334 } else if (hasRule(newRule, RULE_REJECT_METERED)
3335 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003336 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003337 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003338 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003339 // Since blacklist prevails over whitelist, we need to handle the special case
3340 // where app is whitelisted and blacklisted at the same time (although such
3341 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003342 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003343 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003344 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3345 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003346 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003347 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003348 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003349 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003350 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3351 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003352 + ", whitelisted=" + isWhitelisted
3353 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003354 + ", newRule=" + uidRulesToString(newUidRules)
3355 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003356 }
Felipe Leme781ba142016-05-09 16:24:48 -07003357
Sudheer Shankac9d94072017-02-22 22:13:55 +00003358 // Dispatch changed rule to existing listeners.
3359 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003360 }
3361 }
3362
3363 /**
3364 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3365 * listeners in case of change.
3366 * <p>
3367 * There are 3 power-related rules that affects whether an app has background access on
3368 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3369 * restriction, it's added to the equivalent firewall chain:
3370 * <ul>
3371 * <li>App is idle: {@code fw_standby} firewall chain.
3372 * <li>Device is idle: {@code fw_dozable} firewall chain.
3373 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3374 * </ul>
3375 * <p>
3376 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3377 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3378 * <p>
3379 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3380 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003381 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003382 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3383
Sudheer Shankac9d94072017-02-22 22:13:55 +00003384 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003385
Sudheer Shankac9d94072017-02-22 22:13:55 +00003386 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003387 mUidRules.delete(uid);
3388 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003389 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003390 }
3391 }
3392
3393 /**
3394 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3395 *
3396 * @param uid the uid of the app to update rules for
3397 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3398 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3399 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003400 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003401 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003402 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003403 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3404 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3405 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3406 + (paroled ? "P" : "-"));
3407 }
3408 try {
3409 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3410 } finally {
3411 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3412 }
3413 }
3414
3415 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003416 if (!isUidValidForBlacklistRules(uid)) {
3417 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003418 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003419 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003420
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003421 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003422 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003423 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003424
Felipe Lemef0823852016-06-08 13:43:08 -07003425 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003426 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3427 int newRule = RULE_NONE;
3428
3429 // First step: define the new rule based on user restrictions and foreground state.
3430
3431 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3432 // by considering the foreground and non-foreground states.
3433 if (isForeground) {
3434 if (restrictMode) {
3435 newRule = RULE_ALLOW_ALL;
3436 }
3437 } else if (restrictMode) {
3438 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3439 }
3440
3441 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3442
3443 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003444 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003445 + ", isIdle: " + isIdle
3446 + ", mRestrictPower: " + mRestrictPower
3447 + ", mDeviceIdleMode: " + mDeviceIdleMode
3448 + ", isForeground=" + isForeground
3449 + ", isWhitelisted=" + isWhitelisted
3450 + ", oldRule=" + uidRulesToString(oldRule)
3451 + ", newRule=" + uidRulesToString(newRule)
3452 + ", newUidRules=" + uidRulesToString(newUidRules)
3453 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3454 }
3455
Felipe Leme781ba142016-05-09 16:24:48 -07003456 // Second step: notify listeners if state changed.
3457 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003458 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003459 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003460 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003461 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3462 } else {
3463 // All scenarios should have been covered above
3464 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3465 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003466 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003467 + ", newRule=" + uidRulesToString(newUidRules)
3468 + ", oldRule=" + uidRulesToString(oldUidRules));
3469 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003470 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003471 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003472
Sudheer Shankac9d94072017-02-22 22:13:55 +00003473 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003474 }
3475
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003476 private class AppIdleStateChangeListener
3477 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3478
3479 @Override
3480 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3481 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003482 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3483 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003484 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003485 synchronized (mUidRulesFirstLock) {
3486 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003487 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003488 }
3489 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003490 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003491 }
3492
3493 @Override
3494 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003495 synchronized (mUidRulesFirstLock) {
3496 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003497 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003498 }
3499 }
3500
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003501 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3502 if (listener != null) {
3503 try {
3504 listener.onUidRulesChanged(uid, uidRules);
3505 } catch (RemoteException ignored) {
3506 }
3507 }
3508 }
3509
3510 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3511 String[] meteredIfaces) {
3512 if (listener != null) {
3513 try {
3514 listener.onMeteredIfacesChanged(meteredIfaces);
3515 } catch (RemoteException ignored) {
3516 }
3517 }
3518 }
3519
3520 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3521 boolean restrictBackground) {
3522 if (listener != null) {
3523 try {
3524 listener.onRestrictBackgroundChanged(restrictBackground);
3525 } catch (RemoteException ignored) {
3526 }
3527 }
3528 }
3529
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003530 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3531 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003532 if (listener != null) {
3533 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003534 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003535 } catch (RemoteException ignored) {
3536 }
3537 }
3538 }
3539
Makoto Onuki8e777332017-03-28 11:25:47 -07003540 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003541 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003542 public boolean handleMessage(Message msg) {
3543 switch (msg.what) {
3544 case MSG_RULES_CHANGED: {
3545 final int uid = msg.arg1;
3546 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003547 final int length = mListeners.beginBroadcast();
3548 for (int i = 0; i < length; i++) {
3549 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3550 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003551 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003552 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003553 return true;
3554 }
3555 case MSG_METERED_IFACES_CHANGED: {
3556 final String[] meteredIfaces = (String[]) msg.obj;
3557 final int length = mListeners.beginBroadcast();
3558 for (int i = 0; i < length; i++) {
3559 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003560 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003561 }
3562 mListeners.finishBroadcast();
3563 return true;
3564 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003565 case MSG_LIMIT_REACHED: {
3566 final String iface = (String) msg.obj;
3567
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003568 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003569 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003570 if (mMeteredIfaces.contains(iface)) {
3571 try {
3572 // force stats update to make sure we have
3573 // numbers that caused alert to trigger.
3574 mNetworkStats.forceUpdate();
3575 } catch (RemoteException e) {
3576 // ignored; service lives in system_server
3577 }
3578
Felipe Lemef0823852016-06-08 13:43:08 -07003579 updateNetworkEnabledNL();
3580 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003581 }
3582 }
3583 return true;
3584 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003585 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3586 final boolean restrictBackground = msg.arg1 != 0;
3587 final int length = mListeners.beginBroadcast();
3588 for (int i = 0; i < length; i++) {
3589 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003590 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003591 }
3592 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003593 final Intent intent =
3594 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3595 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3596 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3597 return true;
3598 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003599 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003600 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003601 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003602 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003603 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003604 final int length = mListeners.beginBroadcast();
3605 for (int i = 0; i < length; i++) {
3606 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003607 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003608 }
3609 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003610 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3611 if (notifyApp.booleanValue()) {
3612 broadcastRestrictBackgroundChanged(uid, notifyApp);
3613 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003614 return true;
3615 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003616 case MSG_ADVISE_PERSIST_THRESHOLD: {
3617 final long lowestRule = (Long) msg.obj;
3618 try {
3619 // make sure stats are recorded frequently enough; we aim
3620 // for 2MB threshold for 2GB/month rules.
3621 final long persistThreshold = lowestRule / 1000;
3622 mNetworkStats.advisePersistThreshold(persistThreshold);
3623 } catch (RemoteException e) {
3624 // ignored; service lives in system_server
3625 }
3626 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003627 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003628 case MSG_UPDATE_INTERFACE_QUOTA: {
3629 removeInterfaceQuota((String) msg.obj);
3630 // int params need to be stitched back into a long
3631 setInterfaceQuota((String) msg.obj,
3632 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3633 return true;
3634 }
3635 case MSG_REMOVE_INTERFACE_QUOTA: {
3636 removeInterfaceQuota((String) msg.obj);
3637 return true;
3638 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003639 case MSG_SET_FIREWALL_RULES: {
3640 final int chain = msg.arg1;
3641 final int toggle = msg.arg2;
3642 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3643 if (uidRules != null) {
3644 setUidFirewallRules(chain, uidRules);
3645 }
3646 if (toggle != CHAIN_TOGGLE_NONE) {
3647 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3648 }
3649 return true;
3650 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003651 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3652 resetUidFirewallRules(msg.arg1);
3653 return true;
3654 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003655 default: {
3656 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003657 }
3658 }
3659 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003660 };
3661
3662 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3663 @Override
3664 public boolean handleMessage(Message msg) {
3665 switch (msg.what) {
3666 case UID_MSG_STATE_CHANGED: {
3667 final int uid = msg.arg1;
3668 final int procState = msg.arg2;
3669 final long procStateSeq = (Long) msg.obj;
3670
3671 handleUidChanged(uid, procState, procStateSeq);
3672 return true;
3673 }
3674 case UID_MSG_GONE: {
3675 final int uid = msg.arg1;
3676 handleUidGone(uid);
3677 return true;
3678 }
3679 default: {
3680 return false;
3681 }
3682 }
3683 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003684
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003685 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003686
Makoto Onuki8e777332017-03-28 11:25:47 -07003687 void handleUidChanged(int uid, int procState, long procStateSeq) {
3688 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3689 try {
3690 synchronized (mUidRulesFirstLock) {
3691 // We received a uid state change callback, add it to the history so that it
3692 // will be useful for debugging.
3693 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3694 // Now update the network policy rules as per the updated uid state.
3695 updateUidStateUL(uid, procState);
3696 // Updating the network rules is done, so notify AMS about this.
3697 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3698 }
3699 } finally {
3700 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3701 }
3702 }
3703
3704 void handleUidGone(int uid) {
3705 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3706 try {
3707 synchronized (mUidRulesFirstLock) {
3708 removeUidStateUL(uid);
3709 }
3710 } finally {
3711 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3712 }
3713 }
3714
Felipe Leme57e3d312016-08-23 14:42:52 -07003715 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3716 final PackageManager pm = mContext.getPackageManager();
3717 final String[] packages = pm.getPackagesForUid(uid);
3718 if (packages != null) {
3719 final int userId = UserHandle.getUserId(uid);
3720 for (String packageName : packages) {
3721 final Intent intent =
3722 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3723 intent.setPackage(packageName);
3724 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3725 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3726 }
3727 }
3728 }
3729
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003730 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003731 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003732 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003733 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003734 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003735 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003736 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003737 }
3738 }
3739
3740 private void removeInterfaceQuota(String iface) {
3741 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003742 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003743 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003744 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003745 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003746 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003747 }
3748 }
3749
Felipe Leme70c57c22016-03-29 10:45:13 -07003750 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3751 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003752 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003753 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003754 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003755 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3756 } catch (RemoteException e) {
3757 // ignored; service lives in system_server
3758 }
3759 }
3760
3761 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3762 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3763 try {
3764 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3765 } catch (IllegalStateException e) {
3766 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003767 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003768 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003769 }
3770 }
3771
Felipe Lemebc853dd2016-09-08 13:26:55 -07003772 private static final int CHAIN_TOGGLE_NONE = 0;
3773 private static final int CHAIN_TOGGLE_ENABLE = 1;
3774 private static final int CHAIN_TOGGLE_DISABLE = 2;
3775 @Retention(RetentionPolicy.SOURCE)
3776 @IntDef(flag = false, value = {
3777 CHAIN_TOGGLE_NONE,
3778 CHAIN_TOGGLE_ENABLE,
3779 CHAIN_TOGGLE_DISABLE
3780 })
3781 public @interface ChainToggleType {
3782 }
3783
3784 /**
3785 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3786 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3787 *
3788 * @param chain firewall chain.
3789 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3790 * @param toggle whether the chain should be enabled, disabled, or not changed.
3791 */
3792 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3793 @ChainToggleType int toggle) {
3794 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3795 }
3796
Amith Yamasani15e472352015-04-24 19:06:07 -07003797 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003798 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3799 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3800 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003801 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003802 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003803 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003804 int size = uidRules.size();
3805 int[] uids = new int[size];
3806 int[] rules = new int[size];
3807 for(int index = size - 1; index >= 0; --index) {
3808 uids[index] = uidRules.keyAt(index);
3809 rules[index] = uidRules.valueAt(index);
3810 }
3811 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003812 } catch (IllegalStateException e) {
3813 Log.wtf(TAG, "problem setting firewall uid rules", e);
3814 } catch (RemoteException e) {
3815 // ignored; service lives in system_server
3816 }
3817 }
3818
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003819 /**
3820 * Add or remove a uid to the firewall blacklist for all network ifaces.
3821 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003822 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003823 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3824 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3825 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003826 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003827 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003828 if (chain == FIREWALL_CHAIN_DOZABLE) {
3829 mUidFirewallDozableRules.put(uid, rule);
3830 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3831 mUidFirewallStandbyRules.put(uid, rule);
3832 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3833 mUidFirewallPowerSaveRules.put(uid, rule);
3834 }
3835
3836 try {
3837 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3838 } catch (IllegalStateException e) {
3839 Log.wtf(TAG, "problem setting firewall uid rules", e);
3840 } catch (RemoteException e) {
3841 // ignored; service lives in system_server
3842 }
3843 } finally {
3844 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003845 }
3846 }
3847
3848 /**
3849 * Add or remove a uid to the firewall blacklist for all network ifaces.
3850 */
Felipe Lemef0823852016-06-08 13:43:08 -07003851 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003852 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3853 mFirewallChainStates.get(chain) == enable) {
3854 // All is the same, nothing to do.
3855 return;
3856 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003857 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003858 try {
3859 mNetworkManager.setFirewallChainEnabled(chain, enable);
3860 } catch (IllegalStateException e) {
3861 Log.wtf(TAG, "problem enable firewall chain", e);
3862 } catch (RemoteException e) {
3863 // ignored; service lives in system_server
3864 }
3865 }
3866
Felipe Leme03e95e22016-09-09 09:25:31 -07003867 /**
3868 * Resets all firewall rules associated with an UID.
3869 */
3870 private void resetUidFirewallRules(int uid) {
3871 try {
3872 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3873 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3874 mNetworkManager
3875 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3876 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3877 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3878 } catch (IllegalStateException e) {
3879 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3880 } catch (RemoteException e) {
3881 // ignored; service lives in system_server
3882 }
3883 }
3884
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003885 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3886 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003887 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003888 } catch (RuntimeException e) {
3889 Slog.w(TAG, "problem reading network stats: " + e);
3890 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003891 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003892 // ignored; service lives in system_server
3893 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003894 }
3895 }
3896
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003897 private boolean isBandwidthControlEnabled() {
3898 final long token = Binder.clearCallingIdentity();
3899 try {
3900 return mNetworkManager.isBandwidthControlEnabled();
3901 } catch (RemoteException e) {
3902 // ignored; service lives in system_server
3903 return false;
3904 } finally {
3905 Binder.restoreCallingIdentity(token);
3906 }
3907 }
3908
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003909 /**
3910 * Try refreshing {@link #mTime} when stale.
3911 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003912 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003913 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003914 mTime.forceRefresh();
3915 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003916 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003917
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003918 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003919 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3920 }
3921
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003922 private static Intent buildAllowBackgroundDataIntent() {
3923 return new Intent(ACTION_ALLOW_BACKGROUND);
3924 }
3925
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003926 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3927 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3928 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3929 return intent;
3930 }
3931
Wei Liu546cb772016-07-21 16:19:01 -07003932 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003933 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003934 intent.setComponent(ComponentName.unflattenFromString(
3935 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003936 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3937 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3938 return intent;
3939 }
3940
Wei Liu546cb772016-07-21 16:19:01 -07003941 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003942 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003943 intent.setComponent(ComponentName.unflattenFromString(
3944 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003945 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3946 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3947 return intent;
3948 }
3949
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003950 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003951 public void addIdleHandler(IdleHandler handler) {
3952 mHandler.getLooper().getQueue().addIdleHandler(handler);
3953 }
3954
jackqdyulei29c82ab2017-03-10 14:09:16 -08003955 @VisibleForTesting
3956 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
3957 mRestrictBackgroundPowerState = result;
3958
3959 boolean restrictBackground = result.batterySaverEnabled;
3960 boolean shouldInvokeRestrictBackground;
3961 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
3962 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
3963
3964 if (result.globalBatterySaverEnabled) {
3965 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
3966 // turn it on.
3967 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
3968 mRestrictBackgroundBeforeBsm = mRestrictBackground;
3969 localRestrictBgChangedInBsm = false;
3970 } else {
3971 // Try to restore the restrictBackground if it doesn't change in bsm
3972 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
3973 restrictBackground = mRestrictBackgroundBeforeBsm;
3974 }
3975
3976 if (shouldInvokeRestrictBackground) {
3977 setRestrictBackground(restrictBackground);
3978 }
3979
3980 // Change it at last so setRestrictBackground() won't affect this variable
3981 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
3982 }
3983
Jeff Sharkey1b861272011-05-22 00:34:52 -07003984 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3985 final int size = source.size();
3986 for (int i = 0; i < size; i++) {
3987 target.put(source.keyAt(i), true);
3988 }
3989 }
3990
Stuart Scottf1fb3972015-04-02 18:00:02 -07003991 @Override
3992 public void factoryReset(String subscriber) {
3993 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3994
Stuart Scotte3e314d2015-04-20 14:07:45 -07003995 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3996 return;
3997 }
3998
Stuart Scottf1fb3972015-04-02 18:00:02 -07003999 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004000 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004001 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4002 for (NetworkPolicy policy : policies) {
4003 if (policy.template.equals(template)) {
4004 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4005 policy.inferred = false;
4006 policy.clearSnooze();
4007 }
4008 }
4009 setNetworkPolicies(policies);
4010
4011 // Turn restrict background data off
4012 setRestrictBackground(false);
4013
Stuart Scotte3e314d2015-04-20 14:07:45 -07004014 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4015 // Remove app's "restrict background data" flag
4016 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4017 setUidPolicy(uid, POLICY_NONE);
4018 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004019 }
4020 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004021
Felipe Lemed17fda42016-04-29 11:12:45 -07004022 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4023
4024 @Override
4025 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004026 synchronized (mUidRulesFirstLock) {
4027 boolean changed = removeUserStateUL(userId, false);
4028 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004029 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004030 synchronized (mNetworkPoliciesSecondLock) {
4031 writePolicyAL();
4032 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004033 }
4034 }
4035 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004036
4037 /**
4038 * @return true if the given uid is restricted from doing networking on metered networks.
4039 */
4040 @Override
4041 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4042 final int uidRules;
4043 final boolean isBackgroundRestricted;
4044 synchronized (mUidRulesFirstLock) {
4045 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4046 isBackgroundRestricted = mRestrictBackground;
4047 }
4048 return isBackgroundRestricted
4049 && !hasRule(uidRules, RULE_ALLOW_METERED)
4050 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4051 }
4052
4053 /**
4054 * @return true if networking is blocked on the given interface for the given uid according
4055 * to current networking policies.
4056 */
4057 @Override
4058 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4059 final int uidRules;
4060 final boolean isBackgroundRestricted;
4061 final boolean isNetworkMetered;
4062 synchronized (mUidRulesFirstLock) {
4063 uidRules = mUidRules.get(uid, RULE_NONE);
4064 isBackgroundRestricted = mRestrictBackground;
4065 synchronized (mNetworkPoliciesSecondLock) {
4066 isNetworkMetered = mMeteredIfaces.contains(ifname);
4067 }
4068 }
4069 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4070 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4071 return true;
4072 }
4073 if (!isNetworkMetered) {
4074 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4075 return false;
4076 }
4077 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4078 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4079 return true;
4080 }
4081 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4082 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4083 return false;
4084 }
4085 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4086 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4087 return false;
4088 }
4089 if (isBackgroundRestricted) {
4090 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4091 return true;
4092 }
4093 if (LOGV) logUidStatus(uid, "allowed by default");
4094 return false;
4095 }
4096 }
4097
4098 private static boolean hasRule(int uidRules, int rule) {
4099 return (uidRules & rule) != 0;
4100 }
4101
4102 private static void logUidStatus(int uid, String descr) {
4103 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004104 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004105
4106 /**
4107 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4108 * (uid, procStateSeq) pairs.
4109 */
4110 @VisibleForTesting
4111 public static final class ProcStateSeqHistory {
4112 private static final int INVALID_UID = -1;
4113
4114 /**
4115 * Denotes maximum number of items this history can hold.
4116 */
4117 private final int mMaxCapacity;
4118 /**
4119 * Used for storing the uid information.
4120 */
4121 private final int[] mUids;
4122 /**
4123 * Used for storing the sequence numbers associated with {@link #mUids}.
4124 */
4125 private final long[] mProcStateSeqs;
4126 /**
4127 * Points to the next available slot for writing (uid, procStateSeq) pair.
4128 */
4129 private int mHistoryNext;
4130
4131 public ProcStateSeqHistory(int maxCapacity) {
4132 mMaxCapacity = maxCapacity;
4133 mUids = new int[mMaxCapacity];
4134 Arrays.fill(mUids, INVALID_UID);
4135 mProcStateSeqs = new long[mMaxCapacity];
4136 }
4137
4138 @GuardedBy("mUidRulesFirstLock")
4139 public void addProcStateSeqUL(int uid, long procStateSeq) {
4140 mUids[mHistoryNext] = uid;
4141 mProcStateSeqs[mHistoryNext] = procStateSeq;
4142 mHistoryNext = increaseNext(mHistoryNext, 1);
4143 }
4144
4145 @GuardedBy("mUidRulesFirstLock")
4146 public void dumpUL(IndentingPrintWriter fout) {
4147 if (mUids[0] == INVALID_UID) {
4148 fout.println("NONE");
4149 return;
4150 }
4151 int index = mHistoryNext;
4152 do {
4153 index = increaseNext(index, -1);
4154 if (mUids[index] == INVALID_UID) {
4155 break;
4156 }
4157 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4158 } while (index != mHistoryNext);
4159 }
4160
4161 public static String getString(int uid, long procStateSeq) {
4162 return "UID=" + uid + " procStateSeq=" + procStateSeq;
4163 }
4164
4165 private int increaseNext(int next, int increment) {
4166 next += increment;
4167 if (next >= mMaxCapacity) {
4168 next = 0;
4169 } else if (next < 0) {
4170 next = mMaxCapacity - 1;
4171 }
4172 return next;
4173 }
4174 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004175
4176 private class NotificationId {
4177 private final String mTag;
4178 private final int mId;
4179
4180 NotificationId(NetworkPolicy policy, int type) {
4181 mTag = buildNotificationTag(policy, type);
4182 mId = type;
4183 }
4184
4185 @Override
4186 public boolean equals(Object o) {
4187 if (this == o) return true;
4188 if (!(o instanceof NotificationId)) return false;
4189 NotificationId that = (NotificationId) o;
4190 return Objects.equals(mTag, that.mTag);
4191 }
4192
4193 @Override
4194 public int hashCode() {
4195 return Objects.hash(mTag);
4196 }
4197
4198 /**
4199 * Build unique tag that identifies an active {@link NetworkPolicy}
4200 * notification of a specific type, like {@link #TYPE_LIMIT}.
4201 */
4202 private String buildNotificationTag(NetworkPolicy policy, int type) {
4203 return TAG + ":" + policy.template.hashCode() + ":" + type;
4204 }
4205
4206 public String getTag() {
4207 return mTag;
4208 }
4209
4210 public int getId() {
4211 return mId;
4212 }
4213 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004214}