blob: b6af07677d6166d5e706ddfbf2a37a600ce8afb4 [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() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700803 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700804 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
805 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700806 }
807
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700808 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700809 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700810 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700811
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700812 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700813 }
814
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700815 @Override public void onUidIdle(int uid, boolean disabled) {
816 }
817
818 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700819 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700820 };
821
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700822 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700823 @Override
824 public void onReceive(Context context, Intent intent) {
825 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700826 synchronized (mUidRulesFirstLock) {
827 updatePowerSaveWhitelistUL();
828 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700829 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700830 }
831 }
832 };
833
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700834 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
835 @Override
836 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700837 synchronized (mUidRulesFirstLock) {
838 updatePowerSaveTempWhitelistUL();
839 updateRulesForTempWhitelistChangeUL();
840 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700841 }
842 }
843 };
844
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700845 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700846 @Override
847 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700848 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700849
850 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700851 final int uid = intent.getIntExtra(EXTRA_UID, -1);
852 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700853
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700854 if (ACTION_PACKAGE_ADDED.equals(action)) {
855 // update rules for UID, since it might be subject to
856 // global background data policy
857 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700858 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700859 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700860 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700861 }
862 }
863 };
864
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700865 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700866 @Override
867 public void onReceive(Context context, Intent intent) {
868 // on background handler thread, and UID_REMOVED is protected
869
870 final int uid = intent.getIntExtra(EXTRA_UID, -1);
871 if (uid == -1) return;
872
873 // remove any policy and update rules to clean up
874 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700875 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700876 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700877 synchronized (mNetworkPoliciesSecondLock) {
878 writePolicyAL();
879 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700880 }
881 }
882 };
883
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700884 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700885 @Override
886 public void onReceive(Context context, Intent intent) {
887 // on background handler thread, and USER_ADDED and USER_REMOVED
888 // broadcasts are protected
889
890 final String action = intent.getAction();
891 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
892 if (userId == -1) return;
893
Amith Yamasani15e472352015-04-24 19:06:07 -0700894 switch (action) {
895 case ACTION_USER_REMOVED:
896 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700897 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800898 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700899 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700900 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700901 if (action == ACTION_USER_ADDED) {
902 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700903 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700904 }
905 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700906 synchronized (mNetworkPoliciesSecondLock) {
907 updateRulesForGlobalChangeAL(true);
908 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700909 }
910 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700911 }
912 }
913 };
914
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700915 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700916 * Receiver that watches for {@link INetworkStatsService} updates, which we
917 * use to check against {@link NetworkPolicy#warningBytes}.
918 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700919 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700920 @Override
921 public void onReceive(Context context, Intent intent) {
922 // on background handler thread, and verified
923 // READ_NETWORK_USAGE_HISTORY permission above.
924
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800925 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700926 synchronized (mNetworkPoliciesSecondLock) {
927 updateNetworkEnabledNL();
928 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700929 }
930 }
931 };
932
933 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700934 * Receiver that watches for {@link Notification} control of
935 * {@link #mRestrictBackground}.
936 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700937 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700938 @Override
939 public void onReceive(Context context, Intent intent) {
940 // on background handler thread, and verified MANAGE_NETWORK_POLICY
941 // permission above.
942
943 setRestrictBackground(false);
944 }
945 };
946
947 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800948 * Receiver that watches for {@link Notification} control of
949 * {@link NetworkPolicy#lastWarningSnooze}.
950 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700951 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800952 @Override
953 public void onReceive(Context context, Intent intent) {
954 // on background handler thread, and verified MANAGE_NETWORK_POLICY
955 // permission above.
956
957 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
958 performSnooze(template, TYPE_WARNING);
959 }
960 };
961
962 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700963 * Receiver that watches for {@link WifiConfiguration} to be changed.
964 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700965 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700966 @Override
967 public void onReceive(Context context, Intent intent) {
968 // on background handler thread, and verified CONNECTIVITY_INTERNAL
969 // permission above.
970
971 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
972 if (reason == CHANGE_REASON_REMOVED) {
973 final WifiConfiguration config = intent.getParcelableExtra(
974 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700975 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800976 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700977 synchronized (mUidRulesFirstLock) {
978 synchronized (mNetworkPoliciesSecondLock) {
979 if (mNetworkPolicy.containsKey(template)) {
980 mNetworkPolicy.remove(template);
981 writePolicyAL();
982 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700983 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700984 }
985 }
986 }
987 }
988 };
989
990 /**
991 * Receiver that watches {@link WifiInfo} state changes to infer metered
992 * state. Ignores hints when policy is user-defined.
993 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700994 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700995 @Override
996 public void onReceive(Context context, Intent intent) {
997 // on background handler thread, and verified CONNECTIVITY_INTERNAL
998 // permission above.
999
1000 // ignore when not connected
1001 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
1002 if (!netInfo.isConnected()) return;
1003
1004 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
1005 final boolean meteredHint = info.getMeteredHint();
1006
Jeff Sharkey2e4dce02012-12-18 17:06:06 -08001007 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Hugo Benichi446c9c92017-04-10 09:41:10 +09001008 synchronized (mUidRulesFirstLock) {
1009 synchronized (mNetworkPoliciesSecondLock) {
1010 NetworkPolicy policy = mNetworkPolicy.get(template);
1011 if (policy == null && meteredHint) {
1012 // policy doesn't exist, and AP is hinting that it's
1013 // metered: create an inferred policy.
1014 policy = newWifiPolicy(template, meteredHint);
1015 addNetworkPolicyAL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001016
Hugo Benichi446c9c92017-04-10 09:41:10 +09001017 } else if (policy != null && policy.inferred) {
1018 // policy exists, and was inferred: update its current
1019 // metered state.
1020 policy.metered = meteredHint;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001021
Hugo Benichi446c9c92017-04-10 09:41:10 +09001022 // since this is inferred for each wifi session, just update
1023 // rules without persisting.
1024 updateNetworkRulesNL();
1025 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001026 }
1027 }
1028 }
1029 };
1030
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08001031 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
1032 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
1033 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
1034 metered, true);
1035 }
1036
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001037 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001038 * Observer that watches for {@link INetworkManagementService} alerts.
1039 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001040 final private INetworkManagementEventObserver mAlertObserver
1041 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001042 @Override
1043 public void limitReached(String limitName, String iface) {
1044 // only someone like NMS should be calling us
1045 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1046
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001047 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1048 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001049 }
1050 }
1051 };
1052
1053 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001054 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1055 * to show visible notifications as needed.
1056 */
Felipe Lemef0823852016-06-08 13:43:08 -07001057 void updateNotificationsNL() {
1058 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001059
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001061 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063
1064 // TODO: when switching to kernel notifications, compute next future
1065 // cycle boundary to recompute notifications.
1066
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001067 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001068 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001069 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1070 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001071 // ignore policies that aren't relevant to user
1072 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001073 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001074
Jeff Sharkey497e4432011-06-14 17:27:29 -07001075 final long start = computeLastCycleBoundary(currentTime, policy);
1076 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001077 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001078
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001079 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001080 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1082 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001083 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001084 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001085 }
1086
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001088 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001090 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001091 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001092 }
1093 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001094 }
1095
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001096 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001097 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001098 final NotificationId notificationId = beforeNotifs.valueAt(i);
1099 if (!mActiveNotifs.contains(notificationId)) {
1100 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001101 }
1102 }
1103 }
1104
1105 /**
1106 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001107 * current device state, such as when
1108 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1109 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001110 */
1111 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001112 if (template.isMatchRuleMobile()) {
1113 final TelephonyManager tele = TelephonyManager.from(mContext);
1114 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001115
Jeff Sharkey32566012014-12-02 18:30:14 -08001116 // Mobile template is relevant when any active subscriber matches
1117 final int[] subIds = sub.getActiveSubscriptionIdList();
1118 for (int subId : subIds) {
1119 final String subscriberId = tele.getSubscriberId(subId);
1120 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001121 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001122 if (template.matches(probeIdent)) {
1123 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001124 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001125 }
1126 return false;
1127 } else {
1128 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001129 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001130 }
1131
1132 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001133 * Notify that given {@link NetworkTemplate} is over
1134 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1135 */
Felipe Lemef0823852016-06-08 13:43:08 -07001136 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001138 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001139 mOverLimitNotified.add(template);
1140 }
1141 }
1142
Felipe Lemef0823852016-06-08 13:43:08 -07001143 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001144 mOverLimitNotified.remove(template);
1145 }
1146
1147 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 * Show notification for combined {@link NetworkPolicy} and specific type,
1149 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1150 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001151 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001152 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001153 final Notification.Builder builder =
1154 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001155 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001156 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001157 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001158 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001159
1160 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001161 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001162 switch (type) {
1163 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001164 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001165 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001166
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001167 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 builder.setTicker(title);
1169 builder.setContentTitle(title);
1170 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001171 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001172 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001173
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001174 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1175 builder.setDeleteIntent(PendingIntent.getBroadcast(
1176 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1177
Wei Liu546cb772016-07-21 16:19:01 -07001178 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001179 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001180 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1181
Jeff Sharkey497e4432011-06-14 17:27:29 -07001182 break;
1183 }
1184 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001185 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001186
1187 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001188 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001189 switch (policy.template.getMatchRule()) {
1190 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001191 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001193 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001194 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001195 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001196 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001197 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001198 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001199 case MATCH_WIFI:
1200 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001201 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001202 break;
1203 default:
1204 title = null;
1205 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 }
1207
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001208 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001209 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001210 builder.setTicker(title);
1211 builder.setContentTitle(title);
1212 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001213
Wei Liu546cb772016-07-21 16:19:01 -07001214 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001215 builder.setContentIntent(PendingIntent.getActivity(
1216 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1217 break;
1218 }
1219 case TYPE_LIMIT_SNOOZED: {
1220 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001221 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001222 Formatter.formatFileSize(mContext, overBytes));
1223
1224 final CharSequence title;
1225 switch (policy.template.getMatchRule()) {
1226 case MATCH_MOBILE_3G_LOWER:
1227 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1228 break;
1229 case MATCH_MOBILE_4G:
1230 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1231 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001232 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001233 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1234 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001235 case MATCH_WIFI:
1236 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1237 break;
1238 default:
1239 title = null;
1240 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001241 }
1242
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001243 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001244 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001245 builder.setTicker(title);
1246 builder.setContentTitle(title);
1247 builder.setContentText(body);
1248
Wei Liu546cb772016-07-21 16:19:01 -07001249 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001250 builder.setContentIntent(PendingIntent.getActivity(
1251 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001252 break;
1253 }
1254 }
1255
1256 // TODO: move to NotificationManager once we can mock it
1257 try {
1258 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001259 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001260 builder.setStyle(new Notification.BigTextStyle()
1261 .bigText(body));
1262 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001263 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001264 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001265 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001266 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001267 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001268 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001269 }
1270 }
1271
Chris Wren193ae6b2017-03-31 15:17:11 -04001272 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001273 // TODO: move to NotificationManager once we can mock it
1274 try {
1275 final String packageName = mContext.getPackageName();
1276 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001277 packageName, notificationId.getTag(), notificationId.getId(),
1278 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001279 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001280 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001281 }
1282 }
1283
1284 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001285 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001286 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001287 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001288 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 @Override
1290 public void onReceive(Context context, Intent intent) {
1291 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1292 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001293
1294 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001295 synchronized (mUidRulesFirstLock) {
1296 synchronized (mNetworkPoliciesSecondLock) {
1297 ensureActiveMobilePolicyAL();
1298 normalizePoliciesNL();
1299 updateNetworkEnabledNL();
1300 updateNetworkRulesNL();
1301 updateNotificationsNL();
1302 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001303 }
1304 }
1305 };
1306
1307 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001308 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1309 * if necessary.
1310 *
1311 * @param subId that has its associated NetworkPolicy updated if necessary
1312 * @return if any policies were updated
1313 */
1314 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1315 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1316 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1317
1318 if (config == null) {
1319 return false;
1320 }
1321
1322 boolean policyUpdated = false;
1323 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1324
1325 // find and update the mobile NetworkPolicy for this subscriber id
1326 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1327 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1328 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1329 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1330 if (template.matches(probeIdent)) {
1331 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1332
1333 // only update the policy if the user didn't change any of the defaults.
1334 if (!policy.inferred) {
1335 // TODO: inferred could be split, so that if a user changes their data limit or
1336 // warning, it doesn't prevent their cycle date from being updated.
1337 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1338 continue;
1339 }
1340
1341 final int cycleDay = getCycleDayFromCarrierConfig(config, policy.cycleDay);
1342 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1343 policy.warningBytes);
1344 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1345 policy.limitBytes);
1346
1347 if (policy.cycleDay == cycleDay &&
1348 policy.warningBytes == warningBytes &&
1349 policy.limitBytes == limitBytes) {
1350 continue;
1351 }
1352
1353 policyUpdated = true;
1354 policy.cycleDay = cycleDay;
1355 policy.warningBytes = warningBytes;
1356 policy.limitBytes = limitBytes;
1357
1358 if (LOGD) {
1359 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1360 + NetworkIdentity.scrubSubscriberId(subscriberId)
1361 + " from CarrierConfigManager");
1362 }
1363 }
1364 }
1365
1366 return policyUpdated;
1367 }
1368
1369 /**
1370 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1371 *
1372 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1373 * to do so, it returns the fallback value.
1374 *
1375 * @param config The CarrierConfig to read the value from.
1376 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1377 * @return cycleDay to use in the mobile NetworkPolicy.
1378 */
1379 @VisibleForTesting
1380 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1381 int fallbackCycleDay) {
1382 if (config == null) {
1383 return fallbackCycleDay;
1384 }
1385 int cycleDay =
1386 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1387 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1388 return fallbackCycleDay;
1389 }
1390 // validate cycleDay value
1391 final Calendar cal = Calendar.getInstance();
1392 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1393 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1394 Slog.e(TAG, "Invalid date in "
1395 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1396 return fallbackCycleDay;
1397 }
1398 return cycleDay;
1399 }
1400
1401 /**
1402 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1403 *
1404 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1405 * to do so, it returns the fallback value.
1406 *
1407 * @param config The CarrierConfig to read the value from.
1408 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1409 * @return warningBytes to use in the mobile NetworkPolicy.
1410 */
1411 @VisibleForTesting
1412 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1413 long fallbackWarningBytes) {
1414 if (config == null) {
1415 return fallbackWarningBytes;
1416 }
1417 long warningBytes =
1418 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1419
1420 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1421 return WARNING_DISABLED;
1422 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1423 return getPlatformDefaultWarningBytes();
1424 } else if (warningBytes < 0) {
1425 Slog.e(TAG, "Invalid value in "
1426 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1427 + "non-negative value but got: " + warningBytes);
1428 return fallbackWarningBytes;
1429 }
1430
1431 return warningBytes;
1432 }
1433
1434 /**
1435 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1436 *
1437 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1438 * to do so, it returns the fallback value.
1439 *
1440 * @param config The CarrierConfig to read the value from.
1441 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1442 * @return limitBytes to use in the mobile NetworkPolicy.
1443 */
1444 @VisibleForTesting
1445 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1446 long fallbackLimitBytes) {
1447 if (config == null) {
1448 return fallbackLimitBytes;
1449 }
1450 long limitBytes =
1451 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1452
1453 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1454 return LIMIT_DISABLED;
1455 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1456 return getPlatformDefaultLimitBytes();
1457 } else if (limitBytes < 0) {
1458 Slog.e(TAG, "Invalid value in "
1459 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1460 + "non-negative value but got: " + limitBytes);
1461 return fallbackLimitBytes;
1462 }
1463 return limitBytes;
1464 }
1465
1466 /**
1467 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1468 */
1469 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1470 @Override
1471 public void onReceive(Context context, Intent intent) {
1472 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1473 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1474
1475 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1476 return;
1477 }
1478 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1479 final TelephonyManager tele = TelephonyManager.from(mContext);
1480 final String subscriberId = tele.getSubscriberId(subId);
1481
1482 maybeRefreshTrustedTime();
1483 synchronized (mUidRulesFirstLock) {
1484 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001485 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001486 if (added) return;
1487 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1488 if (!updated) return;
1489 // update network and notification rules, as the data cycle changed and it's
1490 // possible that we should be triggering warnings/limits now
1491 handleNetworkPoliciesUpdateAL(true);
1492 }
1493 }
1494 }
1495 };
1496
1497 /**
1498 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1499 * one has been updated.
1500 *
1501 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1502 * update.
1503 */
1504 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1505 if (shouldNormalizePolicies) {
1506 normalizePoliciesNL();
1507 }
1508 updateNetworkEnabledNL();
1509 updateNetworkRulesNL();
1510 updateNotificationsNL();
1511 writePolicyAL();
1512 }
1513
1514 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001515 * Proactively control network data connections when they exceed
1516 * {@link NetworkPolicy#limitBytes}.
1517 */
Felipe Lemef0823852016-06-08 13:43:08 -07001518 void updateNetworkEnabledNL() {
1519 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001520
1521 // TODO: reset any policy-disabled networks when any policy is removed
1522 // completely, which is currently rare case.
1523
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001524 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001525 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1526 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001527 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001528 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001529 setNetworkTemplateEnabled(policy.template, true);
1530 continue;
1531 }
1532
1533 final long start = computeLastCycleBoundary(currentTime, policy);
1534 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001535 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001536
1537 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001538 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1539 && policy.lastLimitSnooze < start;
1540 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001541
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001542 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001543 }
1544 }
1545
1546 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001547 * Proactively disable networks that match the given
1548 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001549 */
1550 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001551 // TODO: reach into ConnectivityManager to proactively disable bringing
1552 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001553
1554 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1555 // If mobile data usage hits the limit or if the user resumes the data, we need to
1556 // notify telephony.
1557 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1558 final TelephonyManager tm = TelephonyManager.from(mContext);
1559
1560 final int[] subIds = sm.getActiveSubscriptionIdList();
1561 for (int subId : subIds) {
1562 final String subscriberId = tm.getSubscriberId(subId);
1563 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1564 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1565 // Template is matched when subscriber id matches.
1566 if (template.matches(probeIdent)) {
1567 tm.setPolicyDataEnabled(enabled, subId);
1568 }
1569 }
1570 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001571 }
1572
1573 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001574 * Examine all connected {@link NetworkState}, looking for
1575 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1576 * remaining quota based on usage cycle and historical stats.
1577 */
Felipe Lemef0823852016-06-08 13:43:08 -07001578 void updateNetworkRulesNL() {
1579 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001580
1581 final NetworkState[] states;
1582 try {
1583 states = mConnManager.getAllNetworkState();
1584 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001585 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 return;
1587 }
1588
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001589 // First, generate identities of all connected networks so we can
1590 // quickly compare them against all defined policies below.
1591 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001592 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001594 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001595 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001596
1597 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001598 if (baseIface != null) {
1599 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001600 }
1601
1602 // Stacked interfaces are considered to have same identity as
1603 // their parent network.
1604 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1605 for (LinkProperties stackedLink : stackedLinks) {
1606 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001607 if (stackedIface != null) {
1608 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001609 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001610 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 }
1612 }
1613
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001614 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001615 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001616 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001617 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001618 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001620 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001621 for (int j = connIdents.size() - 1; j >= 0; j--) {
1622 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1623 if (policy.template.matches(ident.second)) {
1624 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001625 }
1626 }
1627
1628 if (ifaceList.size() > 0) {
1629 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001630 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001631 }
1632 }
1633
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001634 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001635 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001636
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001637 // apply each policy that we found ifaces for; compute remaining data
1638 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001639 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001640 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1641 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1642 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001643
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001644 final long start;
1645 final long totalBytes;
1646 if (policy.hasCycle()) {
1647 start = computeLastCycleBoundary(currentTime, policy);
1648 totalBytes = getTotalBytes(policy.template, start, currentTime);
1649 } else {
1650 start = Long.MAX_VALUE;
1651 totalBytes = 0;
1652 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001653
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001654 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001655 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001656 }
1657
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001658 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001659 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001660 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001661 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001662 if (!hasLimit) {
1663 // metered network, but no policy limit; we still need to
1664 // restrict apps, so push really high quota.
1665 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001666 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001667 // snoozing past quota, but we still need to restrict apps,
1668 // so push really high quota.
1669 quotaBytes = Long.MAX_VALUE;
1670 } else {
1671 // remaining "quota" bytes are based on total usage in
1672 // current cycle. kernel doesn't like 0-byte rules, so we
1673 // set 1-byte quota and disable the radio later.
1674 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1675 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001676
1677 if (ifaces.length > 1) {
1678 // TODO: switch to shared quota once NMS supports
1679 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001680 }
1681
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001682 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001683 // long quotaBytes split up into two ints to fit in message
1684 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1685 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1686 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001687 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001688 }
1689 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001690
1691 // keep track of lowest warning or limit of active policies
1692 if (hasWarning && policy.warningBytes < lowestRule) {
1693 lowestRule = policy.warningBytes;
1694 }
1695 if (hasLimit && policy.limitBytes < lowestRule) {
1696 lowestRule = policy.limitBytes;
1697 }
1698 }
1699
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001700 for (int i = connIfaces.size()-1; i >= 0; i--) {
1701 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001702 // long quotaBytes split up into two ints to fit in message
1703 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1704 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1705 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001706 newMeteredIfaces.add(iface);
1707 }
1708
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001709 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001710
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001711 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001712 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1713 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001714 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001715 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1716 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001717 }
1718 }
1719 mMeteredIfaces = newMeteredIfaces;
1720
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001721 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001722 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001723 }
1724
1725 /**
1726 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1727 * have at least a default mobile policy defined.
1728 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001729 private void ensureActiveMobilePolicyAL() {
1730 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001731 if (mSuppressDefaultPolicy) return;
1732
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001733 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001734 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001735
Jeff Sharkey32566012014-12-02 18:30:14 -08001736 final int[] subIds = sub.getActiveSubscriptionIdList();
1737 for (int subId : subIds) {
1738 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001739 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001740 }
1741 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001742
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001743 /**
1744 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1745 * have at least a default mobile policy defined.
1746 *
1747 * @param subId to build a default policy for
1748 * @param subscriberId that we check for an existing policy
1749 * @return true if a mobile network policy was added, or false one already existed.
1750 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001751 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001752 // Poke around to see if we already have a policy
1753 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001754 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001755 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1756 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1757 if (template.matches(probeIdent)) {
1758 if (LOGD) {
1759 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1760 + NetworkIdentity.scrubSubscriberId(subscriberId));
1761 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001762 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001763 }
1764 }
1765
Jeff Sharkey32566012014-12-02 18:30:14 -08001766 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1767 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001768 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001769 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001770 return true;
1771 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001772
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001773 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001774 final int dataWarningConfig = mContext.getResources().getInteger(
1775 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001776 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001777 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001778 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001779 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001780 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001781 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001782
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001783 private long getPlatformDefaultLimitBytes() {
1784 return LIMIT_DISABLED;
1785 }
1786
1787 @VisibleForTesting
1788 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1789 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1790
1791 // assume usage cycle starts today
Jeff Sharkey32566012014-12-02 18:30:14 -08001792 final Time time = new Time();
1793 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001794
Jeff Sharkey32566012014-12-02 18:30:14 -08001795 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001796
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001797 final int cycleDay = getCycleDayFromCarrierConfig(config, time.monthDay);
1798 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1799 getPlatformDefaultWarningBytes());
1800 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1801 getPlatformDefaultLimitBytes());
1802
Jeff Sharkey32566012014-12-02 18:30:14 -08001803 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1804 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001805 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1806 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001807 }
1808
Felipe Lemef0823852016-06-08 13:43:08 -07001809 private void readPolicyAL() {
1810 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811
1812 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001813 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001814 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001815
1816 FileInputStream fis = null;
1817 try {
1818 fis = mPolicyFile.openRead();
1819 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001820 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821
Felipe Leme46b451f2016-08-19 08:46:17 -07001822 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1823 // to skip UIDs that were explicitly blacklisted.
1824 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1825
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001826 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001827 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001828 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001829 while ((type = in.next()) != END_DOCUMENT) {
1830 final String tag = in.getName();
1831 if (type == START_TAG) {
1832 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001833 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001834 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001835 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1836 mRestrictBackground = readBooleanAttribute(
1837 in, ATTR_RESTRICT_BACKGROUND);
1838 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001839 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001840 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001841 if (mRestrictBackground != oldValue) {
1842 // Some early services may have read the default value,
1843 // so notify them that it's changed
1844 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1845 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1846 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001847
1848 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1849 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1850 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001851 final String networkId;
1852 if (version >= VERSION_ADDED_NETWORK_ID) {
1853 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1854 } else {
1855 networkId = null;
1856 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001857 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001858 final String cycleTimezone;
1859 if (version >= VERSION_ADDED_TIMEZONE) {
1860 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1861 } else {
1862 cycleTimezone = Time.TIMEZONE_UTC;
1863 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001864 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1865 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001866 final long lastLimitSnooze;
1867 if (version >= VERSION_SPLIT_SNOOZE) {
1868 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1869 } else if (version >= VERSION_ADDED_SNOOZE) {
1870 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001871 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001872 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001873 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001874 final boolean metered;
1875 if (version >= VERSION_ADDED_METERED) {
1876 metered = readBooleanAttribute(in, ATTR_METERED);
1877 } else {
1878 switch (networkTemplate) {
1879 case MATCH_MOBILE_3G_LOWER:
1880 case MATCH_MOBILE_4G:
1881 case MATCH_MOBILE_ALL:
1882 metered = true;
1883 break;
1884 default:
1885 metered = false;
1886 }
1887 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001888 final long lastWarningSnooze;
1889 if (version >= VERSION_SPLIT_SNOOZE) {
1890 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1891 } else {
1892 lastWarningSnooze = SNOOZE_NEVER;
1893 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001894 final boolean inferred;
1895 if (version >= VERSION_ADDED_INFERRED) {
1896 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1897 } else {
1898 inferred = false;
1899 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001900
Jeff Sharkey32566012014-12-02 18:30:14 -08001901 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1902 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001903 if (template.isPersistable()) {
1904 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1905 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1906 lastLimitSnooze, metered, inferred));
1907 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001908
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001909 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001910 final int uid = readIntAttribute(in, ATTR_UID);
1911 final int policy = readIntAttribute(in, ATTR_POLICY);
1912
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001913 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001914 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001915 } else {
1916 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1917 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001918 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001919 final int appId = readIntAttribute(in, ATTR_APP_ID);
1920 final int policy = readIntAttribute(in, ATTR_POLICY);
1921
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001922 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001923 // app policy is deprecated so this is only used in pre system user split.
1924 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001925 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001926 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001927 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001928 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001929 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001930 } else if (TAG_WHITELIST.equals(tag)) {
1931 insideWhitelist = true;
1932 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1933 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001934 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001935 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1936 final int uid = readIntAttribute(in, ATTR_UID);
1937 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001938 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001939 } else if (type == END_TAG) {
1940 if (TAG_WHITELIST.equals(tag)) {
1941 insideWhitelist = false;
1942 }
1943
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001944 }
1945 }
1946
Felipe Leme46b451f2016-08-19 08:46:17 -07001947 final int size = whitelistedRestrictBackground.size();
1948 for (int i = 0; i < size; i++) {
1949 final int uid = whitelistedRestrictBackground.keyAt(i);
1950 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1951 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1952 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1953 + " because its policy is " + uidPoliciesToString(policy));
1954 continue;
1955 }
1956 if (UserHandle.isApp(uid)) {
1957 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1958 if (LOGV)
1959 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1960 setUidPolicyUncheckedUL(uid, newPolicy, false);
1961 } else {
1962 Slog.w(TAG, "unable to update policy on UID " + uid);
1963 }
1964 }
1965
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001966 } catch (FileNotFoundException e) {
1967 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001968 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001969 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001970 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001971 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001972 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001973 } finally {
1974 IoUtils.closeQuietly(fis);
1975 }
1976 }
1977
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001978 /**
1979 * Upgrade legacy background data flags, notifying listeners of one last
1980 * change to always-true.
1981 */
Felipe Lemef0823852016-06-08 13:43:08 -07001982 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001983 mRestrictBackground = Settings.Secure.getInt(
1984 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1985
1986 // kick off one last broadcast if restricted
1987 if (mRestrictBackground) {
1988 final Intent broadcast = new Intent(
1989 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001990 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001991 }
1992 }
1993
Felipe Lemef0823852016-06-08 13:43:08 -07001994 void writePolicyAL() {
1995 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001996
1997 FileOutputStream fos = null;
1998 try {
1999 fos = mPolicyFile.startWrite();
2000
2001 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002002 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002003 out.startDocument(null, true);
2004
2005 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002006 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002007 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002008
2009 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002010 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2011 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002012 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002013 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002014
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002015 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002016 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2017 final String subscriberId = template.getSubscriberId();
2018 if (subscriberId != null) {
2019 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002020 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002021 final String networkId = template.getNetworkId();
2022 if (networkId != null) {
2023 out.attribute(null, ATTR_NETWORK_ID, networkId);
2024 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002025 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002026 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002027 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2028 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002029 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2030 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002031 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002032 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002033 out.endTag(null, TAG_NETWORK_POLICY);
2034 }
2035
2036 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002037 for (int i = 0; i < mUidPolicy.size(); i++) {
2038 final int uid = mUidPolicy.keyAt(i);
2039 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002040
Jeff Sharkey497e4432011-06-14 17:27:29 -07002041 // skip writing empty policies
2042 if (policy == POLICY_NONE) continue;
2043
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002044 out.startTag(null, TAG_UID_POLICY);
2045 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002046 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002047 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002048 }
2049
2050 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002051
2052 // write all whitelists
2053 out.startTag(null, TAG_WHITELIST);
2054
Felipe Lemea9505cc2016-02-26 10:28:41 -08002055 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002056 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002057 for (int i = 0; i < size; i++) {
2058 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2059 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2060 writeIntAttribute(out, ATTR_UID, uid);
2061 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2062 }
2063
Felipe Lemeb85a6372016-01-14 16:16:16 -08002064 out.endTag(null, TAG_WHITELIST);
2065
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002066 out.endDocument();
2067
2068 mPolicyFile.finishWrite(fos);
2069 } catch (IOException e) {
2070 if (fos != null) {
2071 mPolicyFile.failWrite(fos);
2072 }
2073 }
2074 }
2075
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002076 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002077 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002078 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002079
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002080 if (!UserHandle.isApp(uid)) {
2081 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002082 }
Felipe Lemef0823852016-06-08 13:43:08 -07002083 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002084 final long token = Binder.clearCallingIdentity();
2085 try {
2086 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2087 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002088 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002089 }
2090 } finally {
2091 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002092 }
2093 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002094 }
2095
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002096 @Override
2097 public void addUidPolicy(int uid, int policy) {
2098 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002099
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002100 if (!UserHandle.isApp(uid)) {
2101 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2102 }
2103
Felipe Lemef0823852016-06-08 13:43:08 -07002104 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002105 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2106 policy |= oldPolicy;
2107 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002108 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002109 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002111 }
2112
2113 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002114 public void removeUidPolicy(int uid, int policy) {
2115 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2116
2117 if (!UserHandle.isApp(uid)) {
2118 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2119 }
2120
Felipe Lemef0823852016-06-08 13:43:08 -07002121 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002122 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2123 policy = oldPolicy & ~policy;
2124 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002125 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002126 }
2127 }
2128 }
2129
Felipe Lemef0823852016-06-08 13:43:08 -07002130 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2131 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002132
Felipe Leme57e3d312016-08-23 14:42:52 -07002133 final boolean notifyApp;
2134 if (!isUidValidForWhitelistRules(uid)) {
2135 notifyApp = false;
2136 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002137 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2138 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2139 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2140 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002141 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2142 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002143 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2144 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2145 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2146 if (LOGD)
2147 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2148 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2149 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002150 notifyApp = wasBlocked != isBlocked;
2151 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002152 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2153 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002154 }
2155
Felipe Lemef0823852016-06-08 13:43:08 -07002156 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002157 if (policy == POLICY_NONE) {
2158 mUidPolicy.delete(uid);
2159 } else {
2160 mUidPolicy.put(uid, policy);
2161 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002162
2163 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002164 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002165 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002166 synchronized (mNetworkPoliciesSecondLock) {
2167 writePolicyAL();
2168 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002169 }
2170 }
2171
2172 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002173 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002174 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2175
Felipe Lemef0823852016-06-08 13:43:08 -07002176 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002177 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002178 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002179 }
2180
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002181 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002182 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002183 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2184
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002185 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002186 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002187 for (int i = 0; i < mUidPolicy.size(); i++) {
2188 final int uid = mUidPolicy.keyAt(i);
2189 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002190 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2191 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002192 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002193 }
2194 }
2195 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002196 return uids;
2197 }
2198
2199 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002200 * Removes any persistable state associated with given {@link UserHandle}, persisting
2201 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002202 */
Felipe Lemef0823852016-06-08 13:43:08 -07002203 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002204
Felipe Lemef0823852016-06-08 13:43:08 -07002205 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002206 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002207
Felipe Lemea110eec2016-04-29 09:58:06 -07002208 // Remove entries from revoked default restricted background UID whitelist
2209 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2210 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2211 if (UserHandle.getUserId(uid) == userId) {
2212 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002213 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002214 }
2215 }
2216
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002217 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002218 int[] uids = new int[0];
2219 for (int i = 0; i < mUidPolicy.size(); i++) {
2220 final int uid = mUidPolicy.keyAt(i);
2221 if (UserHandle.getUserId(uid) == userId) {
2222 uids = appendInt(uids, uid);
2223 }
2224 }
2225
2226 if (uids.length > 0) {
2227 for (int uid : uids) {
2228 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002229 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002230 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002231 }
Felipe Lemef0823852016-06-08 13:43:08 -07002232 synchronized (mNetworkPoliciesSecondLock) {
2233 updateRulesForGlobalChangeAL(true);
2234 if (writePolicy && changed) {
2235 writePolicyAL();
2236 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002237 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002238 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002239 }
2240
2241 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002242 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002243 // TODO: create permission for observing network policy
2244 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002245 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002246 }
2247
2248 @Override
2249 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002250 // TODO: create permission for observing network policy
2251 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002252 mListeners.unregister(listener);
2253 }
2254
Jeff Sharkey1b861272011-05-22 00:34:52 -07002255 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002256 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002257 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2258
Felipe Leme6a05eee2016-02-19 14:43:51 -08002259 final long token = Binder.clearCallingIdentity();
2260 try {
2261 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002262 synchronized (mUidRulesFirstLock) {
2263 synchronized (mNetworkPoliciesSecondLock) {
2264 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002265 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002266 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002267 }
2268 } finally {
2269 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002270 }
2271 }
2272
Hugo Benichi446c9c92017-04-10 09:41:10 +09002273 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002274 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002275 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2276 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002277 }
2278
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002279 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002280 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002281 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002282 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002283 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2284 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2285 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002286 } catch (SecurityException e) {
2287 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002288
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002289 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2290 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2291 return new NetworkPolicy[0];
2292 }
Svet Ganov16a16892015-04-16 10:32:04 -07002293 }
2294
Felipe Lemef0823852016-06-08 13:43:08 -07002295 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002296 final int size = mNetworkPolicy.size();
2297 final NetworkPolicy[] policies = new NetworkPolicy[size];
2298 for (int i = 0; i < size; i++) {
2299 policies[i] = mNetworkPolicy.valueAt(i);
2300 }
2301 return policies;
2302 }
2303 }
2304
Felipe Lemef0823852016-06-08 13:43:08 -07002305 private void normalizePoliciesNL() {
2306 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002307 }
2308
Felipe Lemef0823852016-06-08 13:43:08 -07002309 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002310 final TelephonyManager tele = TelephonyManager.from(mContext);
2311 final String[] merged = tele.getMergedSubscriberIds();
2312
2313 mNetworkPolicy.clear();
2314 for (NetworkPolicy policy : policies) {
2315 // When two normalized templates conflict, prefer the most
2316 // restrictive policy
2317 policy.template = NetworkTemplate.normalize(policy.template, merged);
2318 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2319 if (existing == null || existing.compareTo(policy) > 0) {
2320 if (existing != null) {
2321 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2322 }
2323 mNetworkPolicy.put(policy.template, policy);
2324 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002325 }
2326 }
2327
2328 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002329 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002330 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002331
2332 final long token = Binder.clearCallingIdentity();
2333 try {
2334 performSnooze(template, TYPE_LIMIT);
2335 } finally {
2336 Binder.restoreCallingIdentity(token);
2337 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002338 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002339
Dianne Hackborn497175b2014-07-01 12:56:08 -07002340 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002341 maybeRefreshTrustedTime();
2342 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002343 synchronized (mUidRulesFirstLock) {
2344 synchronized (mNetworkPoliciesSecondLock) {
2345 // find and snooze local policy that matches
2346 final NetworkPolicy policy = mNetworkPolicy.get(template);
2347 if (policy == null) {
2348 throw new IllegalArgumentException("unable to find policy for " + template);
2349 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002350
Felipe Lemef0823852016-06-08 13:43:08 -07002351 switch (type) {
2352 case TYPE_WARNING:
2353 policy.lastWarningSnooze = currentTime;
2354 break;
2355 case TYPE_LIMIT:
2356 policy.lastLimitSnooze = currentTime;
2357 break;
2358 default:
2359 throw new IllegalArgumentException("unexpected type");
2360 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002361
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002362 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002363 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002364 }
2365 }
2366
2367 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002368 public void onTetheringChanged(String iface, boolean tethering) {
2369 // No need to enforce permission because setRestrictBackground() will do it.
2370 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002371 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002372 if (mRestrictBackground && tethering) {
2373 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2374 setRestrictBackground(false);
2375 }
2376 }
2377 }
2378
2379 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002380 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002381 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002382 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002383 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2384 final long token = Binder.clearCallingIdentity();
2385 try {
2386 maybeRefreshTrustedTime();
2387 synchronized (mUidRulesFirstLock) {
2388 if (restrictBackground == mRestrictBackground) {
2389 // Ideally, UI should never allow this scenario...
2390 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2391 return;
2392 }
2393 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002394 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002395
2396 } finally {
2397 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002398 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002399
Felipe Leme29e72ea2016-09-08 13:26:55 -07002400 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2401 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002402 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002403 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002404 }
2405 }
2406
Felipe Lemef0823852016-06-08 13:43:08 -07002407 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002408 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002409 final boolean oldRestrictBackground = mRestrictBackground;
2410 mRestrictBackground = restrictBackground;
2411 // Must whitelist foreground apps before turning data saver mode on.
2412 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2413 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002414 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002415 try {
2416 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2417 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2418 mRestrictBackground = oldRestrictBackground;
2419 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002420 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002421 return;
2422 }
2423 } catch (RemoteException e) {
2424 // ignored; service lives in system_server
2425 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002426
2427 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2428 mRestrictBackgroundChangedInBsm = true;
2429 }
Felipe Lemef0823852016-06-08 13:43:08 -07002430 synchronized (mNetworkPoliciesSecondLock) {
2431 updateNotificationsNL();
2432 writePolicyAL();
2433 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002434 }
2435
Felipe Lemeb85a6372016-01-14 16:16:16 -08002436 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002437 public int getRestrictBackgroundByCaller() {
2438 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2439 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002440
Felipe Lemef0823852016-06-08 13:43:08 -07002441 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002442 // Must clear identity because getUidPolicy() is restricted to system.
2443 final long token = Binder.clearCallingIdentity();
2444 final int policy;
2445 try {
2446 policy = getUidPolicy(uid);
2447 } finally {
2448 Binder.restoreCallingIdentity(token);
2449 }
2450 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2451 // App is blacklisted.
2452 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2453 }
Felipe Leme1b103232016-01-22 09:44:57 -08002454 if (!mRestrictBackground) {
2455 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2456 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002457 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002458 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2459 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2460 }
2461 }
2462
2463 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002464 public boolean getRestrictBackground() {
2465 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2466
Felipe Lemef0823852016-06-08 13:43:08 -07002467 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002468 return mRestrictBackground;
2469 }
2470 }
2471
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002472 @Override
2473 public void setDeviceIdleMode(boolean enabled) {
2474 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002475 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2476 try {
2477 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002478 if (mDeviceIdleMode == enabled) {
2479 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002480 }
Felipe Lemeea014392016-09-06 13:59:54 -07002481 mDeviceIdleMode = enabled;
2482 if (mSystemReady) {
2483 // Device idle change means we need to rebuild rules for all
2484 // known apps, so do a global refresh.
2485 updateRulesForRestrictPowerUL();
2486 }
2487 }
2488 if (enabled) {
2489 EventLogTags.writeDeviceIdleOnPhase("net");
2490 } else {
2491 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002492 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002493 } finally {
2494 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002495 }
2496 }
2497
Felipe Lemef0823852016-06-08 13:43:08 -07002498 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002499 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2500 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002501 if (policy.template.matches(ident)) {
2502 return policy;
2503 }
2504 }
2505 return null;
2506 }
2507
2508 @Override
2509 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2510 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2511
2512 // only returns usage summary, so we don't require caller to have
2513 // READ_NETWORK_USAGE_HISTORY.
2514 final long token = Binder.clearCallingIdentity();
2515 try {
2516 return getNetworkQuotaInfoUnchecked(state);
2517 } finally {
2518 Binder.restoreCallingIdentity(token);
2519 }
2520 }
2521
2522 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2523 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2524
2525 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002526 synchronized (mNetworkPoliciesSecondLock) {
2527 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002528 }
2529
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002530 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002531 // missing policy means we can't derive useful quota info
2532 return null;
2533 }
2534
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002535 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002536
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002537 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002538 final long start = computeLastCycleBoundary(currentTime, policy);
2539 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002540 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002541
2542 // report soft and hard limits under policy
2543 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2544 : NetworkQuotaInfo.NO_LIMIT;
2545 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2546 : NetworkQuotaInfo.NO_LIMIT;
2547
2548 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2549 }
2550
Jeff Sharkey46645002011-07-27 21:11:21 -07002551 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002552 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002553 if (state.networkInfo == null) {
2554 return false;
2555 }
2556
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002557 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2558
2559 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002560 synchronized (mNetworkPoliciesSecondLock) {
2561 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002562 }
2563
2564 if (policy != null) {
2565 return policy.metered;
2566 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002567 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002568 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002569 return true;
2570 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002571 return false;
2572 }
2573 }
2574
2575 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002576 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002577 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002578
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002579 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2580
Dianne Hackborn497175b2014-07-01 12:56:08 -07002581 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002582 for (String arg : args) {
2583 argSet.add(arg);
2584 }
2585
Felipe Lemef0823852016-06-08 13:43:08 -07002586 synchronized (mUidRulesFirstLock) {
2587 synchronized (mNetworkPoliciesSecondLock) {
2588 if (argSet.contains("--unsnooze")) {
2589 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2590 mNetworkPolicy.valueAt(i).clearSnooze();
2591 }
2592
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002593 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002594
2595 fout.println("Cleared snooze timestamps");
2596 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002597 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002598
Felipe Lemef0823852016-06-08 13:43:08 -07002599 fout.print("System ready: "); fout.println(mSystemReady);
2600 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2601 fout.print("Restrict power: "); fout.println(mRestrictPower);
2602 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2603 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002604 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002605 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2606 fout.println(mNetworkPolicy.valueAt(i).toString());
2607 }
2608 fout.decreaseIndent();
2609
2610 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2611
2612 fout.println("Policy for UIDs:");
2613 fout.increaseIndent();
2614 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002615 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002616 final int uid = mUidPolicy.keyAt(i);
2617 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002618 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002619 fout.print(uid);
2620 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002621 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002622 fout.println();
2623 }
2624 fout.decreaseIndent();
2625
2626 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2627 if (size > 0) {
2628 fout.println("Power save whitelist (except idle) app ids:");
2629 fout.increaseIndent();
2630 for (int i = 0; i < size; i++) {
2631 fout.print("UID=");
2632 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2633 fout.print(": ");
2634 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2635 fout.println();
2636 }
2637 fout.decreaseIndent();
2638 }
2639
2640 size = mPowerSaveWhitelistAppIds.size();
2641 if (size > 0) {
2642 fout.println("Power save whitelist app ids:");
2643 fout.increaseIndent();
2644 for (int i = 0; i < size; i++) {
2645 fout.print("UID=");
2646 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2647 fout.print(": ");
2648 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2649 fout.println();
2650 }
2651 fout.decreaseIndent();
2652 }
2653
Felipe Lemef0823852016-06-08 13:43:08 -07002654 size = mDefaultRestrictBackgroundWhitelistUids.size();
2655 if (size > 0) {
2656 fout.println("Default restrict background whitelist uids:");
2657 fout.increaseIndent();
2658 for (int i = 0; i < size; i++) {
2659 fout.print("UID=");
2660 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2661 fout.println();
2662 }
2663 fout.decreaseIndent();
2664 }
2665
2666 size = mRestrictBackgroundWhitelistRevokedUids.size();
2667 if (size > 0) {
2668 fout.println("Default restrict background whitelist uids revoked by users:");
2669 fout.increaseIndent();
2670 for (int i = 0; i < size; i++) {
2671 fout.print("UID=");
2672 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2673 fout.println();
2674 }
2675 fout.decreaseIndent();
2676 }
2677
2678 final SparseBooleanArray knownUids = new SparseBooleanArray();
2679 collectKeys(mUidState, knownUids);
2680 collectKeys(mUidRules, knownUids);
2681
2682 fout.println("Status for all known UIDs:");
2683 fout.increaseIndent();
2684 size = knownUids.size();
2685 for (int i = 0; i < size; i++) {
2686 final int uid = knownUids.keyAt(i);
2687 fout.print("UID=");
2688 fout.print(uid);
2689
2690 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2691 fout.print(" state=");
2692 fout.print(state);
2693 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2694 fout.print(" (fg)");
2695 } else {
2696 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2697 ? " (fg svc)" : " (bg)");
2698 }
2699
2700 final int uidRules = mUidRules.get(uid, RULE_NONE);
2701 fout.print(" rules=");
2702 fout.print(uidRulesToString(uidRules));
2703 fout.println();
2704 }
2705 fout.decreaseIndent();
2706
2707 fout.println("Status for just UIDs with rules:");
2708 fout.increaseIndent();
2709 size = mUidRules.size();
2710 for (int i = 0; i < size; i++) {
2711 final int uid = mUidRules.keyAt(i);
2712 fout.print("UID=");
2713 fout.print(uid);
2714 final int uidRules = mUidRules.get(uid, RULE_NONE);
2715 fout.print(" rules=");
2716 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002717 fout.println();
2718 }
2719 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002720
2721 fout.println("Observed uid state changes:");
2722 fout.increaseIndent();
2723 mObservedHistory.dumpUL(fout);
2724 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002725 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002726 }
2727 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002728
2729 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002730 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002731 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002732 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002733 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002734 }
2735
2736 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002737 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002738 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2739
Felipe Lemef0823852016-06-08 13:43:08 -07002740 synchronized (mUidRulesFirstLock) {
2741 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002742 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002743 }
2744
Felipe Lemef0823852016-06-08 13:43:08 -07002745 private boolean isUidForegroundUL(int uid) {
2746 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002747 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2748 }
2749
Felipe Lemef0823852016-06-08 13:43:08 -07002750 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002751 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002752 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002753 }
2754
Felipe Lemef0823852016-06-08 13:43:08 -07002755 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002756 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2757 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2758 }
2759
Felipe Lemef0823852016-06-08 13:43:08 -07002760 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002761 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002762 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002763 }
2764
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002765 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002766 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002767 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2768 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002769 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002770 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002771 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2772 try {
2773 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2774 if (oldUidState != uidState) {
2775 // state changed, push updated rules
2776 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002777 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2778 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2779 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2780 if (isUidIdle(uid)) {
2781 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002782 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002783 if (mDeviceIdleMode) {
2784 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002785 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002786 if (mRestrictPower) {
2787 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002788 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002789 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002790 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002791 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002792 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002793 } finally {
2794 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002795 }
2796 }
2797
Felipe Lemef0823852016-06-08 13:43:08 -07002798 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002799 final int index = mUidState.indexOfKey(uid);
2800 if (index >= 0) {
2801 final int oldUidState = mUidState.valueAt(index);
2802 mUidState.removeAt(index);
2803 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002804 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002805 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002806 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002807 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002808 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002809 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002810 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002811 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002812 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002813 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002814 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002815 }
2816 }
2817
Felipe Lemef28983d2016-03-25 12:18:23 -07002818 // adjust stats accounting based on foreground status
2819 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002820 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2821 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2822 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2823 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002824 try {
2825 mNetworkStats.setUidForeground(uid, uidForeground);
2826 } catch (RemoteException e) {
2827 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002828 } finally {
2829 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002830 }
2831 }
2832
Sudheer Shankac9d94072017-02-22 22:13:55 +00002833 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2834 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002835 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002836 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002837 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002838 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002839 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002840 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002841 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002842 }
2843
Felipe Lemef0823852016-06-08 13:43:08 -07002844 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002845 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2846 try {
2847 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2848 mUidFirewallPowerSaveRules);
2849 } finally {
2850 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2851 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002852 }
2853
Felipe Lemef0823852016-06-08 13:43:08 -07002854 void updateRuleForRestrictPowerUL(int uid) {
2855 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002856 }
2857
Felipe Lemef0823852016-06-08 13:43:08 -07002858 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002859 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2860 try {
2861 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2862 mUidFirewallDozableRules);
2863 } finally {
2864 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2865 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002866 }
2867
Felipe Lemef0823852016-06-08 13:43:08 -07002868 void updateRuleForDeviceIdleUL(int uid) {
2869 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002870 }
2871
Felipe Lemef28983d2016-03-25 12:18:23 -07002872 // NOTE: since both fw_dozable and fw_powersave uses the same map
2873 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002874 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002875 SparseIntArray rules) {
2876 if (enabled) {
2877 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002878 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002879 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002880 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002881 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002882 for (int ui = users.size() - 1; ui >= 0; ui--) {
2883 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002884 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
2885 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
2886 if (chain == FIREWALL_CHAIN_POWERSAVE) {
2887 updateRulesForWhitelistedAppIds(uidRules,
2888 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002889 }
2890 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002891 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002892 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002893 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2894 }
2895 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002896 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2897 } else {
2898 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002899 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002900 }
2901
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002902 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
2903 final SparseBooleanArray whitelistedAppIds, int userId) {
2904 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
2905 if (whitelistedAppIds.valueAt(i)) {
2906 final int appId = whitelistedAppIds.keyAt(i);
2907 final int uid = UserHandle.getUid(userId, appId);
2908 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2909 }
2910 }
2911 }
2912
2913 /**
2914 * @param deviceIdleMode if true then we don't consider
2915 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
2916 * whitelisted.
2917 */
2918 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002919 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002920 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
2921 || mPowerSaveWhitelistAppIds.get(appId);
2922 if (!deviceIdleMode) {
2923 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
2924 }
2925 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07002926 }
2927
Felipe Lemef28983d2016-03-25 12:18:23 -07002928 // NOTE: since both fw_dozable and fw_powersave uses the same map
2929 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002930 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002931 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002932 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
2933 chain == FIREWALL_CHAIN_DOZABLE);
2934 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002935 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002936 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002937 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002938 }
2939 }
2940 }
2941
Felipe Lemef0823852016-06-08 13:43:08 -07002942 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002943 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2944 try {
2945 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2946 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002947
Felipe Leme873a83a2016-09-07 11:34:10 -07002948 // Fully update the app idle firewall chain.
2949 final List<UserInfo> users = mUserManager.getUsers();
2950 for (int ui = users.size() - 1; ui >= 0; ui--) {
2951 UserInfo user = users.get(ui);
2952 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2953 for (int uid : idleUids) {
2954 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2955 // quick check: if this uid doesn't have INTERNET permission, it
2956 // doesn't have network access anyway, so it is a waste to mess
2957 // with it here.
2958 if (hasInternetPermissions(uid)) {
2959 uidRules.put(uid, FIREWALL_RULE_DENY);
2960 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002961 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002962 }
2963 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002964
Felipe Lemebc853dd2016-09-08 13:26:55 -07002965 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002966 } finally {
2967 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2968 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002969 }
2970
Felipe Lemef0823852016-06-08 13:43:08 -07002971 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002972 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002973
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002974 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2975 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
2976 }
2977 try {
2978 int appId = UserHandle.getAppId(uid);
2979 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2980 && !isUidForegroundOnRestrictPowerUL(uid)) {
2981 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2982 } else {
2983 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2984 }
2985 } finally {
2986 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002987 }
2988 }
2989
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002990 /**
2991 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2992 * changed.
2993 */
Felipe Lemef0823852016-06-08 13:43:08 -07002994 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002995 boolean paroled = mUsageStats.isAppIdleParoleOn();
2996 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002997 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002998
2999 int ruleCount = mUidFirewallStandbyRules.size();
3000 for (int i = 0; i < ruleCount; i++) {
3001 int uid = mUidFirewallStandbyRules.keyAt(i);
3002 int oldRules = mUidRules.get(uid);
3003 if (enableChain) {
3004 // Chain wasn't enabled before and the other power-related
3005 // chains are whitelists, so we can clear the
3006 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3007 // the effective rules result in blocking network access.
3008 oldRules &= MASK_METERED_NETWORKS;
3009 } else {
3010 // Skip if it had no restrictions to begin with
3011 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3012 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003013 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3014 if (newUidRules == RULE_NONE) {
3015 mUidRules.delete(uid);
3016 } else {
3017 mUidRules.put(uid, newUidRules);
3018 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003019 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003020 }
3021
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003022 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003023 * Update rules that might be changed by {@link #mRestrictBackground},
3024 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003025 */
Felipe Lemef0823852016-06-08 13:43:08 -07003026 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003027 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3028 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3029 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3030 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003031 try {
Felipe Leme09700462016-09-08 09:33:48 -07003032 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003033 updateRulesForRestrictPowerUL();
3034 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003035
Felipe Leme873a83a2016-09-07 11:34:10 -07003036 // If the set of restricted networks may have changed, re-evaluate those.
3037 if (restrictedNetworksChanged) {
3038 normalizePoliciesNL();
3039 updateNetworkRulesNL();
3040 }
3041 } finally {
3042 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003043 }
3044 }
3045
Felipe Leme09700462016-09-08 09:33:48 -07003046 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003047 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003048 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3049 try {
3050 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003051 updateRulesForPowerSaveUL();
3052 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3053 } finally {
3054 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3055 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003056 }
3057
Felipe Lemef0823852016-06-08 13:43:08 -07003058 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003059 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3060 try {
3061 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3062 } finally {
3063 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3064 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003065 }
3066
3067 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3068 private static final int TYPE_RESTRICT_POWER = 2;
3069 @Retention(RetentionPolicy.SOURCE)
3070 @IntDef(flag = false, value = {
3071 TYPE_RESTRICT_BACKGROUND,
3072 TYPE_RESTRICT_POWER,
3073 })
3074 public @interface RestrictType {
3075 }
3076
3077 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003078 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003079 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3080 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3081 }
3082 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003083 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003084
3085 final PackageManager pm = mContext.getPackageManager();
3086 final List<UserInfo> users;
3087 final List<ApplicationInfo> apps;
3088
3089 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3090 try {
3091 users = mUserManager.getUsers();
3092 } finally {
3093 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3094 }
3095 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3096 try {
3097 apps = pm.getInstalledApplications(
3098 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3099 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3100 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3101 } finally {
3102 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3103 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003104
Felipe Leme873a83a2016-09-07 11:34:10 -07003105 final int usersSize = users.size();
3106 final int appsSize = apps.size();
3107 for (int i = 0; i < usersSize; i++) {
3108 final UserInfo user = users.get(i);
3109 for (int j = 0; j < appsSize; j++) {
3110 final ApplicationInfo app = apps.get(j);
3111 final int uid = UserHandle.getUid(user.id, app.uid);
3112 switch (type) {
3113 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003114 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003115 break;
3116 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003117 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003118 break;
3119 default:
3120 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3121 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003122 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003123 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003124 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003125 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003126 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003127 }
3128
Felipe Lemef0823852016-06-08 13:43:08 -07003129 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003130 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003131 for (int i = 0; i < users.size(); i++) {
3132 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003133 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003134 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003135 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003136 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003137 updateRuleForAppIdleUL(uid);
3138 updateRuleForDeviceIdleUL(uid);
3139 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003140 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003141 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003142 }
3143 }
3144 }
3145
Felipe Leme70c57c22016-03-29 10:45:13 -07003146 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3147 // methods below could be merged into a isUidValidForRules() method.
3148 private boolean isUidValidForBlacklistRules(int uid) {
3149 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003150 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003151 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003152 return true;
3153 }
3154
3155 return false;
3156 }
3157
Felipe Leme70c57c22016-03-29 10:45:13 -07003158 private boolean isUidValidForWhitelistRules(int uid) {
3159 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3160 }
3161
Amith Yamasani15e472352015-04-24 19:06:07 -07003162 private boolean isUidIdle(int uid) {
3163 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3164 final int userId = UserHandle.getUserId(uid);
3165
songjinshi0655edd2016-05-18 19:55:32 +08003166 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003167 for (String packageName : packages) {
3168 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3169 return false;
3170 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003171 }
3172 }
3173 return true;
3174 }
3175
3176 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003177 * Checks if an uid has INTERNET permissions.
3178 * <p>
3179 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003180 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003181 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003182 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003183 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003184 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003185 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003186 }
3187 } catch (RemoteException e) {
3188 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003189 return true;
3190 }
3191
3192 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003193 * Clears all state - internal and external - associated with an UID.
3194 */
3195 private void onUidDeletedUL(int uid) {
3196 // First cleanup in-memory state synchronously...
3197 mUidRules.delete(uid);
3198 mUidPolicy.delete(uid);
3199 mUidFirewallStandbyRules.delete(uid);
3200 mUidFirewallDozableRules.delete(uid);
3201 mUidFirewallPowerSaveRules.delete(uid);
3202 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3203 mPowerSaveWhitelistAppIds.delete(uid);
3204 mPowerSaveTempWhitelistAppIds.delete(uid);
3205
3206 // ...then update iptables asynchronously.
3207 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3208 }
3209
3210 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003211 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003212 *
Felipe Leme781ba142016-05-09 16:24:48 -07003213 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003214 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003215 * <li>Doze mode
3216 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003217 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003218 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003219 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003220 *
3221 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003222 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003223 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003224 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003225 updateRuleForDeviceIdleUL(uid);
3226 updateRuleForAppIdleUL(uid);
3227 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003228
3229 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003230 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003231
3232 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003233 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003234 }
3235
Felipe Leme70c57c22016-03-29 10:45:13 -07003236 /**
3237 * Applies network rules to bandwidth controllers based on process state and user-defined
3238 * restrictions (blacklist / whitelist).
3239 *
3240 * <p>
3241 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3242 * networks:
3243 * <ul>
3244 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3245 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3246 * also blacklisted.
3247 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3248 * no UIDs other those whitelisted will have access.
3249 * <ul>
3250 *
3251 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3252 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3253 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3254 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003255 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003256 * {@link INetworkManagementService}, but this method should also be called in events (like
3257 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3258 * following rules should also be applied:
3259 *
3260 * <ul>
3261 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3262 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3263 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3264 * {@code bw_penalty_box}.
3265 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3266 * </ul>
3267 *
3268 * <p>For optimization, the rules are only applied on user apps that have internet access
3269 * permission, since there is no need to change the {@code iptables} rule if the app does not
3270 * have permission to use the internet.
3271 *
3272 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003273 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003274 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003275 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003276 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3277 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3278 "updateRulesForDataUsageRestrictionsUL: " + uid);
3279 }
3280 try {
3281 updateRulesForDataUsageRestrictionsULInner(uid);
3282 } finally {
3283 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3284 }
3285 }
3286
3287 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003288 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003289 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003290 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003291 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003292
Dianne Hackborn497175b2014-07-01 12:56:08 -07003293 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003294 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003295 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003296
Felipe Leme781ba142016-05-09 16:24:48 -07003297 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003298 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003299 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3300 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003301
Felipe Leme70c57c22016-03-29 10:45:13 -07003302 // First step: define the new rule based on user restrictions and foreground state.
3303 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003304 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3305 newRule = RULE_TEMPORARY_ALLOW_METERED;
3306 } else if (isWhitelisted) {
3307 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003308 }
3309 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003310 if (isBlacklisted) {
3311 newRule = RULE_REJECT_METERED;
3312 } else if (mRestrictBackground && isWhitelisted) {
3313 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003314 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003315 }
Felipe Leme781ba142016-05-09 16:24:48 -07003316 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003317
Felipe Lemef28983d2016-03-25 12:18:23 -07003318 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003319 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003320 + ": isForeground=" +isForeground
3321 + ", isBlacklisted=" + isBlacklisted
3322 + ", isWhitelisted=" + isWhitelisted
3323 + ", oldRule=" + uidRulesToString(oldRule)
3324 + ", newRule=" + uidRulesToString(newRule)
3325 + ", newUidRules=" + uidRulesToString(newUidRules)
3326 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003327 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003328
Felipe Leme46c4fc32016-05-04 09:21:43 -07003329 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003330 mUidRules.delete(uid);
3331 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003332 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003333 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003334
Felipe Leme70c57c22016-03-29 10:45:13 -07003335 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003336 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003337 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003338 // Temporarily whitelist foreground app, removing from blacklist if necessary
3339 // (since bw_penalty_box prevails over bw_happy_box).
3340
3341 setMeteredNetworkWhitelist(uid, true);
3342 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3343 // but ideally it should be just:
3344 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003345 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003346 setMeteredNetworkBlacklist(uid, false);
3347 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003348 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003349 // Remove temporary whitelist from app that is not on foreground anymore.
3350
3351 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3352 // but ideally they should be just:
3353 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3354 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003355 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003356 setMeteredNetworkWhitelist(uid, false);
3357 }
Felipe Leme781ba142016-05-09 16:24:48 -07003358 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003359 setMeteredNetworkBlacklist(uid, true);
3360 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003361 } else if (hasRule(newRule, RULE_REJECT_METERED)
3362 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003363 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003364 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003365 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003366 // Since blacklist prevails over whitelist, we need to handle the special case
3367 // where app is whitelisted and blacklisted at the same time (although such
3368 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003369 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003370 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003371 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3372 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003373 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003374 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003375 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003376 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003377 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3378 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003379 + ", whitelisted=" + isWhitelisted
3380 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003381 + ", newRule=" + uidRulesToString(newUidRules)
3382 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003383 }
Felipe Leme781ba142016-05-09 16:24:48 -07003384
Sudheer Shankac9d94072017-02-22 22:13:55 +00003385 // Dispatch changed rule to existing listeners.
3386 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003387 }
3388 }
3389
3390 /**
3391 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3392 * listeners in case of change.
3393 * <p>
3394 * There are 3 power-related rules that affects whether an app has background access on
3395 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3396 * restriction, it's added to the equivalent firewall chain:
3397 * <ul>
3398 * <li>App is idle: {@code fw_standby} firewall chain.
3399 * <li>Device is idle: {@code fw_dozable} firewall chain.
3400 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3401 * </ul>
3402 * <p>
3403 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3404 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3405 * <p>
3406 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3407 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003408 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003409 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3410
Sudheer Shankac9d94072017-02-22 22:13:55 +00003411 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003412
Sudheer Shankac9d94072017-02-22 22:13:55 +00003413 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003414 mUidRules.delete(uid);
3415 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003416 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003417 }
3418 }
3419
3420 /**
3421 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3422 *
3423 * @param uid the uid of the app to update rules for
3424 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3425 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3426 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003427 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003428 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003429 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003430 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3431 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3432 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3433 + (paroled ? "P" : "-"));
3434 }
3435 try {
3436 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3437 } finally {
3438 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3439 }
3440 }
3441
3442 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003443 if (!isUidValidForBlacklistRules(uid)) {
3444 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003445 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003446 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003447
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003448 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003449 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003450 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003451
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003452 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003453 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3454 int newRule = RULE_NONE;
3455
3456 // First step: define the new rule based on user restrictions and foreground state.
3457
3458 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3459 // by considering the foreground and non-foreground states.
3460 if (isForeground) {
3461 if (restrictMode) {
3462 newRule = RULE_ALLOW_ALL;
3463 }
3464 } else if (restrictMode) {
3465 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3466 }
3467
3468 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3469
3470 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003471 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003472 + ", isIdle: " + isIdle
3473 + ", mRestrictPower: " + mRestrictPower
3474 + ", mDeviceIdleMode: " + mDeviceIdleMode
3475 + ", isForeground=" + isForeground
3476 + ", isWhitelisted=" + isWhitelisted
3477 + ", oldRule=" + uidRulesToString(oldRule)
3478 + ", newRule=" + uidRulesToString(newRule)
3479 + ", newUidRules=" + uidRulesToString(newUidRules)
3480 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3481 }
3482
Felipe Leme781ba142016-05-09 16:24:48 -07003483 // Second step: notify listeners if state changed.
3484 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003485 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003486 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003487 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003488 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3489 } else {
3490 // All scenarios should have been covered above
3491 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3492 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003493 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003494 + ", newRule=" + uidRulesToString(newUidRules)
3495 + ", oldRule=" + uidRulesToString(oldUidRules));
3496 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003497 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003498 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003499
Sudheer Shankac9d94072017-02-22 22:13:55 +00003500 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003501 }
3502
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003503 private class AppIdleStateChangeListener
3504 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3505
3506 @Override
3507 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3508 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003509 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3510 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003511 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003512 synchronized (mUidRulesFirstLock) {
3513 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003514 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003515 }
3516 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003517 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003518 }
3519
3520 @Override
3521 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003522 synchronized (mUidRulesFirstLock) {
3523 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003524 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003525 }
3526 }
3527
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003528 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3529 if (listener != null) {
3530 try {
3531 listener.onUidRulesChanged(uid, uidRules);
3532 } catch (RemoteException ignored) {
3533 }
3534 }
3535 }
3536
3537 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3538 String[] meteredIfaces) {
3539 if (listener != null) {
3540 try {
3541 listener.onMeteredIfacesChanged(meteredIfaces);
3542 } catch (RemoteException ignored) {
3543 }
3544 }
3545 }
3546
3547 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3548 boolean restrictBackground) {
3549 if (listener != null) {
3550 try {
3551 listener.onRestrictBackgroundChanged(restrictBackground);
3552 } catch (RemoteException ignored) {
3553 }
3554 }
3555 }
3556
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003557 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3558 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003559 if (listener != null) {
3560 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003561 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003562 } catch (RemoteException ignored) {
3563 }
3564 }
3565 }
3566
Makoto Onuki8e777332017-03-28 11:25:47 -07003567 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003568 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003569 public boolean handleMessage(Message msg) {
3570 switch (msg.what) {
3571 case MSG_RULES_CHANGED: {
3572 final int uid = msg.arg1;
3573 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003574 final int length = mListeners.beginBroadcast();
3575 for (int i = 0; i < length; i++) {
3576 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3577 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003578 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003579 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003580 return true;
3581 }
3582 case MSG_METERED_IFACES_CHANGED: {
3583 final String[] meteredIfaces = (String[]) msg.obj;
3584 final int length = mListeners.beginBroadcast();
3585 for (int i = 0; i < length; i++) {
3586 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003587 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003588 }
3589 mListeners.finishBroadcast();
3590 return true;
3591 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003592 case MSG_LIMIT_REACHED: {
3593 final String iface = (String) msg.obj;
3594
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003595 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003596 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003597 if (mMeteredIfaces.contains(iface)) {
3598 try {
3599 // force stats update to make sure we have
3600 // numbers that caused alert to trigger.
3601 mNetworkStats.forceUpdate();
3602 } catch (RemoteException e) {
3603 // ignored; service lives in system_server
3604 }
3605
Felipe Lemef0823852016-06-08 13:43:08 -07003606 updateNetworkEnabledNL();
3607 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003608 }
3609 }
3610 return true;
3611 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003612 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3613 final boolean restrictBackground = msg.arg1 != 0;
3614 final int length = mListeners.beginBroadcast();
3615 for (int i = 0; i < length; i++) {
3616 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003617 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003618 }
3619 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003620 final Intent intent =
3621 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3622 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3623 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3624 return true;
3625 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003626 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003627 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003628 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003629 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003630 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003631 final int length = mListeners.beginBroadcast();
3632 for (int i = 0; i < length; i++) {
3633 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003634 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003635 }
3636 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003637 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3638 if (notifyApp.booleanValue()) {
3639 broadcastRestrictBackgroundChanged(uid, notifyApp);
3640 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003641 return true;
3642 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003643 case MSG_ADVISE_PERSIST_THRESHOLD: {
3644 final long lowestRule = (Long) msg.obj;
3645 try {
3646 // make sure stats are recorded frequently enough; we aim
3647 // for 2MB threshold for 2GB/month rules.
3648 final long persistThreshold = lowestRule / 1000;
3649 mNetworkStats.advisePersistThreshold(persistThreshold);
3650 } catch (RemoteException e) {
3651 // ignored; service lives in system_server
3652 }
3653 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003654 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003655 case MSG_UPDATE_INTERFACE_QUOTA: {
3656 removeInterfaceQuota((String) msg.obj);
3657 // int params need to be stitched back into a long
3658 setInterfaceQuota((String) msg.obj,
3659 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3660 return true;
3661 }
3662 case MSG_REMOVE_INTERFACE_QUOTA: {
3663 removeInterfaceQuota((String) msg.obj);
3664 return true;
3665 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003666 case MSG_SET_FIREWALL_RULES: {
3667 final int chain = msg.arg1;
3668 final int toggle = msg.arg2;
3669 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3670 if (uidRules != null) {
3671 setUidFirewallRules(chain, uidRules);
3672 }
3673 if (toggle != CHAIN_TOGGLE_NONE) {
3674 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3675 }
3676 return true;
3677 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003678 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3679 resetUidFirewallRules(msg.arg1);
3680 return true;
3681 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003682 default: {
3683 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003684 }
3685 }
3686 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003687 };
3688
3689 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3690 @Override
3691 public boolean handleMessage(Message msg) {
3692 switch (msg.what) {
3693 case UID_MSG_STATE_CHANGED: {
3694 final int uid = msg.arg1;
3695 final int procState = msg.arg2;
3696 final long procStateSeq = (Long) msg.obj;
3697
3698 handleUidChanged(uid, procState, procStateSeq);
3699 return true;
3700 }
3701 case UID_MSG_GONE: {
3702 final int uid = msg.arg1;
3703 handleUidGone(uid);
3704 return true;
3705 }
3706 default: {
3707 return false;
3708 }
3709 }
3710 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003711
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003712 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003713
Makoto Onuki8e777332017-03-28 11:25:47 -07003714 void handleUidChanged(int uid, int procState, long procStateSeq) {
3715 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3716 try {
3717 synchronized (mUidRulesFirstLock) {
3718 // We received a uid state change callback, add it to the history so that it
3719 // will be useful for debugging.
3720 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3721 // Now update the network policy rules as per the updated uid state.
3722 updateUidStateUL(uid, procState);
3723 // Updating the network rules is done, so notify AMS about this.
3724 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3725 }
3726 } finally {
3727 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3728 }
3729 }
3730
3731 void handleUidGone(int uid) {
3732 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3733 try {
3734 synchronized (mUidRulesFirstLock) {
3735 removeUidStateUL(uid);
3736 }
3737 } finally {
3738 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3739 }
3740 }
3741
Felipe Leme57e3d312016-08-23 14:42:52 -07003742 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3743 final PackageManager pm = mContext.getPackageManager();
3744 final String[] packages = pm.getPackagesForUid(uid);
3745 if (packages != null) {
3746 final int userId = UserHandle.getUserId(uid);
3747 for (String packageName : packages) {
3748 final Intent intent =
3749 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3750 intent.setPackage(packageName);
3751 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3752 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3753 }
3754 }
3755 }
3756
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003757 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003758 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003759 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003760 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003761 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003762 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003763 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003764 }
3765 }
3766
3767 private void removeInterfaceQuota(String iface) {
3768 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003769 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003770 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003771 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003772 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003773 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003774 }
3775 }
3776
Felipe Leme70c57c22016-03-29 10:45:13 -07003777 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3778 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003779 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003780 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003781 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003782 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3783 } catch (RemoteException e) {
3784 // ignored; service lives in system_server
3785 }
3786 }
3787
3788 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3789 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3790 try {
3791 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3792 } catch (IllegalStateException e) {
3793 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003794 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003795 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003796 }
3797 }
3798
Felipe Lemebc853dd2016-09-08 13:26:55 -07003799 private static final int CHAIN_TOGGLE_NONE = 0;
3800 private static final int CHAIN_TOGGLE_ENABLE = 1;
3801 private static final int CHAIN_TOGGLE_DISABLE = 2;
3802 @Retention(RetentionPolicy.SOURCE)
3803 @IntDef(flag = false, value = {
3804 CHAIN_TOGGLE_NONE,
3805 CHAIN_TOGGLE_ENABLE,
3806 CHAIN_TOGGLE_DISABLE
3807 })
3808 public @interface ChainToggleType {
3809 }
3810
3811 /**
3812 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3813 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3814 *
3815 * @param chain firewall chain.
3816 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3817 * @param toggle whether the chain should be enabled, disabled, or not changed.
3818 */
3819 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3820 @ChainToggleType int toggle) {
3821 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3822 }
3823
Amith Yamasani15e472352015-04-24 19:06:07 -07003824 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003825 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3826 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3827 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003828 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003829 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003830 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003831 int size = uidRules.size();
3832 int[] uids = new int[size];
3833 int[] rules = new int[size];
3834 for(int index = size - 1; index >= 0; --index) {
3835 uids[index] = uidRules.keyAt(index);
3836 rules[index] = uidRules.valueAt(index);
3837 }
3838 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003839 } catch (IllegalStateException e) {
3840 Log.wtf(TAG, "problem setting firewall uid rules", e);
3841 } catch (RemoteException e) {
3842 // ignored; service lives in system_server
3843 }
3844 }
3845
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003846 /**
3847 * Add or remove a uid to the firewall blacklist for all network ifaces.
3848 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003849 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003850 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3851 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3852 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003853 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003854 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003855 if (chain == FIREWALL_CHAIN_DOZABLE) {
3856 mUidFirewallDozableRules.put(uid, rule);
3857 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3858 mUidFirewallStandbyRules.put(uid, rule);
3859 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3860 mUidFirewallPowerSaveRules.put(uid, rule);
3861 }
3862
3863 try {
3864 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3865 } catch (IllegalStateException e) {
3866 Log.wtf(TAG, "problem setting firewall uid rules", e);
3867 } catch (RemoteException e) {
3868 // ignored; service lives in system_server
3869 }
3870 } finally {
3871 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003872 }
3873 }
3874
3875 /**
3876 * Add or remove a uid to the firewall blacklist for all network ifaces.
3877 */
Felipe Lemef0823852016-06-08 13:43:08 -07003878 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003879 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3880 mFirewallChainStates.get(chain) == enable) {
3881 // All is the same, nothing to do.
3882 return;
3883 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003884 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003885 try {
3886 mNetworkManager.setFirewallChainEnabled(chain, enable);
3887 } catch (IllegalStateException e) {
3888 Log.wtf(TAG, "problem enable firewall chain", e);
3889 } catch (RemoteException e) {
3890 // ignored; service lives in system_server
3891 }
3892 }
3893
Felipe Leme03e95e22016-09-09 09:25:31 -07003894 /**
3895 * Resets all firewall rules associated with an UID.
3896 */
3897 private void resetUidFirewallRules(int uid) {
3898 try {
3899 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3900 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3901 mNetworkManager
3902 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3903 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3904 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3905 } catch (IllegalStateException e) {
3906 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3907 } catch (RemoteException e) {
3908 // ignored; service lives in system_server
3909 }
3910 }
3911
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003912 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3913 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003914 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003915 } catch (RuntimeException e) {
3916 Slog.w(TAG, "problem reading network stats: " + e);
3917 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003918 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003919 // ignored; service lives in system_server
3920 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003921 }
3922 }
3923
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003924 private boolean isBandwidthControlEnabled() {
3925 final long token = Binder.clearCallingIdentity();
3926 try {
3927 return mNetworkManager.isBandwidthControlEnabled();
3928 } catch (RemoteException e) {
3929 // ignored; service lives in system_server
3930 return false;
3931 } finally {
3932 Binder.restoreCallingIdentity(token);
3933 }
3934 }
3935
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003936 /**
3937 * Try refreshing {@link #mTime} when stale.
3938 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003939 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003940 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003941 mTime.forceRefresh();
3942 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003943 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003944
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003945 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003946 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3947 }
3948
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003949 private static Intent buildAllowBackgroundDataIntent() {
3950 return new Intent(ACTION_ALLOW_BACKGROUND);
3951 }
3952
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003953 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3954 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3955 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3956 return intent;
3957 }
3958
Wei Liu546cb772016-07-21 16:19:01 -07003959 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003960 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003961 intent.setComponent(ComponentName.unflattenFromString(
3962 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003963 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3964 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3965 return intent;
3966 }
3967
Wei Liu546cb772016-07-21 16:19:01 -07003968 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003969 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003970 intent.setComponent(ComponentName.unflattenFromString(
3971 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003972 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3973 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3974 return intent;
3975 }
3976
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003977 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003978 public void addIdleHandler(IdleHandler handler) {
3979 mHandler.getLooper().getQueue().addIdleHandler(handler);
3980 }
3981
jackqdyulei29c82ab2017-03-10 14:09:16 -08003982 @VisibleForTesting
3983 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
3984 mRestrictBackgroundPowerState = result;
3985
3986 boolean restrictBackground = result.batterySaverEnabled;
3987 boolean shouldInvokeRestrictBackground;
3988 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
3989 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
3990
3991 if (result.globalBatterySaverEnabled) {
3992 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
3993 // turn it on.
3994 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
3995 mRestrictBackgroundBeforeBsm = mRestrictBackground;
3996 localRestrictBgChangedInBsm = false;
3997 } else {
3998 // Try to restore the restrictBackground if it doesn't change in bsm
3999 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4000 restrictBackground = mRestrictBackgroundBeforeBsm;
4001 }
4002
4003 if (shouldInvokeRestrictBackground) {
4004 setRestrictBackground(restrictBackground);
4005 }
4006
4007 // Change it at last so setRestrictBackground() won't affect this variable
4008 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4009 }
4010
Jeff Sharkey1b861272011-05-22 00:34:52 -07004011 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4012 final int size = source.size();
4013 for (int i = 0; i < size; i++) {
4014 target.put(source.keyAt(i), true);
4015 }
4016 }
4017
Stuart Scottf1fb3972015-04-02 18:00:02 -07004018 @Override
4019 public void factoryReset(String subscriber) {
4020 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4021
Stuart Scotte3e314d2015-04-20 14:07:45 -07004022 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4023 return;
4024 }
4025
Stuart Scottf1fb3972015-04-02 18:00:02 -07004026 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004027 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004028 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4029 for (NetworkPolicy policy : policies) {
4030 if (policy.template.equals(template)) {
4031 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4032 policy.inferred = false;
4033 policy.clearSnooze();
4034 }
4035 }
4036 setNetworkPolicies(policies);
4037
4038 // Turn restrict background data off
4039 setRestrictBackground(false);
4040
Stuart Scotte3e314d2015-04-20 14:07:45 -07004041 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4042 // Remove app's "restrict background data" flag
4043 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4044 setUidPolicy(uid, POLICY_NONE);
4045 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004046 }
4047 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004048
Felipe Lemed17fda42016-04-29 11:12:45 -07004049 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4050
4051 @Override
4052 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004053 synchronized (mUidRulesFirstLock) {
4054 boolean changed = removeUserStateUL(userId, false);
4055 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004056 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004057 synchronized (mNetworkPoliciesSecondLock) {
4058 writePolicyAL();
4059 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004060 }
4061 }
4062 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004063
4064 /**
4065 * @return true if the given uid is restricted from doing networking on metered networks.
4066 */
4067 @Override
4068 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4069 final int uidRules;
4070 final boolean isBackgroundRestricted;
4071 synchronized (mUidRulesFirstLock) {
4072 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4073 isBackgroundRestricted = mRestrictBackground;
4074 }
4075 return isBackgroundRestricted
4076 && !hasRule(uidRules, RULE_ALLOW_METERED)
4077 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4078 }
4079
4080 /**
4081 * @return true if networking is blocked on the given interface for the given uid according
4082 * to current networking policies.
4083 */
4084 @Override
4085 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4086 final int uidRules;
4087 final boolean isBackgroundRestricted;
4088 final boolean isNetworkMetered;
4089 synchronized (mUidRulesFirstLock) {
4090 uidRules = mUidRules.get(uid, RULE_NONE);
4091 isBackgroundRestricted = mRestrictBackground;
4092 synchronized (mNetworkPoliciesSecondLock) {
4093 isNetworkMetered = mMeteredIfaces.contains(ifname);
4094 }
4095 }
4096 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4097 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4098 return true;
4099 }
4100 if (!isNetworkMetered) {
4101 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4102 return false;
4103 }
4104 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4105 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4106 return true;
4107 }
4108 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4109 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4110 return false;
4111 }
4112 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4113 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4114 return false;
4115 }
4116 if (isBackgroundRestricted) {
4117 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4118 return true;
4119 }
4120 if (LOGV) logUidStatus(uid, "allowed by default");
4121 return false;
4122 }
4123 }
4124
4125 private static boolean hasRule(int uidRules, int rule) {
4126 return (uidRules & rule) != 0;
4127 }
4128
4129 private static void logUidStatus(int uid, String descr) {
4130 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004131 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004132
4133 /**
4134 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4135 * (uid, procStateSeq) pairs.
4136 */
4137 @VisibleForTesting
4138 public static final class ProcStateSeqHistory {
4139 private static final int INVALID_UID = -1;
4140
4141 /**
4142 * Denotes maximum number of items this history can hold.
4143 */
4144 private final int mMaxCapacity;
4145 /**
4146 * Used for storing the uid information.
4147 */
4148 private final int[] mUids;
4149 /**
4150 * Used for storing the sequence numbers associated with {@link #mUids}.
4151 */
4152 private final long[] mProcStateSeqs;
4153 /**
4154 * Points to the next available slot for writing (uid, procStateSeq) pair.
4155 */
4156 private int mHistoryNext;
4157
4158 public ProcStateSeqHistory(int maxCapacity) {
4159 mMaxCapacity = maxCapacity;
4160 mUids = new int[mMaxCapacity];
4161 Arrays.fill(mUids, INVALID_UID);
4162 mProcStateSeqs = new long[mMaxCapacity];
4163 }
4164
4165 @GuardedBy("mUidRulesFirstLock")
4166 public void addProcStateSeqUL(int uid, long procStateSeq) {
4167 mUids[mHistoryNext] = uid;
4168 mProcStateSeqs[mHistoryNext] = procStateSeq;
4169 mHistoryNext = increaseNext(mHistoryNext, 1);
4170 }
4171
4172 @GuardedBy("mUidRulesFirstLock")
4173 public void dumpUL(IndentingPrintWriter fout) {
4174 if (mUids[0] == INVALID_UID) {
4175 fout.println("NONE");
4176 return;
4177 }
4178 int index = mHistoryNext;
4179 do {
4180 index = increaseNext(index, -1);
4181 if (mUids[index] == INVALID_UID) {
4182 break;
4183 }
4184 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4185 } while (index != mHistoryNext);
4186 }
4187
4188 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004189 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004190 }
4191
4192 private int increaseNext(int next, int increment) {
4193 next += increment;
4194 if (next >= mMaxCapacity) {
4195 next = 0;
4196 } else if (next < 0) {
4197 next = mMaxCapacity - 1;
4198 }
4199 return next;
4200 }
4201 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004202
4203 private class NotificationId {
4204 private final String mTag;
4205 private final int mId;
4206
4207 NotificationId(NetworkPolicy policy, int type) {
4208 mTag = buildNotificationTag(policy, type);
4209 mId = type;
4210 }
4211
4212 @Override
4213 public boolean equals(Object o) {
4214 if (this == o) return true;
4215 if (!(o instanceof NotificationId)) return false;
4216 NotificationId that = (NotificationId) o;
4217 return Objects.equals(mTag, that.mTag);
4218 }
4219
4220 @Override
4221 public int hashCode() {
4222 return Objects.hash(mTag);
4223 }
4224
4225 /**
4226 * Build unique tag that identifies an active {@link NetworkPolicy}
4227 * notification of a specific type, like {@link #TYPE_LIMIT}.
4228 */
4229 private String buildNotificationTag(NetworkPolicy policy, int type) {
4230 return TAG + ":" + policy.template.hashCode() + ":" + type;
4231 }
4232
4233 public String getTag() {
4234 return mTag;
4235 }
4236
4237 public int getId() {
4238 return mId;
4239 }
4240 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004241}