blob: 2d27e1d24e9e49e218e2fdceabc3b7496b2b54aa [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 Benichi938ab4f2017-02-11 17:04:43 +0900251 private static final boolean LOGD = true; // UNDO
252 private static final boolean LOGV = true; // UNDO
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700253
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700254 private static final int VERSION_INIT = 1;
255 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700256 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800257 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800258 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800259 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700260 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700261 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700262 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700263 private static final int VERSION_SWITCH_UID = 10;
264 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265
Sudheer Shankae7361852017-03-07 11:51:46 -0800266 /**
267 * Max items written to {@link #ProcStateSeqHistory}.
268 */
269 @VisibleForTesting
270 public static final int MAX_PROC_STATE_SEQ_HISTORY =
271 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
272
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800273 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400274 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800275 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400276 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400278 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700279
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 private static final String TAG_POLICY_LIST = "policy-list";
281 private static final String TAG_NETWORK_POLICY = "network-policy";
282 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700283 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800284 private static final String TAG_WHITELIST = "whitelist";
285 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800286 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700287
288 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700289 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
291 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700292 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700293 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800294 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700295 private static final String ATTR_WARNING_BYTES = "warningBytes";
296 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700297 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800298 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
299 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800300 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700301 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700303 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700304 private static final String ATTR_POLICY = "policy";
305
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800306 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800307 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800308 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800309 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700310
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
312
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700313 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700314 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800315 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800316 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700317 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700318 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
319 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700320 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700321 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700322 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700323
Makoto Onuki8e777332017-03-28 11:25:47 -0700324 private static final int UID_MSG_STATE_CHANGED = 100;
325 private static final int UID_MSG_GONE = 101;
326
Jeff Sharkey75279902011-05-24 18:39:45 -0700327 private final Context mContext;
328 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700329 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700330 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700331 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700332 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700333 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700334 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700335
336 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700337 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700338 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700339 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800340 @GuardedBy("mUidRulesFirstLock")
341 private PowerSaveState mRestrictBackgroundPowerState;
342
343 // Store the status of restrict background before turning on battery saver.
344 // Used to restore mRestrictBackground when battery saver is turned off.
345 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700346
Felipe Lemef0823852016-06-08 13:43:08 -0700347 // See main javadoc for instructions on how to use these locks.
348 final Object mUidRulesFirstLock = new Object();
349 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700350
Felipe Lemef0823852016-06-08 13:43:08 -0700351 @GuardedBy("allLocks") volatile boolean mSystemReady;
352
Felipe Lemef0823852016-06-08 13:43:08 -0700353 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
354 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
355 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800356 // Store whether user flipped restrict background in battery saver mode
357 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700358
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700359 private final boolean mSuppressDefaultPolicy;
360
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700361 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800362 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700363 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800364 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700365
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700366 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700368 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700369 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700370
Felipe Lemef0823852016-06-08 13:43:08 -0700371 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700372 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700373 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700374 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700375 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800376 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700377
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700378 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700379 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700380 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
381
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 /**
383 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700384 * in power save mode, except device idle (doze) still applies.
385 * TODO: An int array might be sufficient
386 */
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700388 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
389
390 /**
391 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800392 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700393 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800394 */
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700396 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700397
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700399 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
400
Felipe Lemeb85a6372016-01-14 16:16:16 -0800401 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800402 * UIDs that have been initially white-listed by system to avoid restricted background.
403 */
Felipe Lemef0823852016-06-08 13:43:08 -0700404 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800405 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
406 new SparseBooleanArray();
407
408 /**
409 * UIDs that have been initially white-listed by system to avoid restricted background,
410 * but later revoked by user.
411 */
Felipe Lemef0823852016-06-08 13:43:08 -0700412 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800413 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
414 new SparseBooleanArray();
415
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700416 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800418 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700419 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800421 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700422
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700423 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700424 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400425 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700426
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700427 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800429 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700430
Jeff Sharkey32566012014-12-02 18:30:14 -0800431 private final RemoteCallbackList<INetworkPolicyListener>
432 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700433
Dianne Hackborn497175b2014-07-01 12:56:08 -0700434 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700435 @VisibleForTesting
436 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700437
438 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700439
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700441 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700442
Svet Ganov16a16892015-04-16 10:32:04 -0700443 private final AppOpsManager mAppOps;
444
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800445 private final IPackageManager mIPm;
446
Sudheer Shankae7361852017-03-07 11:51:46 -0800447 private ActivityManagerInternal mActivityManagerInternal;
448
449 /**
450 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
451 * the uid and procStateSeq will be written to this and will be printed as part of dump.
452 */
453 @VisibleForTesting
454 public ProcStateSeqHistory mObservedHistory
455 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800456
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700457 // TODO: keep whitelist of system-critical services that should never have
458 // rules enforced, such as system, phone, and radio UIDs.
459
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700460 // TODO: migrate notifications to SystemUI
461
Jeff Sharkey75279902011-05-24 18:39:45 -0700462 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700463 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
464 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700465 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
466 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700467 }
468
469 private static File getSystemDir() {
470 return new File(Environment.getDataDirectory(), "system");
471 }
472
473 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700474 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700475 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700476 mContext = checkNotNull(context, "missing context");
477 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700478 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700479 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700480 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700481 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700482 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700483 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700484 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700485 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700486
Amith Yamasani450a16b2013-09-18 16:28:50 -0700487 HandlerThread thread = new HandlerThread(TAG);
488 thread.start();
489 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700490
Makoto Onuki8e777332017-03-28 11:25:47 -0700491 // We create another thread for the UID events, which are more time-critical.
492 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
493 /*allowIo=*/ false);
494 mUidEventThread.start();
495 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
496
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700497 mSuppressDefaultPolicy = suppressDefaultPolicy;
498
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700499 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700500
501 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800502
Felipe Lemed17fda42016-04-29 11:12:45 -0700503 // Expose private service for system components to use.
504 LocalServices.addService(NetworkPolicyManagerInternal.class,
505 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506 }
507
508 public void bindConnectivityManager(IConnectivityManager connManager) {
509 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700510 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700511
Jeff Sharkey497e4432011-06-14 17:27:29 -0700512 public void bindNotificationManager(INotificationManager notifManager) {
513 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
514 }
515
Felipe Lemef0823852016-06-08 13:43:08 -0700516 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700517 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700518 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
519 mPowerSaveWhitelistExceptIdleAppIds.clear();
520 if (whitelist != null) {
521 for (int uid : whitelist) {
522 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
523 }
524 }
525 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700526 mPowerSaveWhitelistAppIds.clear();
527 if (whitelist != null) {
528 for (int uid : whitelist) {
529 mPowerSaveWhitelistAppIds.put(uid, true);
530 }
531 }
532 } catch (RemoteException e) {
533 }
534 }
535
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 /**
537 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
538 * revoke the whitelist.
539 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700540 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800541 */
Felipe Lemef0823852016-06-08 13:43:08 -0700542 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800543 final List<UserInfo> users = mUserManager.getUsers();
544 final int numberUsers = users.size();
545
Felipe Lemea110eec2016-04-29 09:58:06 -0700546 boolean changed = false;
547 for (int i = 0; i < numberUsers; i++) {
548 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700549 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700550 }
551 return changed;
552 }
553
Felipe Lemef0823852016-06-08 13:43:08 -0700554 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700555 final SystemConfig sysConfig = SystemConfig.getInstance();
556 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800557 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
558 boolean changed = false;
559 for (int i = 0; i < allowDataUsage.size(); i++) {
560 final String pkg = allowDataUsage.valueAt(i);
561 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700562 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
563 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800564 final ApplicationInfo app;
565 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700566 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800567 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700568 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
569 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800570 continue;
571 }
572 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700573 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
574 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800575 continue;
576 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700577 final int uid = UserHandle.getUid(userId, app.uid);
578 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
579 if (LOGD)
580 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
581 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800582 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700583 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700584 if (LOGD)
585 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
586 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700587 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700588 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800589 }
590 }
591 return changed;
592 }
593
Felipe Lemef0823852016-06-08 13:43:08 -0700594 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700595 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700596 // Clear the states of the current whitelist
597 final int N = mPowerSaveTempWhitelistAppIds.size();
598 for (int i = 0; i < N; i++) {
599 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
600 }
601 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700602 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700603 if (whitelist != null) {
604 for (int uid : whitelist) {
605 mPowerSaveTempWhitelistAppIds.put(uid, true);
606 }
607 }
608 } catch (RemoteException e) {
609 }
610 }
611
Amith Yamasani06f08062015-06-12 13:23:33 -0700612 /**
613 * Remove unnecessary entries in the temp whitelist
614 */
Felipe Lemef0823852016-06-08 13:43:08 -0700615 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700616 final int N = mPowerSaveTempWhitelistAppIds.size();
617 for (int i = N - 1; i >= 0; i--) {
618 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
619 mPowerSaveTempWhitelistAppIds.removeAt(i);
620 }
621 }
622 }
623
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800624 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800626 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700627 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800628 // Boost thread's priority during system server init
629 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700630 if (!isBandwidthControlEnabled()) {
631 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
632 return;
633 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700634
Felipe Leme873a83a2016-09-07 11:34:10 -0700635 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700636
Felipe Leme873a83a2016-09-07 11:34:10 -0700637 synchronized (mUidRulesFirstLock) {
638 synchronized (mNetworkPoliciesSecondLock) {
639 updatePowerSaveWhitelistUL();
640 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
641 mPowerManagerInternal.registerLowPowerModeObserver(
642 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800643 @Override
644 public int getServiceType() {
645 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700646 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800647
648 @Override
649 public void onLowPowerModeChanged(PowerSaveState result) {
650 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800651 if (LOGD) {
652 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
653 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800654 synchronized (mUidRulesFirstLock) {
655 if (mRestrictPower != enabled) {
656 mRestrictPower = enabled;
657 updateRulesForRestrictPowerUL();
658 }
659 }
660 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800661 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800662 mRestrictPower = mPowerManagerInternal.getLowPowerState(
663 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700664
665 mSystemReady = true;
666
667 // read policy from disk
668 readPolicyAL();
669
jackqdyulei29c82ab2017-03-10 14:09:16 -0800670 // Update the restrictBackground if battery saver is turned on
671 mRestrictBackgroundBeforeBsm = mRestrictBackground;
672 mRestrictBackgroundPowerState = mPowerManagerInternal
673 .getLowPowerState(ServiceType.DATA_SAVER);
674 final boolean localRestrictBackground =
675 mRestrictBackgroundPowerState.batterySaverEnabled;
676 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
677 mRestrictBackground = localRestrictBackground;
678 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
679 mRestrictBackground ? 1 : 0, 0).sendToTarget();
680 }
681 mPowerManagerInternal.registerLowPowerModeObserver(
682 new PowerManagerInternal.LowPowerModeListener() {
683 @Override
684 public int getServiceType() {
685 return ServiceType.DATA_SAVER;
686 }
687
688 @Override
689 public void onLowPowerModeChanged(PowerSaveState result) {
690 synchronized (mUidRulesFirstLock) {
691 updateRestrictBackgroundByLowPowerModeUL(result);
692 }
693 }
694 });
695
Felipe Leme873a83a2016-09-07 11:34:10 -0700696 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
697 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700698 }
Felipe Lemef0823852016-06-08 13:43:08 -0700699
Felipe Leme873a83a2016-09-07 11:34:10 -0700700 setRestrictBackgroundUL(mRestrictBackground);
701 updateRulesForGlobalChangeAL(false);
702 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700703 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800704 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700705
Sudheer Shankae7361852017-03-07 11:51:46 -0800706 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700707 try {
708 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000709 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800710 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700711 mNetworkManager.registerObserver(mAlertObserver);
712 } catch (RemoteException e) {
713 // ignored; both services live in system_server
714 }
715
716 // listen for changes to power save whitelist
717 final IntentFilter whitelistFilter = new IntentFilter(
718 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
719 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
720
721 DeviceIdleController.LocalService deviceIdleService
722 = LocalServices.getService(DeviceIdleController.LocalService.class);
723 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
724
725 // watch for network interfaces to be claimed
726 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
727 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
728
729 // listen for package changes to update policy
730 final IntentFilter packageFilter = new IntentFilter();
731 packageFilter.addAction(ACTION_PACKAGE_ADDED);
732 packageFilter.addDataScheme("package");
733 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
734
735 // listen for UID changes to update policy
736 mContext.registerReceiver(
737 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
738
739 // listen for user changes to update policy
740 final IntentFilter userFilter = new IntentFilter();
741 userFilter.addAction(ACTION_USER_ADDED);
742 userFilter.addAction(ACTION_USER_REMOVED);
743 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
744
745 // listen for stats update events
746 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
747 mContext.registerReceiver(
748 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
749
750 // listen for restrict background changes from notifications
751 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
752 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
753
754 // listen for snooze warning from notifications
755 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
756 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
757 MANAGE_NETWORK_POLICY, mHandler);
758
759 // listen for configured wifi networks to be removed
760 final IntentFilter wifiConfigFilter =
761 new IntentFilter(CONFIGURED_NETWORKS_CHANGED_ACTION);
762 mContext.registerReceiver(mWifiConfigReceiver, wifiConfigFilter, null, mHandler);
763
764 // listen for wifi state changes to catch metered hint
765 final IntentFilter wifiStateFilter = new IntentFilter(
766 WifiManager.NETWORK_STATE_CHANGED_ACTION);
767 mContext.registerReceiver(mWifiStateReceiver, wifiStateFilter, null, mHandler);
768
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700769 // listen for carrier config changes to update data cycle information
770 final IntentFilter carrierConfigFilter = new IntentFilter(
771 ACTION_CARRIER_CONFIG_CHANGED);
772 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
773
Felipe Leme873a83a2016-09-07 11:34:10 -0700774 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800775 // tell systemReady() that the service has been initialized
776 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700777 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800778 // Restore the default priority after init is done
779 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700780 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700781 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700782 }
783
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800784 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
785 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
786 mHandler.post(() -> initService(initCompleteSignal));
787 return initCompleteSignal;
788 }
789
790 public void systemReady(CountDownLatch initCompleteSignal) {
791 // wait for initService to complete
792 try {
793 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
794 throw new IllegalStateException("Service " + TAG +" init timeout");
795 }
796 } catch (InterruptedException e) {
797 Thread.currentThread().interrupt();
798 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
799 }
800 }
801
Sudheer Shankac9d94072017-02-22 22:13:55 +0000802 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Sudheer Shanka80255802017-03-04 14:48:53 -0800803 @Override public void onUidStateChanged(int uid, int procState,
804 long procStateSeq) throws RemoteException {
Makoto Onuki8e777332017-03-28 11:25:47 -0700805 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
806 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700807 }
808
Dianne Hackborne07641d2016-11-09 15:07:23 -0800809 @Override public void onUidGone(int uid, boolean disabled) throws RemoteException {
Makoto Onuki8e777332017-03-28 11:25:47 -0700810 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700811 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700812
813 @Override public void onUidActive(int uid) throws RemoteException {
814 }
815
Dianne Hackborne07641d2016-11-09 15:07:23 -0800816 @Override public void onUidIdle(int uid, boolean disabled) throws RemoteException {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700817 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700818 };
819
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700820 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700821 @Override
822 public void onReceive(Context context, Intent intent) {
823 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700824 synchronized (mUidRulesFirstLock) {
825 updatePowerSaveWhitelistUL();
826 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700827 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700828 }
829 }
830 };
831
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700832 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
833 @Override
834 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700835 synchronized (mUidRulesFirstLock) {
836 updatePowerSaveTempWhitelistUL();
837 updateRulesForTempWhitelistChangeUL();
838 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700839 }
840 }
841 };
842
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700843 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700844 @Override
845 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700846 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700847
848 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700849 final int uid = intent.getIntExtra(EXTRA_UID, -1);
850 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700851
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700852 if (ACTION_PACKAGE_ADDED.equals(action)) {
853 // update rules for UID, since it might be subject to
854 // global background data policy
855 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700856 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700857 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700858 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700859 }
860 }
861 };
862
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700863 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700864 @Override
865 public void onReceive(Context context, Intent intent) {
866 // on background handler thread, and UID_REMOVED is protected
867
868 final int uid = intent.getIntExtra(EXTRA_UID, -1);
869 if (uid == -1) return;
870
871 // remove any policy and update rules to clean up
872 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700873 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700874 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700875 synchronized (mNetworkPoliciesSecondLock) {
876 writePolicyAL();
877 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700878 }
879 }
880 };
881
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700882 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700883 @Override
884 public void onReceive(Context context, Intent intent) {
885 // on background handler thread, and USER_ADDED and USER_REMOVED
886 // broadcasts are protected
887
888 final String action = intent.getAction();
889 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
890 if (userId == -1) return;
891
Amith Yamasani15e472352015-04-24 19:06:07 -0700892 switch (action) {
893 case ACTION_USER_REMOVED:
894 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700895 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800896 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700897 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700898 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700899 if (action == ACTION_USER_ADDED) {
900 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700901 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700902 }
903 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700904 synchronized (mNetworkPoliciesSecondLock) {
905 updateRulesForGlobalChangeAL(true);
906 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700907 }
908 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700909 }
910 }
911 };
912
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700913 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700914 * Receiver that watches for {@link INetworkStatsService} updates, which we
915 * use to check against {@link NetworkPolicy#warningBytes}.
916 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700917 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700918 @Override
919 public void onReceive(Context context, Intent intent) {
920 // on background handler thread, and verified
921 // READ_NETWORK_USAGE_HISTORY permission above.
922
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800923 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700924 synchronized (mNetworkPoliciesSecondLock) {
925 updateNetworkEnabledNL();
926 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 }
928 }
929 };
930
931 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700932 * Receiver that watches for {@link Notification} control of
933 * {@link #mRestrictBackground}.
934 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700935 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700936 @Override
937 public void onReceive(Context context, Intent intent) {
938 // on background handler thread, and verified MANAGE_NETWORK_POLICY
939 // permission above.
940
941 setRestrictBackground(false);
942 }
943 };
944
945 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800946 * Receiver that watches for {@link Notification} control of
947 * {@link NetworkPolicy#lastWarningSnooze}.
948 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700949 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800950 @Override
951 public void onReceive(Context context, Intent intent) {
952 // on background handler thread, and verified MANAGE_NETWORK_POLICY
953 // permission above.
954
955 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
956 performSnooze(template, TYPE_WARNING);
957 }
958 };
959
960 /**
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700961 * Receiver that watches for {@link WifiConfiguration} to be changed.
962 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700963 final private BroadcastReceiver mWifiConfigReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700964 @Override
965 public void onReceive(Context context, Intent intent) {
966 // on background handler thread, and verified CONNECTIVITY_INTERNAL
967 // permission above.
968
969 final int reason = intent.getIntExtra(EXTRA_CHANGE_REASON, CHANGE_REASON_ADDED);
970 if (reason == CHANGE_REASON_REMOVED) {
971 final WifiConfiguration config = intent.getParcelableExtra(
972 EXTRA_WIFI_CONFIGURATION);
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700973 if (config.SSID != null) {
Jeff Sharkey2e4dce02012-12-18 17:06:06 -0800974 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(config.SSID);
Felipe Lemef0823852016-06-08 13:43:08 -0700975 synchronized (mUidRulesFirstLock) {
976 synchronized (mNetworkPoliciesSecondLock) {
977 if (mNetworkPolicy.containsKey(template)) {
978 mNetworkPolicy.remove(template);
979 writePolicyAL();
980 }
Irfan Sheriff00a10a12012-04-27 21:24:17 -0700981 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700982 }
983 }
984 }
985 }
986 };
987
988 /**
989 * Receiver that watches {@link WifiInfo} state changes to infer metered
990 * state. Ignores hints when policy is user-defined.
991 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700992 final private BroadcastReceiver mWifiStateReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700993 @Override
994 public void onReceive(Context context, Intent intent) {
995 // on background handler thread, and verified CONNECTIVITY_INTERNAL
996 // permission above.
997
998 // ignore when not connected
999 final NetworkInfo netInfo = intent.getParcelableExtra(EXTRA_NETWORK_INFO);
1000 if (!netInfo.isConnected()) return;
1001
1002 final WifiInfo info = intent.getParcelableExtra(EXTRA_WIFI_INFO);
1003 final boolean meteredHint = info.getMeteredHint();
1004
Jeff Sharkey2e4dce02012-12-18 17:06:06 -08001005 final NetworkTemplate template = NetworkTemplate.buildTemplateWifi(info.getSSID());
Hugo Benichi446c9c92017-04-10 09:41:10 +09001006 synchronized (mUidRulesFirstLock) {
1007 synchronized (mNetworkPoliciesSecondLock) {
1008 NetworkPolicy policy = mNetworkPolicy.get(template);
1009 if (policy == null && meteredHint) {
1010 // policy doesn't exist, and AP is hinting that it's
1011 // metered: create an inferred policy.
1012 policy = newWifiPolicy(template, meteredHint);
1013 addNetworkPolicyAL(policy);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001014
Hugo Benichi446c9c92017-04-10 09:41:10 +09001015 } else if (policy != null && policy.inferred) {
1016 // policy exists, and was inferred: update its current
1017 // metered state.
1018 policy.metered = meteredHint;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001019
Hugo Benichi446c9c92017-04-10 09:41:10 +09001020 // since this is inferred for each wifi session, just update
1021 // rules without persisting.
1022 updateNetworkRulesNL();
1023 }
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001024 }
1025 }
1026 }
1027 };
1028
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08001029 static NetworkPolicy newWifiPolicy(NetworkTemplate template, boolean metered) {
1030 return new NetworkPolicy(template, CYCLE_NONE, Time.TIMEZONE_UTC,
1031 WARNING_DISABLED, LIMIT_DISABLED, SNOOZE_NEVER, SNOOZE_NEVER,
1032 metered, true);
1033 }
1034
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001035 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001036 * Observer that watches for {@link INetworkManagementService} alerts.
1037 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001038 final private INetworkManagementEventObserver mAlertObserver
1039 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001040 @Override
1041 public void limitReached(String limitName, String iface) {
1042 // only someone like NMS should be calling us
1043 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1044
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001045 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1046 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001047 }
1048 }
1049 };
1050
1051 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001052 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1053 * to show visible notifications as needed.
1054 */
Felipe Lemef0823852016-06-08 13:43:08 -07001055 void updateNotificationsNL() {
1056 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001057
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001058 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001059 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001060 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001061
1062 // TODO: when switching to kernel notifications, compute next future
1063 // cycle boundary to recompute notifications.
1064
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001065 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001066 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001067 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1068 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001069 // ignore policies that aren't relevant to user
1070 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001071 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001072
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 final long start = computeLastCycleBoundary(currentTime, policy);
1074 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001075 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001076
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001077 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001078 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001079 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1080 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001081 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001082 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001083 }
1084
Jeff Sharkey497e4432011-06-14 17:27:29 -07001085 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001086 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001088 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001090 }
1091 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001092 }
1093
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001094 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001095 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001096 final NotificationId notificationId = beforeNotifs.valueAt(i);
1097 if (!mActiveNotifs.contains(notificationId)) {
1098 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001099 }
1100 }
1101 }
1102
1103 /**
1104 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001105 * current device state, such as when
1106 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1107 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001108 */
1109 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001110 if (template.isMatchRuleMobile()) {
1111 final TelephonyManager tele = TelephonyManager.from(mContext);
1112 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001113
Jeff Sharkey32566012014-12-02 18:30:14 -08001114 // Mobile template is relevant when any active subscriber matches
1115 final int[] subIds = sub.getActiveSubscriptionIdList();
1116 for (int subId : subIds) {
1117 final String subscriberId = tele.getSubscriberId(subId);
1118 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001119 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001120 if (template.matches(probeIdent)) {
1121 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001122 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001123 }
1124 return false;
1125 } else {
1126 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001128 }
1129
1130 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131 * Notify that given {@link NetworkTemplate} is over
1132 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1133 */
Felipe Lemef0823852016-06-08 13:43:08 -07001134 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001135 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001136 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 mOverLimitNotified.add(template);
1138 }
1139 }
1140
Felipe Lemef0823852016-06-08 13:43:08 -07001141 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001142 mOverLimitNotified.remove(template);
1143 }
1144
1145 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146 * Show notification for combined {@link NetworkPolicy} and specific type,
1147 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1148 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001150 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001151 final Notification.Builder builder =
1152 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001153 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001154 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001155 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001156 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001157
1158 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001159 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 switch (type) {
1161 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001162 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001163 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001165 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001166 builder.setTicker(title);
1167 builder.setContentTitle(title);
1168 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001169 builder.setDefaults(Notification.DEFAULT_ALL);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001170 builder.setChannel(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001171
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001172 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1173 builder.setDeleteIntent(PendingIntent.getBroadcast(
1174 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1175
Wei Liu546cb772016-07-21 16:19:01 -07001176 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001177 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001178 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1179
Jeff Sharkey497e4432011-06-14 17:27:29 -07001180 break;
1181 }
1182 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001183 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001184
1185 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001186 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001187 switch (policy.template.getMatchRule()) {
1188 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001189 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001190 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001191 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001192 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001193 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001194 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001196 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001197 case MATCH_WIFI:
1198 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001199 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001200 break;
1201 default:
1202 title = null;
1203 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001204 }
1205
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001206 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001207 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001208 builder.setTicker(title);
1209 builder.setContentTitle(title);
1210 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001211
Wei Liu546cb772016-07-21 16:19:01 -07001212 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001213 builder.setContentIntent(PendingIntent.getActivity(
1214 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1215 break;
1216 }
1217 case TYPE_LIMIT_SNOOZED: {
1218 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001219 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001220 Formatter.formatFileSize(mContext, overBytes));
1221
1222 final CharSequence title;
1223 switch (policy.template.getMatchRule()) {
1224 case MATCH_MOBILE_3G_LOWER:
1225 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1226 break;
1227 case MATCH_MOBILE_4G:
1228 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1229 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001230 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001231 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1232 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001233 case MATCH_WIFI:
1234 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1235 break;
1236 default:
1237 title = null;
1238 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001239 }
1240
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001241 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001242 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001243 builder.setTicker(title);
1244 builder.setContentTitle(title);
1245 builder.setContentText(body);
1246
Wei Liu546cb772016-07-21 16:19:01 -07001247 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001248 builder.setContentIntent(PendingIntent.getActivity(
1249 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001250 break;
1251 }
1252 }
1253
1254 // TODO: move to NotificationManager once we can mock it
1255 try {
1256 final String packageName = mContext.getPackageName();
1257 final int[] idReceived = new int[1];
Chris Wren193ae6b2017-03-31 15:17:11 -04001258 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001259 builder.setStyle(new Notification.BigTextStyle()
1260 .bigText(body));
1261 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001262 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001263 packageName, packageName, notificationId.getTag(), notificationId.getId(),
1264 builder.build(), idReceived, UserHandle.USER_ALL);
1265 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001266 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001267 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001268 }
1269 }
1270
Chris Wren193ae6b2017-03-31 15:17:11 -04001271 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001272 // TODO: move to NotificationManager once we can mock it
1273 try {
1274 final String packageName = mContext.getPackageName();
1275 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001276 packageName, notificationId.getTag(), notificationId.getId(),
1277 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001278 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001279 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001280 }
1281 }
1282
1283 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001284 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001285 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001286 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001287 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001288 @Override
1289 public void onReceive(Context context, Intent intent) {
1290 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1291 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001292
1293 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001294 synchronized (mUidRulesFirstLock) {
1295 synchronized (mNetworkPoliciesSecondLock) {
1296 ensureActiveMobilePolicyAL();
1297 normalizePoliciesNL();
1298 updateNetworkEnabledNL();
1299 updateNetworkRulesNL();
1300 updateNotificationsNL();
1301 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001302 }
1303 }
1304 };
1305
1306 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001307 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1308 * if necessary.
1309 *
1310 * @param subId that has its associated NetworkPolicy updated if necessary
1311 * @return if any policies were updated
1312 */
1313 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1314 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1315 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1316
1317 if (config == null) {
1318 return false;
1319 }
1320
1321 boolean policyUpdated = false;
1322 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1323
1324 // find and update the mobile NetworkPolicy for this subscriber id
1325 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1326 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1327 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1328 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1329 if (template.matches(probeIdent)) {
1330 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1331
1332 // only update the policy if the user didn't change any of the defaults.
1333 if (!policy.inferred) {
1334 // TODO: inferred could be split, so that if a user changes their data limit or
1335 // warning, it doesn't prevent their cycle date from being updated.
1336 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1337 continue;
1338 }
1339
1340 final int cycleDay = getCycleDayFromCarrierConfig(config, policy.cycleDay);
1341 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1342 policy.warningBytes);
1343 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1344 policy.limitBytes);
1345
1346 if (policy.cycleDay == cycleDay &&
1347 policy.warningBytes == warningBytes &&
1348 policy.limitBytes == limitBytes) {
1349 continue;
1350 }
1351
1352 policyUpdated = true;
1353 policy.cycleDay = cycleDay;
1354 policy.warningBytes = warningBytes;
1355 policy.limitBytes = limitBytes;
1356
1357 if (LOGD) {
1358 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1359 + NetworkIdentity.scrubSubscriberId(subscriberId)
1360 + " from CarrierConfigManager");
1361 }
1362 }
1363 }
1364
1365 return policyUpdated;
1366 }
1367
1368 /**
1369 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1370 *
1371 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1372 * to do so, it returns the fallback value.
1373 *
1374 * @param config The CarrierConfig to read the value from.
1375 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1376 * @return cycleDay to use in the mobile NetworkPolicy.
1377 */
1378 @VisibleForTesting
1379 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1380 int fallbackCycleDay) {
1381 if (config == null) {
1382 return fallbackCycleDay;
1383 }
1384 int cycleDay =
1385 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1386 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1387 return fallbackCycleDay;
1388 }
1389 // validate cycleDay value
1390 final Calendar cal = Calendar.getInstance();
1391 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1392 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1393 Slog.e(TAG, "Invalid date in "
1394 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1395 return fallbackCycleDay;
1396 }
1397 return cycleDay;
1398 }
1399
1400 /**
1401 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1402 *
1403 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1404 * to do so, it returns the fallback value.
1405 *
1406 * @param config The CarrierConfig to read the value from.
1407 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1408 * @return warningBytes to use in the mobile NetworkPolicy.
1409 */
1410 @VisibleForTesting
1411 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1412 long fallbackWarningBytes) {
1413 if (config == null) {
1414 return fallbackWarningBytes;
1415 }
1416 long warningBytes =
1417 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1418
1419 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1420 return WARNING_DISABLED;
1421 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1422 return getPlatformDefaultWarningBytes();
1423 } else if (warningBytes < 0) {
1424 Slog.e(TAG, "Invalid value in "
1425 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1426 + "non-negative value but got: " + warningBytes);
1427 return fallbackWarningBytes;
1428 }
1429
1430 return warningBytes;
1431 }
1432
1433 /**
1434 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1435 *
1436 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1437 * to do so, it returns the fallback value.
1438 *
1439 * @param config The CarrierConfig to read the value from.
1440 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1441 * @return limitBytes to use in the mobile NetworkPolicy.
1442 */
1443 @VisibleForTesting
1444 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1445 long fallbackLimitBytes) {
1446 if (config == null) {
1447 return fallbackLimitBytes;
1448 }
1449 long limitBytes =
1450 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1451
1452 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1453 return LIMIT_DISABLED;
1454 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1455 return getPlatformDefaultLimitBytes();
1456 } else if (limitBytes < 0) {
1457 Slog.e(TAG, "Invalid value in "
1458 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1459 + "non-negative value but got: " + limitBytes);
1460 return fallbackLimitBytes;
1461 }
1462 return limitBytes;
1463 }
1464
1465 /**
1466 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1467 */
1468 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1469 @Override
1470 public void onReceive(Context context, Intent intent) {
1471 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1472 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1473
1474 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1475 return;
1476 }
1477 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1478 final TelephonyManager tele = TelephonyManager.from(mContext);
1479 final String subscriberId = tele.getSubscriberId(subId);
1480
1481 maybeRefreshTrustedTime();
1482 synchronized (mUidRulesFirstLock) {
1483 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001484 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001485 if (added) return;
1486 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1487 if (!updated) return;
1488 // update network and notification rules, as the data cycle changed and it's
1489 // possible that we should be triggering warnings/limits now
1490 handleNetworkPoliciesUpdateAL(true);
1491 }
1492 }
1493 }
1494 };
1495
1496 /**
1497 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1498 * one has been updated.
1499 *
1500 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1501 * update.
1502 */
1503 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1504 if (shouldNormalizePolicies) {
1505 normalizePoliciesNL();
1506 }
1507 updateNetworkEnabledNL();
1508 updateNetworkRulesNL();
1509 updateNotificationsNL();
1510 writePolicyAL();
1511 }
1512
1513 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001514 * Proactively control network data connections when they exceed
1515 * {@link NetworkPolicy#limitBytes}.
1516 */
Felipe Lemef0823852016-06-08 13:43:08 -07001517 void updateNetworkEnabledNL() {
1518 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001519
1520 // TODO: reset any policy-disabled networks when any policy is removed
1521 // completely, which is currently rare case.
1522
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001523 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001524 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1525 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001526 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001527 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001528 setNetworkTemplateEnabled(policy.template, true);
1529 continue;
1530 }
1531
1532 final long start = computeLastCycleBoundary(currentTime, policy);
1533 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001534 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001535
1536 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001537 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1538 && policy.lastLimitSnooze < start;
1539 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001540
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001541 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001542 }
1543 }
1544
1545 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001546 * Proactively disable networks that match the given
1547 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001548 */
1549 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001550 // TODO: reach into ConnectivityManager to proactively disable bringing
1551 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001552
1553 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1554 // If mobile data usage hits the limit or if the user resumes the data, we need to
1555 // notify telephony.
1556 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1557 final TelephonyManager tm = TelephonyManager.from(mContext);
1558
1559 final int[] subIds = sm.getActiveSubscriptionIdList();
1560 for (int subId : subIds) {
1561 final String subscriberId = tm.getSubscriberId(subId);
1562 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1563 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1564 // Template is matched when subscriber id matches.
1565 if (template.matches(probeIdent)) {
1566 tm.setPolicyDataEnabled(enabled, subId);
1567 }
1568 }
1569 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001570 }
1571
1572 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 * Examine all connected {@link NetworkState}, looking for
1574 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1575 * remaining quota based on usage cycle and historical stats.
1576 */
Felipe Lemef0823852016-06-08 13:43:08 -07001577 void updateNetworkRulesNL() {
1578 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579
1580 final NetworkState[] states;
1581 try {
1582 states = mConnManager.getAllNetworkState();
1583 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001584 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 return;
1586 }
1587
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001588 // First, generate identities of all connected networks so we can
1589 // quickly compare them against all defined policies below.
1590 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001591 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001592 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001593 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001594 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001595
1596 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001597 if (baseIface != null) {
1598 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001599 }
1600
1601 // Stacked interfaces are considered to have same identity as
1602 // their parent network.
1603 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1604 for (LinkProperties stackedLink : stackedLinks) {
1605 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001606 if (stackedIface != null) {
1607 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001608 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001609 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610 }
1611 }
1612
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001613 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001614 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001615 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001616 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001617 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001618
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001619 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001620 for (int j = connIdents.size() - 1; j >= 0; j--) {
1621 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1622 if (policy.template.matches(ident.second)) {
1623 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001624 }
1625 }
1626
1627 if (ifaceList.size() > 0) {
1628 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001629 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001630 }
1631 }
1632
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001633 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001634 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001635
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001636 // apply each policy that we found ifaces for; compute remaining data
1637 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001638 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001639 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1640 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1641 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001642
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001643 final long start;
1644 final long totalBytes;
1645 if (policy.hasCycle()) {
1646 start = computeLastCycleBoundary(currentTime, policy);
1647 totalBytes = getTotalBytes(policy.template, start, currentTime);
1648 } else {
1649 start = Long.MAX_VALUE;
1650 totalBytes = 0;
1651 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001652
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001653 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001654 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001655 }
1656
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001657 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001658 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001659 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001660 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001661 if (!hasLimit) {
1662 // metered network, but no policy limit; we still need to
1663 // restrict apps, so push really high quota.
1664 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001665 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001666 // snoozing past quota, but we still need to restrict apps,
1667 // so push really high quota.
1668 quotaBytes = Long.MAX_VALUE;
1669 } else {
1670 // remaining "quota" bytes are based on total usage in
1671 // current cycle. kernel doesn't like 0-byte rules, so we
1672 // set 1-byte quota and disable the radio later.
1673 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1674 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001675
1676 if (ifaces.length > 1) {
1677 // TODO: switch to shared quota once NMS supports
1678 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001679 }
1680
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001681 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001682 // long quotaBytes split up into two ints to fit in message
1683 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1684 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1685 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001686 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001687 }
1688 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001689
1690 // keep track of lowest warning or limit of active policies
1691 if (hasWarning && policy.warningBytes < lowestRule) {
1692 lowestRule = policy.warningBytes;
1693 }
1694 if (hasLimit && policy.limitBytes < lowestRule) {
1695 lowestRule = policy.limitBytes;
1696 }
1697 }
1698
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001699 for (int i = connIfaces.size()-1; i >= 0; i--) {
1700 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001701 // long quotaBytes split up into two ints to fit in message
1702 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1703 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1704 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001705 newMeteredIfaces.add(iface);
1706 }
1707
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001708 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001709
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001710 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001711 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1712 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001713 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001714 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1715 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001716 }
1717 }
1718 mMeteredIfaces = newMeteredIfaces;
1719
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001720 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001721 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001722 }
1723
1724 /**
1725 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1726 * have at least a default mobile policy defined.
1727 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001728 private void ensureActiveMobilePolicyAL() {
1729 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001730 if (mSuppressDefaultPolicy) return;
1731
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001732 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001733 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001734
Jeff Sharkey32566012014-12-02 18:30:14 -08001735 final int[] subIds = sub.getActiveSubscriptionIdList();
1736 for (int subId : subIds) {
1737 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001738 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001739 }
1740 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001741
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001742 /**
1743 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1744 * have at least a default mobile policy defined.
1745 *
1746 * @param subId to build a default policy for
1747 * @param subscriberId that we check for an existing policy
1748 * @return true if a mobile network policy was added, or false one already existed.
1749 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001750 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001751 // Poke around to see if we already have a policy
1752 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001753 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001754 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1755 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1756 if (template.matches(probeIdent)) {
1757 if (LOGD) {
1758 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1759 + NetworkIdentity.scrubSubscriberId(subscriberId));
1760 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001761 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001762 }
1763 }
1764
Jeff Sharkey32566012014-12-02 18:30:14 -08001765 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1766 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001767 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001768 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001769 return true;
1770 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001771
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001772 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001773 final int dataWarningConfig = mContext.getResources().getInteger(
1774 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001775 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001776 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001777 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001778 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001779 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001780 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001781
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001782 private long getPlatformDefaultLimitBytes() {
1783 return LIMIT_DISABLED;
1784 }
1785
1786 @VisibleForTesting
1787 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1788 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1789
1790 // assume usage cycle starts today
Jeff Sharkey32566012014-12-02 18:30:14 -08001791 final Time time = new Time();
1792 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001793
Jeff Sharkey32566012014-12-02 18:30:14 -08001794 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001795
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001796 final int cycleDay = getCycleDayFromCarrierConfig(config, time.monthDay);
1797 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1798 getPlatformDefaultWarningBytes());
1799 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1800 getPlatformDefaultLimitBytes());
1801
Jeff Sharkey32566012014-12-02 18:30:14 -08001802 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1803 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001804 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1805 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001806 }
1807
Felipe Lemef0823852016-06-08 13:43:08 -07001808 private void readPolicyAL() {
1809 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001810
1811 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001812 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001813 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001814
1815 FileInputStream fis = null;
1816 try {
1817 fis = mPolicyFile.openRead();
1818 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001819 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001820
Felipe Leme46b451f2016-08-19 08:46:17 -07001821 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1822 // to skip UIDs that were explicitly blacklisted.
1823 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1824
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001825 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001826 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001827 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001828 while ((type = in.next()) != END_DOCUMENT) {
1829 final String tag = in.getName();
1830 if (type == START_TAG) {
1831 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001832 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001833 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001834 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1835 mRestrictBackground = readBooleanAttribute(
1836 in, ATTR_RESTRICT_BACKGROUND);
1837 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001838 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001839 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001840 if (mRestrictBackground != oldValue) {
1841 // Some early services may have read the default value,
1842 // so notify them that it's changed
1843 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1844 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1845 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001846
1847 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1848 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1849 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001850 final String networkId;
1851 if (version >= VERSION_ADDED_NETWORK_ID) {
1852 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1853 } else {
1854 networkId = null;
1855 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001856 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001857 final String cycleTimezone;
1858 if (version >= VERSION_ADDED_TIMEZONE) {
1859 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1860 } else {
1861 cycleTimezone = Time.TIMEZONE_UTC;
1862 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001863 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1864 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001865 final long lastLimitSnooze;
1866 if (version >= VERSION_SPLIT_SNOOZE) {
1867 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1868 } else if (version >= VERSION_ADDED_SNOOZE) {
1869 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001870 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001871 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001872 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001873 final boolean metered;
1874 if (version >= VERSION_ADDED_METERED) {
1875 metered = readBooleanAttribute(in, ATTR_METERED);
1876 } else {
1877 switch (networkTemplate) {
1878 case MATCH_MOBILE_3G_LOWER:
1879 case MATCH_MOBILE_4G:
1880 case MATCH_MOBILE_ALL:
1881 metered = true;
1882 break;
1883 default:
1884 metered = false;
1885 }
1886 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001887 final long lastWarningSnooze;
1888 if (version >= VERSION_SPLIT_SNOOZE) {
1889 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1890 } else {
1891 lastWarningSnooze = SNOOZE_NEVER;
1892 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001893 final boolean inferred;
1894 if (version >= VERSION_ADDED_INFERRED) {
1895 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1896 } else {
1897 inferred = false;
1898 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001899
Jeff Sharkey32566012014-12-02 18:30:14 -08001900 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1901 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001902 if (template.isPersistable()) {
1903 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1904 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1905 lastLimitSnooze, metered, inferred));
1906 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001907
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001908 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001909 final int uid = readIntAttribute(in, ATTR_UID);
1910 final int policy = readIntAttribute(in, ATTR_POLICY);
1911
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001912 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001913 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001914 } else {
1915 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1916 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001917 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001918 final int appId = readIntAttribute(in, ATTR_APP_ID);
1919 final int policy = readIntAttribute(in, ATTR_POLICY);
1920
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001921 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001922 // app policy is deprecated so this is only used in pre system user split.
1923 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001924 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001925 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001926 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001927 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001928 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001929 } else if (TAG_WHITELIST.equals(tag)) {
1930 insideWhitelist = true;
1931 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1932 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001933 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001934 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1935 final int uid = readIntAttribute(in, ATTR_UID);
1936 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001937 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001938 } else if (type == END_TAG) {
1939 if (TAG_WHITELIST.equals(tag)) {
1940 insideWhitelist = false;
1941 }
1942
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001943 }
1944 }
1945
Felipe Leme46b451f2016-08-19 08:46:17 -07001946 final int size = whitelistedRestrictBackground.size();
1947 for (int i = 0; i < size; i++) {
1948 final int uid = whitelistedRestrictBackground.keyAt(i);
1949 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1950 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1951 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1952 + " because its policy is " + uidPoliciesToString(policy));
1953 continue;
1954 }
1955 if (UserHandle.isApp(uid)) {
1956 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1957 if (LOGV)
1958 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1959 setUidPolicyUncheckedUL(uid, newPolicy, false);
1960 } else {
1961 Slog.w(TAG, "unable to update policy on UID " + uid);
1962 }
1963 }
1964
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001965 } catch (FileNotFoundException e) {
1966 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001967 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001968 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001969 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001970 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001971 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001972 } finally {
1973 IoUtils.closeQuietly(fis);
1974 }
1975 }
1976
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001977 /**
1978 * Upgrade legacy background data flags, notifying listeners of one last
1979 * change to always-true.
1980 */
Felipe Lemef0823852016-06-08 13:43:08 -07001981 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001982 mRestrictBackground = Settings.Secure.getInt(
1983 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1984
1985 // kick off one last broadcast if restricted
1986 if (mRestrictBackground) {
1987 final Intent broadcast = new Intent(
1988 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001989 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001990 }
1991 }
1992
Felipe Lemef0823852016-06-08 13:43:08 -07001993 void writePolicyAL() {
1994 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001995
1996 FileOutputStream fos = null;
1997 try {
1998 fos = mPolicyFile.startWrite();
1999
2000 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002001 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002002 out.startDocument(null, true);
2003
2004 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002005 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002006 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002007
2008 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002009 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2010 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002011 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002012 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002013
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002014 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002015 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2016 final String subscriberId = template.getSubscriberId();
2017 if (subscriberId != null) {
2018 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002019 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002020 final String networkId = template.getNetworkId();
2021 if (networkId != null) {
2022 out.attribute(null, ATTR_NETWORK_ID, networkId);
2023 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002024 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08002025 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002026 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2027 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002028 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2029 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002030 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002031 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002032 out.endTag(null, TAG_NETWORK_POLICY);
2033 }
2034
2035 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002036 for (int i = 0; i < mUidPolicy.size(); i++) {
2037 final int uid = mUidPolicy.keyAt(i);
2038 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002039
Jeff Sharkey497e4432011-06-14 17:27:29 -07002040 // skip writing empty policies
2041 if (policy == POLICY_NONE) continue;
2042
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002043 out.startTag(null, TAG_UID_POLICY);
2044 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002045 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002046 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002047 }
2048
2049 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002050
2051 // write all whitelists
2052 out.startTag(null, TAG_WHITELIST);
2053
Felipe Lemea9505cc2016-02-26 10:28:41 -08002054 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002055 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002056 for (int i = 0; i < size; i++) {
2057 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2058 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2059 writeIntAttribute(out, ATTR_UID, uid);
2060 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2061 }
2062
Felipe Lemeb85a6372016-01-14 16:16:16 -08002063 out.endTag(null, TAG_WHITELIST);
2064
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002065 out.endDocument();
2066
2067 mPolicyFile.finishWrite(fos);
2068 } catch (IOException e) {
2069 if (fos != null) {
2070 mPolicyFile.failWrite(fos);
2071 }
2072 }
2073 }
2074
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002075 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002076 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002077 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002078
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002079 if (!UserHandle.isApp(uid)) {
2080 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002081 }
Felipe Lemef0823852016-06-08 13:43:08 -07002082 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002083 final long token = Binder.clearCallingIdentity();
2084 try {
2085 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2086 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002087 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002088 }
2089 } finally {
2090 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002091 }
2092 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002093 }
2094
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002095 @Override
2096 public void addUidPolicy(int uid, int policy) {
2097 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002098
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002099 if (!UserHandle.isApp(uid)) {
2100 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2101 }
2102
Felipe Lemef0823852016-06-08 13:43:08 -07002103 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002104 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2105 policy |= oldPolicy;
2106 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002107 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002108 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002109 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002110 }
2111
2112 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002113 public void removeUidPolicy(int uid, int policy) {
2114 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2115
2116 if (!UserHandle.isApp(uid)) {
2117 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2118 }
2119
Felipe Lemef0823852016-06-08 13:43:08 -07002120 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002121 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2122 policy = oldPolicy & ~policy;
2123 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002124 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002125 }
2126 }
2127 }
2128
Felipe Lemef0823852016-06-08 13:43:08 -07002129 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2130 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002131
Felipe Leme57e3d312016-08-23 14:42:52 -07002132 final boolean notifyApp;
2133 if (!isUidValidForWhitelistRules(uid)) {
2134 notifyApp = false;
2135 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002136 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2137 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2138 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2139 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002140 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2141 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002142 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2143 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2144 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2145 if (LOGD)
2146 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2147 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2148 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002149 notifyApp = wasBlocked != isBlocked;
2150 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002151 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2152 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002153 }
2154
Felipe Lemef0823852016-06-08 13:43:08 -07002155 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002156 if (policy == POLICY_NONE) {
2157 mUidPolicy.delete(uid);
2158 } else {
2159 mUidPolicy.put(uid, policy);
2160 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002161
2162 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002163 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002164 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002165 synchronized (mNetworkPoliciesSecondLock) {
2166 writePolicyAL();
2167 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002168 }
2169 }
2170
2171 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002172 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002173 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2174
Felipe Lemef0823852016-06-08 13:43:08 -07002175 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002176 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002177 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002178 }
2179
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002180 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002181 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002182 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2183
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002184 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002185 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002186 for (int i = 0; i < mUidPolicy.size(); i++) {
2187 final int uid = mUidPolicy.keyAt(i);
2188 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002189 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2190 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002191 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002192 }
2193 }
2194 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002195 return uids;
2196 }
2197
2198 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002199 * Removes any persistable state associated with given {@link UserHandle}, persisting
2200 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002201 */
Felipe Lemef0823852016-06-08 13:43:08 -07002202 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002203
Felipe Lemef0823852016-06-08 13:43:08 -07002204 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002205 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002206
Felipe Lemea110eec2016-04-29 09:58:06 -07002207 // Remove entries from revoked default restricted background UID whitelist
2208 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2209 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2210 if (UserHandle.getUserId(uid) == userId) {
2211 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002212 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002213 }
2214 }
2215
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002216 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002217 int[] uids = new int[0];
2218 for (int i = 0; i < mUidPolicy.size(); i++) {
2219 final int uid = mUidPolicy.keyAt(i);
2220 if (UserHandle.getUserId(uid) == userId) {
2221 uids = appendInt(uids, uid);
2222 }
2223 }
2224
2225 if (uids.length > 0) {
2226 for (int uid : uids) {
2227 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002228 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002229 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002230 }
Felipe Lemef0823852016-06-08 13:43:08 -07002231 synchronized (mNetworkPoliciesSecondLock) {
2232 updateRulesForGlobalChangeAL(true);
2233 if (writePolicy && changed) {
2234 writePolicyAL();
2235 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002236 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002237 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002238 }
2239
2240 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002241 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002242 // TODO: create permission for observing network policy
2243 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002244 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002245 }
2246
2247 @Override
2248 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002249 // TODO: create permission for observing network policy
2250 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002251 mListeners.unregister(listener);
2252 }
2253
Jeff Sharkey1b861272011-05-22 00:34:52 -07002254 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002255 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002256 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2257
Felipe Leme6a05eee2016-02-19 14:43:51 -08002258 final long token = Binder.clearCallingIdentity();
2259 try {
2260 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002261 synchronized (mUidRulesFirstLock) {
2262 synchronized (mNetworkPoliciesSecondLock) {
2263 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002264 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002265 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002266 }
2267 } finally {
2268 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002269 }
2270 }
2271
Hugo Benichi446c9c92017-04-10 09:41:10 +09002272 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002273 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002274 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2275 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002276 }
2277
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002278 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002279 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002280 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002281 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002282 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2283 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2284 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002285 } catch (SecurityException e) {
2286 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002287
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002288 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2289 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2290 return new NetworkPolicy[0];
2291 }
Svet Ganov16a16892015-04-16 10:32:04 -07002292 }
2293
Felipe Lemef0823852016-06-08 13:43:08 -07002294 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002295 final int size = mNetworkPolicy.size();
2296 final NetworkPolicy[] policies = new NetworkPolicy[size];
2297 for (int i = 0; i < size; i++) {
2298 policies[i] = mNetworkPolicy.valueAt(i);
2299 }
2300 return policies;
2301 }
2302 }
2303
Felipe Lemef0823852016-06-08 13:43:08 -07002304 private void normalizePoliciesNL() {
2305 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002306 }
2307
Felipe Lemef0823852016-06-08 13:43:08 -07002308 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002309 final TelephonyManager tele = TelephonyManager.from(mContext);
2310 final String[] merged = tele.getMergedSubscriberIds();
2311
2312 mNetworkPolicy.clear();
2313 for (NetworkPolicy policy : policies) {
2314 // When two normalized templates conflict, prefer the most
2315 // restrictive policy
2316 policy.template = NetworkTemplate.normalize(policy.template, merged);
2317 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2318 if (existing == null || existing.compareTo(policy) > 0) {
2319 if (existing != null) {
2320 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2321 }
2322 mNetworkPolicy.put(policy.template, policy);
2323 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002324 }
2325 }
2326
2327 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002328 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002329 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002330
2331 final long token = Binder.clearCallingIdentity();
2332 try {
2333 performSnooze(template, TYPE_LIMIT);
2334 } finally {
2335 Binder.restoreCallingIdentity(token);
2336 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002337 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002338
Dianne Hackborn497175b2014-07-01 12:56:08 -07002339 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002340 maybeRefreshTrustedTime();
2341 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002342 synchronized (mUidRulesFirstLock) {
2343 synchronized (mNetworkPoliciesSecondLock) {
2344 // find and snooze local policy that matches
2345 final NetworkPolicy policy = mNetworkPolicy.get(template);
2346 if (policy == null) {
2347 throw new IllegalArgumentException("unable to find policy for " + template);
2348 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002349
Felipe Lemef0823852016-06-08 13:43:08 -07002350 switch (type) {
2351 case TYPE_WARNING:
2352 policy.lastWarningSnooze = currentTime;
2353 break;
2354 case TYPE_LIMIT:
2355 policy.lastLimitSnooze = currentTime;
2356 break;
2357 default:
2358 throw new IllegalArgumentException("unexpected type");
2359 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002360
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002361 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002362 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002363 }
2364 }
2365
2366 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002367 public void onTetheringChanged(String iface, boolean tethering) {
2368 // No need to enforce permission because setRestrictBackground() will do it.
2369 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002370 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002371 if (mRestrictBackground && tethering) {
2372 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2373 setRestrictBackground(false);
2374 }
2375 }
2376 }
2377
2378 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002379 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002380 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002381 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002382 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2383 final long token = Binder.clearCallingIdentity();
2384 try {
2385 maybeRefreshTrustedTime();
2386 synchronized (mUidRulesFirstLock) {
2387 if (restrictBackground == mRestrictBackground) {
2388 // Ideally, UI should never allow this scenario...
2389 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2390 return;
2391 }
2392 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002393 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002394
2395 } finally {
2396 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002397 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002398
Felipe Leme29e72ea2016-09-08 13:26:55 -07002399 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2400 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002401 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002402 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002403 }
2404 }
2405
Felipe Lemef0823852016-06-08 13:43:08 -07002406 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002407 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002408 final boolean oldRestrictBackground = mRestrictBackground;
2409 mRestrictBackground = restrictBackground;
2410 // Must whitelist foreground apps before turning data saver mode on.
2411 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2412 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002413 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002414 try {
2415 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2416 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2417 mRestrictBackground = oldRestrictBackground;
2418 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002419 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002420 return;
2421 }
2422 } catch (RemoteException e) {
2423 // ignored; service lives in system_server
2424 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002425
2426 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2427 mRestrictBackgroundChangedInBsm = true;
2428 }
Felipe Lemef0823852016-06-08 13:43:08 -07002429 synchronized (mNetworkPoliciesSecondLock) {
2430 updateNotificationsNL();
2431 writePolicyAL();
2432 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002433 }
2434
Felipe Lemeb85a6372016-01-14 16:16:16 -08002435 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002436 public int getRestrictBackgroundByCaller() {
2437 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2438 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002439
Felipe Lemef0823852016-06-08 13:43:08 -07002440 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002441 // Must clear identity because getUidPolicy() is restricted to system.
2442 final long token = Binder.clearCallingIdentity();
2443 final int policy;
2444 try {
2445 policy = getUidPolicy(uid);
2446 } finally {
2447 Binder.restoreCallingIdentity(token);
2448 }
2449 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2450 // App is blacklisted.
2451 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2452 }
Felipe Leme1b103232016-01-22 09:44:57 -08002453 if (!mRestrictBackground) {
2454 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2455 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002456 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002457 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2458 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2459 }
2460 }
2461
2462 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002463 public boolean getRestrictBackground() {
2464 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2465
Felipe Lemef0823852016-06-08 13:43:08 -07002466 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002467 return mRestrictBackground;
2468 }
2469 }
2470
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002471 @Override
2472 public void setDeviceIdleMode(boolean enabled) {
2473 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002474 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2475 try {
2476 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002477 if (mDeviceIdleMode == enabled) {
2478 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002479 }
Felipe Lemeea014392016-09-06 13:59:54 -07002480 mDeviceIdleMode = enabled;
2481 if (mSystemReady) {
2482 // Device idle change means we need to rebuild rules for all
2483 // known apps, so do a global refresh.
2484 updateRulesForRestrictPowerUL();
2485 }
2486 }
2487 if (enabled) {
2488 EventLogTags.writeDeviceIdleOnPhase("net");
2489 } else {
2490 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002491 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002492 } finally {
2493 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002494 }
2495 }
2496
Felipe Lemef0823852016-06-08 13:43:08 -07002497 private NetworkPolicy findPolicyForNetworkNL(NetworkIdentity ident) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002498 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2499 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002500 if (policy.template.matches(ident)) {
2501 return policy;
2502 }
2503 }
2504 return null;
2505 }
2506
2507 @Override
2508 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2509 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2510
2511 // only returns usage summary, so we don't require caller to have
2512 // READ_NETWORK_USAGE_HISTORY.
2513 final long token = Binder.clearCallingIdentity();
2514 try {
2515 return getNetworkQuotaInfoUnchecked(state);
2516 } finally {
2517 Binder.restoreCallingIdentity(token);
2518 }
2519 }
2520
2521 private NetworkQuotaInfo getNetworkQuotaInfoUnchecked(NetworkState state) {
2522 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2523
2524 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002525 synchronized (mNetworkPoliciesSecondLock) {
2526 policy = findPolicyForNetworkNL(ident);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002527 }
2528
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002529 if (policy == null || !policy.hasCycle()) {
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002530 // missing policy means we can't derive useful quota info
2531 return null;
2532 }
2533
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002534 final long currentTime = currentTimeMillis();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002535
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002536 // find total bytes used under policy
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002537 final long start = computeLastCycleBoundary(currentTime, policy);
2538 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07002539 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002540
2541 // report soft and hard limits under policy
2542 final long softLimitBytes = policy.warningBytes != WARNING_DISABLED ? policy.warningBytes
2543 : NetworkQuotaInfo.NO_LIMIT;
2544 final long hardLimitBytes = policy.limitBytes != LIMIT_DISABLED ? policy.limitBytes
2545 : NetworkQuotaInfo.NO_LIMIT;
2546
2547 return new NetworkQuotaInfo(totalBytes, softLimitBytes, hardLimitBytes);
2548 }
2549
Jeff Sharkey46645002011-07-27 21:11:21 -07002550 @Override
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002551 public boolean isNetworkMetered(NetworkState state) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06002552 if (state.networkInfo == null) {
2553 return false;
2554 }
2555
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002556 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
2557
2558 final NetworkPolicy policy;
Felipe Lemef0823852016-06-08 13:43:08 -07002559 synchronized (mNetworkPoliciesSecondLock) {
2560 policy = findPolicyForNetworkNL(ident);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002561 }
2562
2563 if (policy != null) {
2564 return policy.metered;
2565 } else {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002566 final int type = state.networkInfo.getType();
Jack Yub6587ea2016-06-22 11:35:10 -07002567 if ((isNetworkTypeMobile(type) && ident.getMetered()) || type == TYPE_WIMAX) {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002568 return true;
2569 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002570 return false;
2571 }
2572 }
2573
2574 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002575 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002576 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002577
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002578 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2579
Dianne Hackborn497175b2014-07-01 12:56:08 -07002580 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002581 for (String arg : args) {
2582 argSet.add(arg);
2583 }
2584
Felipe Lemef0823852016-06-08 13:43:08 -07002585 synchronized (mUidRulesFirstLock) {
2586 synchronized (mNetworkPoliciesSecondLock) {
2587 if (argSet.contains("--unsnooze")) {
2588 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2589 mNetworkPolicy.valueAt(i).clearSnooze();
2590 }
2591
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002592 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002593
2594 fout.println("Cleared snooze timestamps");
2595 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002596 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002597
Felipe Lemef0823852016-06-08 13:43:08 -07002598 fout.print("System ready: "); fout.println(mSystemReady);
2599 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2600 fout.print("Restrict power: "); fout.println(mRestrictPower);
2601 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2602 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002603 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002604 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2605 fout.println(mNetworkPolicy.valueAt(i).toString());
2606 }
2607 fout.decreaseIndent();
2608
2609 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2610
2611 fout.println("Policy for UIDs:");
2612 fout.increaseIndent();
2613 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002614 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002615 final int uid = mUidPolicy.keyAt(i);
2616 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002617 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002618 fout.print(uid);
2619 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002620 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002621 fout.println();
2622 }
2623 fout.decreaseIndent();
2624
2625 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2626 if (size > 0) {
2627 fout.println("Power save whitelist (except idle) app ids:");
2628 fout.increaseIndent();
2629 for (int i = 0; i < size; i++) {
2630 fout.print("UID=");
2631 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2632 fout.print(": ");
2633 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2634 fout.println();
2635 }
2636 fout.decreaseIndent();
2637 }
2638
2639 size = mPowerSaveWhitelistAppIds.size();
2640 if (size > 0) {
2641 fout.println("Power save whitelist app ids:");
2642 fout.increaseIndent();
2643 for (int i = 0; i < size; i++) {
2644 fout.print("UID=");
2645 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2646 fout.print(": ");
2647 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2648 fout.println();
2649 }
2650 fout.decreaseIndent();
2651 }
2652
Felipe Lemef0823852016-06-08 13:43:08 -07002653 size = mDefaultRestrictBackgroundWhitelistUids.size();
2654 if (size > 0) {
2655 fout.println("Default restrict background whitelist uids:");
2656 fout.increaseIndent();
2657 for (int i = 0; i < size; i++) {
2658 fout.print("UID=");
2659 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2660 fout.println();
2661 }
2662 fout.decreaseIndent();
2663 }
2664
2665 size = mRestrictBackgroundWhitelistRevokedUids.size();
2666 if (size > 0) {
2667 fout.println("Default restrict background whitelist uids revoked by users:");
2668 fout.increaseIndent();
2669 for (int i = 0; i < size; i++) {
2670 fout.print("UID=");
2671 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2672 fout.println();
2673 }
2674 fout.decreaseIndent();
2675 }
2676
2677 final SparseBooleanArray knownUids = new SparseBooleanArray();
2678 collectKeys(mUidState, knownUids);
2679 collectKeys(mUidRules, knownUids);
2680
2681 fout.println("Status for all known UIDs:");
2682 fout.increaseIndent();
2683 size = knownUids.size();
2684 for (int i = 0; i < size; i++) {
2685 final int uid = knownUids.keyAt(i);
2686 fout.print("UID=");
2687 fout.print(uid);
2688
2689 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2690 fout.print(" state=");
2691 fout.print(state);
2692 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2693 fout.print(" (fg)");
2694 } else {
2695 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2696 ? " (fg svc)" : " (bg)");
2697 }
2698
2699 final int uidRules = mUidRules.get(uid, RULE_NONE);
2700 fout.print(" rules=");
2701 fout.print(uidRulesToString(uidRules));
2702 fout.println();
2703 }
2704 fout.decreaseIndent();
2705
2706 fout.println("Status for just UIDs with rules:");
2707 fout.increaseIndent();
2708 size = mUidRules.size();
2709 for (int i = 0; i < size; i++) {
2710 final int uid = mUidRules.keyAt(i);
2711 fout.print("UID=");
2712 fout.print(uid);
2713 final int uidRules = mUidRules.get(uid, RULE_NONE);
2714 fout.print(" rules=");
2715 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002716 fout.println();
2717 }
2718 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002719
2720 fout.println("Observed uid state changes:");
2721 fout.increaseIndent();
2722 mObservedHistory.dumpUL(fout);
2723 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002724 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002725 }
2726 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002727
2728 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002729 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002730 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002731 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002732 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002733 }
2734
2735 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002736 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002737 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2738
Felipe Lemef0823852016-06-08 13:43:08 -07002739 synchronized (mUidRulesFirstLock) {
2740 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002741 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002742 }
2743
Felipe Lemef0823852016-06-08 13:43:08 -07002744 private boolean isUidForegroundUL(int uid) {
2745 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002746 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2747 }
2748
Felipe Lemef0823852016-06-08 13:43:08 -07002749 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002750 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002751 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002752 }
2753
Felipe Lemef0823852016-06-08 13:43:08 -07002754 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002755 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2756 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2757 }
2758
Felipe Lemef0823852016-06-08 13:43:08 -07002759 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002760 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002761 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002762 }
2763
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002764 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002765 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002766 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2767 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002768 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002769 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002770 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2771 try {
2772 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2773 if (oldUidState != uidState) {
2774 // state changed, push updated rules
2775 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002776 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2777 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2778 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2779 if (isUidIdle(uid)) {
2780 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002781 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002782 if (mDeviceIdleMode) {
2783 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002784 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002785 if (mRestrictPower) {
2786 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002787 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002788 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002789 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002790 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002791 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002792 } finally {
2793 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002794 }
2795 }
2796
Felipe Lemef0823852016-06-08 13:43:08 -07002797 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002798 final int index = mUidState.indexOfKey(uid);
2799 if (index >= 0) {
2800 final int oldUidState = mUidState.valueAt(index);
2801 mUidState.removeAt(index);
2802 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002803 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002804 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002805 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002806 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002807 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002808 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002809 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002810 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002811 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002812 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002813 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002814 }
2815 }
2816
Felipe Lemef28983d2016-03-25 12:18:23 -07002817 // adjust stats accounting based on foreground status
2818 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002819 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2820 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2821 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2822 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002823 try {
2824 mNetworkStats.setUidForeground(uid, uidForeground);
2825 } catch (RemoteException e) {
2826 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002827 } finally {
2828 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002829 }
2830 }
2831
Sudheer Shankac9d94072017-02-22 22:13:55 +00002832 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2833 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002834 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002835 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002836 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002837 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002838 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002839 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002840 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002841 }
2842
Felipe Lemef0823852016-06-08 13:43:08 -07002843 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002844 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2845 try {
2846 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2847 mUidFirewallPowerSaveRules);
2848 } finally {
2849 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2850 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002851 }
2852
Felipe Lemef0823852016-06-08 13:43:08 -07002853 void updateRuleForRestrictPowerUL(int uid) {
2854 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002855 }
2856
Felipe Lemef0823852016-06-08 13:43:08 -07002857 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002858 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2859 try {
2860 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2861 mUidFirewallDozableRules);
2862 } finally {
2863 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2864 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002865 }
2866
Felipe Lemef0823852016-06-08 13:43:08 -07002867 void updateRuleForDeviceIdleUL(int uid) {
2868 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002869 }
2870
Felipe Lemef28983d2016-03-25 12:18:23 -07002871 // NOTE: since both fw_dozable and fw_powersave uses the same map
2872 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002873 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002874 SparseIntArray rules) {
2875 if (enabled) {
2876 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002877 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002878 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002879 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002880 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002881 for (int ui = users.size() - 1; ui >= 0; ui--) {
2882 UserInfo user = users.get(ui);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002883 for (int i = mPowerSaveTempWhitelistAppIds.size() - 1; i >= 0; i--) {
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002884 if (mPowerSaveTempWhitelistAppIds.valueAt(i)) {
2885 int appId = mPowerSaveTempWhitelistAppIds.keyAt(i);
2886 int uid = UserHandle.getUid(user.id, appId);
2887 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2888 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002889 }
2890 for (int i = mPowerSaveWhitelistAppIds.size() - 1; i >= 0; i--) {
2891 int appId = mPowerSaveWhitelistAppIds.keyAt(i);
2892 int uid = UserHandle.getUid(user.id, appId);
2893 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2894 }
2895 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002896 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002897 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002898 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2899 }
2900 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002901 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2902 } else {
2903 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002904 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002905 }
2906
Felipe Lemef0823852016-06-08 13:43:08 -07002907 private boolean isWhitelistedBatterySaverUL(int uid) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002908 final int appId = UserHandle.getAppId(uid);
2909 return mPowerSaveTempWhitelistAppIds.get(appId) || mPowerSaveWhitelistAppIds.get(appId);
2910 }
2911
Felipe Lemef28983d2016-03-25 12:18:23 -07002912 // NOTE: since both fw_dozable and fw_powersave uses the same map
2913 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002914 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002915 if (enabled) {
Sudheer Shanka12d29222017-02-24 16:30:04 -08002916 if (isWhitelistedBatterySaverUL(uid) || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002917 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002918 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002919 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002920 }
2921 }
2922 }
2923
Felipe Lemef0823852016-06-08 13:43:08 -07002924 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002925 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2926 try {
2927 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2928 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002929
Felipe Leme873a83a2016-09-07 11:34:10 -07002930 // Fully update the app idle firewall chain.
2931 final List<UserInfo> users = mUserManager.getUsers();
2932 for (int ui = users.size() - 1; ui >= 0; ui--) {
2933 UserInfo user = users.get(ui);
2934 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2935 for (int uid : idleUids) {
2936 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2937 // quick check: if this uid doesn't have INTERNET permission, it
2938 // doesn't have network access anyway, so it is a waste to mess
2939 // with it here.
2940 if (hasInternetPermissions(uid)) {
2941 uidRules.put(uid, FIREWALL_RULE_DENY);
2942 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002943 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002944 }
2945 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002946
Felipe Lemebc853dd2016-09-08 13:26:55 -07002947 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002948 } finally {
2949 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2950 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002951 }
2952
Felipe Lemef0823852016-06-08 13:43:08 -07002953 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002954 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002955
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002956 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2957 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
2958 }
2959 try {
2960 int appId = UserHandle.getAppId(uid);
2961 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2962 && !isUidForegroundOnRestrictPowerUL(uid)) {
2963 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2964 } else {
2965 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2966 }
2967 } finally {
2968 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002969 }
2970 }
2971
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002972 /**
2973 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2974 * changed.
2975 */
Felipe Lemef0823852016-06-08 13:43:08 -07002976 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002977 boolean paroled = mUsageStats.isAppIdleParoleOn();
2978 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002979 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002980
2981 int ruleCount = mUidFirewallStandbyRules.size();
2982 for (int i = 0; i < ruleCount; i++) {
2983 int uid = mUidFirewallStandbyRules.keyAt(i);
2984 int oldRules = mUidRules.get(uid);
2985 if (enableChain) {
2986 // Chain wasn't enabled before and the other power-related
2987 // chains are whitelists, so we can clear the
2988 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2989 // the effective rules result in blocking network access.
2990 oldRules &= MASK_METERED_NETWORKS;
2991 } else {
2992 // Skip if it had no restrictions to begin with
2993 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2994 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002995 updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002996 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002997 }
2998
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002999 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003000 * Update rules that might be changed by {@link #mRestrictBackground},
3001 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003002 */
Felipe Lemef0823852016-06-08 13:43:08 -07003003 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003004 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3005 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3006 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3007 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003008 try {
Felipe Leme09700462016-09-08 09:33:48 -07003009 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003010 updateRulesForRestrictPowerUL();
3011 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003012
Felipe Leme873a83a2016-09-07 11:34:10 -07003013 // If the set of restricted networks may have changed, re-evaluate those.
3014 if (restrictedNetworksChanged) {
3015 normalizePoliciesNL();
3016 updateNetworkRulesNL();
3017 }
3018 } finally {
3019 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003020 }
3021 }
3022
Felipe Leme09700462016-09-08 09:33:48 -07003023 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003024 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003025 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3026 try {
3027 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003028 updateRulesForPowerSaveUL();
3029 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3030 } finally {
3031 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3032 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003033 }
3034
Felipe Lemef0823852016-06-08 13:43:08 -07003035 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003036 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3037 try {
3038 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3039 } finally {
3040 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3041 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003042 }
3043
3044 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3045 private static final int TYPE_RESTRICT_POWER = 2;
3046 @Retention(RetentionPolicy.SOURCE)
3047 @IntDef(flag = false, value = {
3048 TYPE_RESTRICT_BACKGROUND,
3049 TYPE_RESTRICT_POWER,
3050 })
3051 public @interface RestrictType {
3052 }
3053
3054 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003055 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003056 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3057 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3058 }
3059 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003060 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003061
3062 final PackageManager pm = mContext.getPackageManager();
3063 final List<UserInfo> users;
3064 final List<ApplicationInfo> apps;
3065
3066 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3067 try {
3068 users = mUserManager.getUsers();
3069 } finally {
3070 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3071 }
3072 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3073 try {
3074 apps = pm.getInstalledApplications(
3075 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3076 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3077 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3078 } finally {
3079 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3080 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003081
Felipe Leme873a83a2016-09-07 11:34:10 -07003082 final int usersSize = users.size();
3083 final int appsSize = apps.size();
3084 for (int i = 0; i < usersSize; i++) {
3085 final UserInfo user = users.get(i);
3086 for (int j = 0; j < appsSize; j++) {
3087 final ApplicationInfo app = apps.get(j);
3088 final int uid = UserHandle.getUid(user.id, app.uid);
3089 switch (type) {
3090 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003091 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003092 break;
3093 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003094 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003095 break;
3096 default:
3097 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3098 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003099 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003100 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003101 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003102 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003103 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003104 }
3105
Felipe Lemef0823852016-06-08 13:43:08 -07003106 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003107 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003108 for (int i = 0; i < users.size(); i++) {
3109 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003110 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003111 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003112 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003113 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003114 updateRuleForAppIdleUL(uid);
3115 updateRuleForDeviceIdleUL(uid);
3116 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003117 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003118 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003119 }
3120 }
3121 }
3122
Felipe Leme70c57c22016-03-29 10:45:13 -07003123 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3124 // methods below could be merged into a isUidValidForRules() method.
3125 private boolean isUidValidForBlacklistRules(int uid) {
3126 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003127 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003128 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003129 return true;
3130 }
3131
3132 return false;
3133 }
3134
Felipe Leme70c57c22016-03-29 10:45:13 -07003135 private boolean isUidValidForWhitelistRules(int uid) {
3136 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3137 }
3138
Amith Yamasani15e472352015-04-24 19:06:07 -07003139 private boolean isUidIdle(int uid) {
3140 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3141 final int userId = UserHandle.getUserId(uid);
3142
songjinshi0655edd2016-05-18 19:55:32 +08003143 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003144 for (String packageName : packages) {
3145 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3146 return false;
3147 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003148 }
3149 }
3150 return true;
3151 }
3152
3153 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003154 * Checks if an uid has INTERNET permissions.
3155 * <p>
3156 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003157 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003158 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003159 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003160 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003161 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003162 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003163 }
3164 } catch (RemoteException e) {
3165 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003166 return true;
3167 }
3168
3169 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003170 * Clears all state - internal and external - associated with an UID.
3171 */
3172 private void onUidDeletedUL(int uid) {
3173 // First cleanup in-memory state synchronously...
3174 mUidRules.delete(uid);
3175 mUidPolicy.delete(uid);
3176 mUidFirewallStandbyRules.delete(uid);
3177 mUidFirewallDozableRules.delete(uid);
3178 mUidFirewallPowerSaveRules.delete(uid);
3179 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3180 mPowerSaveWhitelistAppIds.delete(uid);
3181 mPowerSaveTempWhitelistAppIds.delete(uid);
3182
3183 // ...then update iptables asynchronously.
3184 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3185 }
3186
3187 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003188 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003189 *
Felipe Leme781ba142016-05-09 16:24:48 -07003190 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003191 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003192 * <li>Doze mode
3193 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003194 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003195 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003196 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003197 *
3198 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003199 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003200 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003201 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003202 updateRuleForDeviceIdleUL(uid);
3203 updateRuleForAppIdleUL(uid);
3204 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003205
3206 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003207 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003208
3209 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003210 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003211 }
3212
Felipe Leme70c57c22016-03-29 10:45:13 -07003213 /**
3214 * Applies network rules to bandwidth controllers based on process state and user-defined
3215 * restrictions (blacklist / whitelist).
3216 *
3217 * <p>
3218 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3219 * networks:
3220 * <ul>
3221 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3222 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3223 * also blacklisted.
3224 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3225 * no UIDs other those whitelisted will have access.
3226 * <ul>
3227 *
3228 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3229 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3230 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3231 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003232 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003233 * {@link INetworkManagementService}, but this method should also be called in events (like
3234 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3235 * following rules should also be applied:
3236 *
3237 * <ul>
3238 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3239 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3240 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3241 * {@code bw_penalty_box}.
3242 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3243 * </ul>
3244 *
3245 * <p>For optimization, the rules are only applied on user apps that have internet access
3246 * permission, since there is no need to change the {@code iptables} rule if the app does not
3247 * have permission to use the internet.
3248 *
3249 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003250 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003251 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003252 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003253 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3254 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3255 "updateRulesForDataUsageRestrictionsUL: " + uid);
3256 }
3257 try {
3258 updateRulesForDataUsageRestrictionsULInner(uid);
3259 } finally {
3260 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3261 }
3262 }
3263
3264 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003265 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003266 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003267 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003268 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003269
Dianne Hackborn497175b2014-07-01 12:56:08 -07003270 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003271 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003272 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003273
Felipe Leme781ba142016-05-09 16:24:48 -07003274 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003275 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003276 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3277 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003278
Felipe Leme70c57c22016-03-29 10:45:13 -07003279 // First step: define the new rule based on user restrictions and foreground state.
3280 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003281 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3282 newRule = RULE_TEMPORARY_ALLOW_METERED;
3283 } else if (isWhitelisted) {
3284 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003285 }
3286 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003287 if (isBlacklisted) {
3288 newRule = RULE_REJECT_METERED;
3289 } else if (mRestrictBackground && isWhitelisted) {
3290 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003291 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003292 }
Felipe Leme781ba142016-05-09 16:24:48 -07003293 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003294
Felipe Lemef28983d2016-03-25 12:18:23 -07003295 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003296 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003297 + ": isForeground=" +isForeground
3298 + ", isBlacklisted=" + isBlacklisted
3299 + ", isWhitelisted=" + isWhitelisted
3300 + ", oldRule=" + uidRulesToString(oldRule)
3301 + ", newRule=" + uidRulesToString(newRule)
3302 + ", newUidRules=" + uidRulesToString(newUidRules)
3303 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003304 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003305
Felipe Leme46c4fc32016-05-04 09:21:43 -07003306 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003307 mUidRules.delete(uid);
3308 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003309 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003310 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003311
Felipe Leme70c57c22016-03-29 10:45:13 -07003312 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003313 if (newRule != oldRule) {
Felipe Leme781ba142016-05-09 16:24:48 -07003314 if ((newRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003315 // Temporarily whitelist foreground app, removing from blacklist if necessary
3316 // (since bw_penalty_box prevails over bw_happy_box).
3317
3318 setMeteredNetworkWhitelist(uid, true);
3319 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3320 // but ideally it should be just:
3321 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003322 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003323 setMeteredNetworkBlacklist(uid, false);
3324 }
Felipe Leme781ba142016-05-09 16:24:48 -07003325 } else if ((oldRule & RULE_TEMPORARY_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003326 // Remove temporary whitelist from app that is not on foreground anymore.
3327
3328 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3329 // but ideally they should be just:
3330 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3331 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003332 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003333 setMeteredNetworkWhitelist(uid, false);
3334 }
Felipe Leme781ba142016-05-09 16:24:48 -07003335 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003336 setMeteredNetworkBlacklist(uid, true);
3337 }
Felipe Leme781ba142016-05-09 16:24:48 -07003338 } else if ((newRule & RULE_REJECT_METERED) != 0
3339 || (oldRule & RULE_REJECT_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003340 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003341 setMeteredNetworkBlacklist(uid, isBlacklisted);
3342 if ((oldRule & RULE_REJECT_METERED) != 0 && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003343 // Since blacklist prevails over whitelist, we need to handle the special case
3344 // where app is whitelisted and blacklisted at the same time (although such
3345 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003346 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003347 }
Felipe Leme781ba142016-05-09 16:24:48 -07003348 } else if ((newRule & RULE_ALLOW_METERED) != 0
3349 || (oldRule & RULE_ALLOW_METERED) != 0) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003350 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003351 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003352 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003353 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003354 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3355 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003356 + ", whitelisted=" + isWhitelisted
3357 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003358 + ", newRule=" + uidRulesToString(newUidRules)
3359 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003360 }
Felipe Leme781ba142016-05-09 16:24:48 -07003361
Sudheer Shankac9d94072017-02-22 22:13:55 +00003362 // Dispatch changed rule to existing listeners.
3363 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003364 }
3365 }
3366
3367 /**
3368 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3369 * listeners in case of change.
3370 * <p>
3371 * There are 3 power-related rules that affects whether an app has background access on
3372 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3373 * restriction, it's added to the equivalent firewall chain:
3374 * <ul>
3375 * <li>App is idle: {@code fw_standby} firewall chain.
3376 * <li>Device is idle: {@code fw_dozable} firewall chain.
3377 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3378 * </ul>
3379 * <p>
3380 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3381 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3382 * <p>
3383 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3384 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003385 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003386 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3387
Sudheer Shankac9d94072017-02-22 22:13:55 +00003388 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003389
Sudheer Shankac9d94072017-02-22 22:13:55 +00003390 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003391 mUidRules.delete(uid);
3392 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003393 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003394 }
3395 }
3396
3397 /**
3398 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3399 *
3400 * @param uid the uid of the app to update rules for
3401 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3402 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3403 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003404 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003405 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003406 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003407 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3408 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3409 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3410 + (paroled ? "P" : "-"));
3411 }
3412 try {
3413 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3414 } finally {
3415 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3416 }
3417 }
3418
3419 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003420 if (!isUidValidForBlacklistRules(uid)) {
3421 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003422 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003423 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003424
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003425 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003426 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003427 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003428
Felipe Lemef0823852016-06-08 13:43:08 -07003429 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003430 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3431 int newRule = RULE_NONE;
3432
3433 // First step: define the new rule based on user restrictions and foreground state.
3434
3435 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3436 // by considering the foreground and non-foreground states.
3437 if (isForeground) {
3438 if (restrictMode) {
3439 newRule = RULE_ALLOW_ALL;
3440 }
3441 } else if (restrictMode) {
3442 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3443 }
3444
3445 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3446
3447 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003448 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003449 + ", isIdle: " + isIdle
3450 + ", mRestrictPower: " + mRestrictPower
3451 + ", mDeviceIdleMode: " + mDeviceIdleMode
3452 + ", isForeground=" + isForeground
3453 + ", isWhitelisted=" + isWhitelisted
3454 + ", oldRule=" + uidRulesToString(oldRule)
3455 + ", newRule=" + uidRulesToString(newRule)
3456 + ", newUidRules=" + uidRulesToString(newUidRules)
3457 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3458 }
3459
Felipe Leme781ba142016-05-09 16:24:48 -07003460 // Second step: notify listeners if state changed.
3461 if (newRule != oldRule) {
3462 if (newRule == RULE_NONE || (newRule & RULE_ALLOW_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003463 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003464 } else if ((newRule & RULE_REJECT_ALL) != 0) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003465 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3466 } else {
3467 // All scenarios should have been covered above
3468 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3469 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003470 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003471 + ", newRule=" + uidRulesToString(newUidRules)
3472 + ", oldRule=" + uidRulesToString(oldUidRules));
3473 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003474 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003475 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003476
Sudheer Shankac9d94072017-02-22 22:13:55 +00003477 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003478 }
3479
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003480 private class AppIdleStateChangeListener
3481 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3482
3483 @Override
3484 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3485 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003486 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3487 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003488 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003489 synchronized (mUidRulesFirstLock) {
3490 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003491 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003492 }
3493 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003494 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003495 }
3496
3497 @Override
3498 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003499 synchronized (mUidRulesFirstLock) {
3500 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003501 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003502 }
3503 }
3504
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003505 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3506 if (listener != null) {
3507 try {
3508 listener.onUidRulesChanged(uid, uidRules);
3509 } catch (RemoteException ignored) {
3510 }
3511 }
3512 }
3513
3514 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3515 String[] meteredIfaces) {
3516 if (listener != null) {
3517 try {
3518 listener.onMeteredIfacesChanged(meteredIfaces);
3519 } catch (RemoteException ignored) {
3520 }
3521 }
3522 }
3523
3524 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3525 boolean restrictBackground) {
3526 if (listener != null) {
3527 try {
3528 listener.onRestrictBackgroundChanged(restrictBackground);
3529 } catch (RemoteException ignored) {
3530 }
3531 }
3532 }
3533
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003534 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3535 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003536 if (listener != null) {
3537 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003538 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003539 } catch (RemoteException ignored) {
3540 }
3541 }
3542 }
3543
Makoto Onuki8e777332017-03-28 11:25:47 -07003544 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003545 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003546 public boolean handleMessage(Message msg) {
3547 switch (msg.what) {
3548 case MSG_RULES_CHANGED: {
3549 final int uid = msg.arg1;
3550 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003551 final int length = mListeners.beginBroadcast();
3552 for (int i = 0; i < length; i++) {
3553 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3554 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003555 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003556 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003557 return true;
3558 }
3559 case MSG_METERED_IFACES_CHANGED: {
3560 final String[] meteredIfaces = (String[]) msg.obj;
3561 final int length = mListeners.beginBroadcast();
3562 for (int i = 0; i < length; i++) {
3563 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003564 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003565 }
3566 mListeners.finishBroadcast();
3567 return true;
3568 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003569 case MSG_LIMIT_REACHED: {
3570 final String iface = (String) msg.obj;
3571
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003572 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003573 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003574 if (mMeteredIfaces.contains(iface)) {
3575 try {
3576 // force stats update to make sure we have
3577 // numbers that caused alert to trigger.
3578 mNetworkStats.forceUpdate();
3579 } catch (RemoteException e) {
3580 // ignored; service lives in system_server
3581 }
3582
Felipe Lemef0823852016-06-08 13:43:08 -07003583 updateNetworkEnabledNL();
3584 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003585 }
3586 }
3587 return true;
3588 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003589 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3590 final boolean restrictBackground = msg.arg1 != 0;
3591 final int length = mListeners.beginBroadcast();
3592 for (int i = 0; i < length; i++) {
3593 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003594 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003595 }
3596 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003597 final Intent intent =
3598 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3599 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3600 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3601 return true;
3602 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003603 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003604 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003605 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003606 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003607 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003608 final int length = mListeners.beginBroadcast();
3609 for (int i = 0; i < length; i++) {
3610 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003611 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003612 }
3613 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003614 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3615 if (notifyApp.booleanValue()) {
3616 broadcastRestrictBackgroundChanged(uid, notifyApp);
3617 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003618 return true;
3619 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003620 case MSG_ADVISE_PERSIST_THRESHOLD: {
3621 final long lowestRule = (Long) msg.obj;
3622 try {
3623 // make sure stats are recorded frequently enough; we aim
3624 // for 2MB threshold for 2GB/month rules.
3625 final long persistThreshold = lowestRule / 1000;
3626 mNetworkStats.advisePersistThreshold(persistThreshold);
3627 } catch (RemoteException e) {
3628 // ignored; service lives in system_server
3629 }
3630 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003631 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003632 case MSG_UPDATE_INTERFACE_QUOTA: {
3633 removeInterfaceQuota((String) msg.obj);
3634 // int params need to be stitched back into a long
3635 setInterfaceQuota((String) msg.obj,
3636 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3637 return true;
3638 }
3639 case MSG_REMOVE_INTERFACE_QUOTA: {
3640 removeInterfaceQuota((String) msg.obj);
3641 return true;
3642 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003643 case MSG_SET_FIREWALL_RULES: {
3644 final int chain = msg.arg1;
3645 final int toggle = msg.arg2;
3646 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3647 if (uidRules != null) {
3648 setUidFirewallRules(chain, uidRules);
3649 }
3650 if (toggle != CHAIN_TOGGLE_NONE) {
3651 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3652 }
3653 return true;
3654 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003655 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3656 resetUidFirewallRules(msg.arg1);
3657 return true;
3658 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003659 default: {
3660 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003661 }
3662 }
3663 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003664 };
3665
3666 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3667 @Override
3668 public boolean handleMessage(Message msg) {
3669 switch (msg.what) {
3670 case UID_MSG_STATE_CHANGED: {
3671 final int uid = msg.arg1;
3672 final int procState = msg.arg2;
3673 final long procStateSeq = (Long) msg.obj;
3674
3675 handleUidChanged(uid, procState, procStateSeq);
3676 return true;
3677 }
3678 case UID_MSG_GONE: {
3679 final int uid = msg.arg1;
3680 handleUidGone(uid);
3681 return true;
3682 }
3683 default: {
3684 return false;
3685 }
3686 }
3687 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003688
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003689 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003690
Makoto Onuki8e777332017-03-28 11:25:47 -07003691 void handleUidChanged(int uid, int procState, long procStateSeq) {
3692 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3693 try {
3694 synchronized (mUidRulesFirstLock) {
3695 // We received a uid state change callback, add it to the history so that it
3696 // will be useful for debugging.
3697 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3698 // Now update the network policy rules as per the updated uid state.
3699 updateUidStateUL(uid, procState);
3700 // Updating the network rules is done, so notify AMS about this.
3701 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3702 }
3703 } finally {
3704 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3705 }
3706 }
3707
3708 void handleUidGone(int uid) {
3709 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3710 try {
3711 synchronized (mUidRulesFirstLock) {
3712 removeUidStateUL(uid);
3713 }
3714 } finally {
3715 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3716 }
3717 }
3718
Felipe Leme57e3d312016-08-23 14:42:52 -07003719 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3720 final PackageManager pm = mContext.getPackageManager();
3721 final String[] packages = pm.getPackagesForUid(uid);
3722 if (packages != null) {
3723 final int userId = UserHandle.getUserId(uid);
3724 for (String packageName : packages) {
3725 final Intent intent =
3726 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3727 intent.setPackage(packageName);
3728 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3729 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3730 }
3731 }
3732 }
3733
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003734 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003735 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003736 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003737 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003738 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003739 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003740 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003741 }
3742 }
3743
3744 private void removeInterfaceQuota(String iface) {
3745 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003746 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003747 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003748 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003749 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003750 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003751 }
3752 }
3753
Felipe Leme70c57c22016-03-29 10:45:13 -07003754 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3755 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003756 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003757 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003758 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003759 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3760 } catch (RemoteException e) {
3761 // ignored; service lives in system_server
3762 }
3763 }
3764
3765 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3766 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3767 try {
3768 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3769 } catch (IllegalStateException e) {
3770 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003771 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003772 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003773 }
3774 }
3775
Felipe Lemebc853dd2016-09-08 13:26:55 -07003776 private static final int CHAIN_TOGGLE_NONE = 0;
3777 private static final int CHAIN_TOGGLE_ENABLE = 1;
3778 private static final int CHAIN_TOGGLE_DISABLE = 2;
3779 @Retention(RetentionPolicy.SOURCE)
3780 @IntDef(flag = false, value = {
3781 CHAIN_TOGGLE_NONE,
3782 CHAIN_TOGGLE_ENABLE,
3783 CHAIN_TOGGLE_DISABLE
3784 })
3785 public @interface ChainToggleType {
3786 }
3787
3788 /**
3789 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3790 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3791 *
3792 * @param chain firewall chain.
3793 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3794 * @param toggle whether the chain should be enabled, disabled, or not changed.
3795 */
3796 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3797 @ChainToggleType int toggle) {
3798 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3799 }
3800
Amith Yamasani15e472352015-04-24 19:06:07 -07003801 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003802 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3803 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3804 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003805 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003806 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003807 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003808 int size = uidRules.size();
3809 int[] uids = new int[size];
3810 int[] rules = new int[size];
3811 for(int index = size - 1; index >= 0; --index) {
3812 uids[index] = uidRules.keyAt(index);
3813 rules[index] = uidRules.valueAt(index);
3814 }
3815 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003816 } catch (IllegalStateException e) {
3817 Log.wtf(TAG, "problem setting firewall uid rules", e);
3818 } catch (RemoteException e) {
3819 // ignored; service lives in system_server
3820 }
3821 }
3822
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003823 /**
3824 * Add or remove a uid to the firewall blacklist for all network ifaces.
3825 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003826 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003827 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3828 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3829 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003830 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003831 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003832 if (chain == FIREWALL_CHAIN_DOZABLE) {
3833 mUidFirewallDozableRules.put(uid, rule);
3834 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3835 mUidFirewallStandbyRules.put(uid, rule);
3836 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3837 mUidFirewallPowerSaveRules.put(uid, rule);
3838 }
3839
3840 try {
3841 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3842 } catch (IllegalStateException e) {
3843 Log.wtf(TAG, "problem setting firewall uid rules", e);
3844 } catch (RemoteException e) {
3845 // ignored; service lives in system_server
3846 }
3847 } finally {
3848 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003849 }
3850 }
3851
3852 /**
3853 * Add or remove a uid to the firewall blacklist for all network ifaces.
3854 */
Felipe Lemef0823852016-06-08 13:43:08 -07003855 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003856 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3857 mFirewallChainStates.get(chain) == enable) {
3858 // All is the same, nothing to do.
3859 return;
3860 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003861 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003862 try {
3863 mNetworkManager.setFirewallChainEnabled(chain, enable);
3864 } catch (IllegalStateException e) {
3865 Log.wtf(TAG, "problem enable firewall chain", e);
3866 } catch (RemoteException e) {
3867 // ignored; service lives in system_server
3868 }
3869 }
3870
Felipe Leme03e95e22016-09-09 09:25:31 -07003871 /**
3872 * Resets all firewall rules associated with an UID.
3873 */
3874 private void resetUidFirewallRules(int uid) {
3875 try {
3876 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3877 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3878 mNetworkManager
3879 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3880 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3881 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3882 } catch (IllegalStateException e) {
3883 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3884 } catch (RemoteException e) {
3885 // ignored; service lives in system_server
3886 }
3887 }
3888
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003889 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3890 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003891 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003892 } catch (RuntimeException e) {
3893 Slog.w(TAG, "problem reading network stats: " + e);
3894 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003895 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003896 // ignored; service lives in system_server
3897 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003898 }
3899 }
3900
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003901 private boolean isBandwidthControlEnabled() {
3902 final long token = Binder.clearCallingIdentity();
3903 try {
3904 return mNetworkManager.isBandwidthControlEnabled();
3905 } catch (RemoteException e) {
3906 // ignored; service lives in system_server
3907 return false;
3908 } finally {
3909 Binder.restoreCallingIdentity(token);
3910 }
3911 }
3912
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003913 /**
3914 * Try refreshing {@link #mTime} when stale.
3915 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003916 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003917 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003918 mTime.forceRefresh();
3919 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003920 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003921
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003922 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003923 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3924 }
3925
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003926 private static Intent buildAllowBackgroundDataIntent() {
3927 return new Intent(ACTION_ALLOW_BACKGROUND);
3928 }
3929
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003930 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3931 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3932 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3933 return intent;
3934 }
3935
Wei Liu546cb772016-07-21 16:19:01 -07003936 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003937 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003938 intent.setComponent(ComponentName.unflattenFromString(
3939 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003940 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3941 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3942 return intent;
3943 }
3944
Wei Liu546cb772016-07-21 16:19:01 -07003945 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003946 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003947 intent.setComponent(ComponentName.unflattenFromString(
3948 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003949 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3950 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3951 return intent;
3952 }
3953
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003954 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003955 public void addIdleHandler(IdleHandler handler) {
3956 mHandler.getLooper().getQueue().addIdleHandler(handler);
3957 }
3958
jackqdyulei29c82ab2017-03-10 14:09:16 -08003959 @VisibleForTesting
3960 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
3961 mRestrictBackgroundPowerState = result;
3962
3963 boolean restrictBackground = result.batterySaverEnabled;
3964 boolean shouldInvokeRestrictBackground;
3965 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
3966 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
3967
3968 if (result.globalBatterySaverEnabled) {
3969 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
3970 // turn it on.
3971 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
3972 mRestrictBackgroundBeforeBsm = mRestrictBackground;
3973 localRestrictBgChangedInBsm = false;
3974 } else {
3975 // Try to restore the restrictBackground if it doesn't change in bsm
3976 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
3977 restrictBackground = mRestrictBackgroundBeforeBsm;
3978 }
3979
3980 if (shouldInvokeRestrictBackground) {
3981 setRestrictBackground(restrictBackground);
3982 }
3983
3984 // Change it at last so setRestrictBackground() won't affect this variable
3985 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
3986 }
3987
Jeff Sharkey1b861272011-05-22 00:34:52 -07003988 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3989 final int size = source.size();
3990 for (int i = 0; i < size; i++) {
3991 target.put(source.keyAt(i), true);
3992 }
3993 }
3994
Stuart Scottf1fb3972015-04-02 18:00:02 -07003995 @Override
3996 public void factoryReset(String subscriber) {
3997 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3998
Stuart Scotte3e314d2015-04-20 14:07:45 -07003999 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4000 return;
4001 }
4002
Stuart Scottf1fb3972015-04-02 18:00:02 -07004003 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004004 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004005 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4006 for (NetworkPolicy policy : policies) {
4007 if (policy.template.equals(template)) {
4008 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4009 policy.inferred = false;
4010 policy.clearSnooze();
4011 }
4012 }
4013 setNetworkPolicies(policies);
4014
4015 // Turn restrict background data off
4016 setRestrictBackground(false);
4017
Stuart Scotte3e314d2015-04-20 14:07:45 -07004018 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4019 // Remove app's "restrict background data" flag
4020 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4021 setUidPolicy(uid, POLICY_NONE);
4022 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004023 }
4024 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004025
Felipe Lemed17fda42016-04-29 11:12:45 -07004026 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4027
4028 @Override
4029 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004030 synchronized (mUidRulesFirstLock) {
4031 boolean changed = removeUserStateUL(userId, false);
4032 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004033 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004034 synchronized (mNetworkPoliciesSecondLock) {
4035 writePolicyAL();
4036 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004037 }
4038 }
4039 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004040
4041 /**
4042 * @return true if the given uid is restricted from doing networking on metered networks.
4043 */
4044 @Override
4045 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4046 final int uidRules;
4047 final boolean isBackgroundRestricted;
4048 synchronized (mUidRulesFirstLock) {
4049 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4050 isBackgroundRestricted = mRestrictBackground;
4051 }
4052 return isBackgroundRestricted
4053 && !hasRule(uidRules, RULE_ALLOW_METERED)
4054 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4055 }
4056
4057 /**
4058 * @return true if networking is blocked on the given interface for the given uid according
4059 * to current networking policies.
4060 */
4061 @Override
4062 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4063 final int uidRules;
4064 final boolean isBackgroundRestricted;
4065 final boolean isNetworkMetered;
4066 synchronized (mUidRulesFirstLock) {
4067 uidRules = mUidRules.get(uid, RULE_NONE);
4068 isBackgroundRestricted = mRestrictBackground;
4069 synchronized (mNetworkPoliciesSecondLock) {
4070 isNetworkMetered = mMeteredIfaces.contains(ifname);
4071 }
4072 }
4073 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4074 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4075 return true;
4076 }
4077 if (!isNetworkMetered) {
4078 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4079 return false;
4080 }
4081 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4082 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4083 return true;
4084 }
4085 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4086 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4087 return false;
4088 }
4089 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4090 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4091 return false;
4092 }
4093 if (isBackgroundRestricted) {
4094 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4095 return true;
4096 }
4097 if (LOGV) logUidStatus(uid, "allowed by default");
4098 return false;
4099 }
4100 }
4101
4102 private static boolean hasRule(int uidRules, int rule) {
4103 return (uidRules & rule) != 0;
4104 }
4105
4106 private static void logUidStatus(int uid, String descr) {
4107 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004108 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004109
4110 /**
4111 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4112 * (uid, procStateSeq) pairs.
4113 */
4114 @VisibleForTesting
4115 public static final class ProcStateSeqHistory {
4116 private static final int INVALID_UID = -1;
4117
4118 /**
4119 * Denotes maximum number of items this history can hold.
4120 */
4121 private final int mMaxCapacity;
4122 /**
4123 * Used for storing the uid information.
4124 */
4125 private final int[] mUids;
4126 /**
4127 * Used for storing the sequence numbers associated with {@link #mUids}.
4128 */
4129 private final long[] mProcStateSeqs;
4130 /**
4131 * Points to the next available slot for writing (uid, procStateSeq) pair.
4132 */
4133 private int mHistoryNext;
4134
4135 public ProcStateSeqHistory(int maxCapacity) {
4136 mMaxCapacity = maxCapacity;
4137 mUids = new int[mMaxCapacity];
4138 Arrays.fill(mUids, INVALID_UID);
4139 mProcStateSeqs = new long[mMaxCapacity];
4140 }
4141
4142 @GuardedBy("mUidRulesFirstLock")
4143 public void addProcStateSeqUL(int uid, long procStateSeq) {
4144 mUids[mHistoryNext] = uid;
4145 mProcStateSeqs[mHistoryNext] = procStateSeq;
4146 mHistoryNext = increaseNext(mHistoryNext, 1);
4147 }
4148
4149 @GuardedBy("mUidRulesFirstLock")
4150 public void dumpUL(IndentingPrintWriter fout) {
4151 if (mUids[0] == INVALID_UID) {
4152 fout.println("NONE");
4153 return;
4154 }
4155 int index = mHistoryNext;
4156 do {
4157 index = increaseNext(index, -1);
4158 if (mUids[index] == INVALID_UID) {
4159 break;
4160 }
4161 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4162 } while (index != mHistoryNext);
4163 }
4164
4165 public static String getString(int uid, long procStateSeq) {
4166 return "UID=" + uid + " procStateSeq=" + procStateSeq;
4167 }
4168
4169 private int increaseNext(int next, int increment) {
4170 next += increment;
4171 if (next >= mMaxCapacity) {
4172 next = 0;
4173 } else if (next < 0) {
4174 next = mMaxCapacity - 1;
4175 }
4176 return next;
4177 }
4178 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004179
4180 private class NotificationId {
4181 private final String mTag;
4182 private final int mId;
4183
4184 NotificationId(NetworkPolicy policy, int type) {
4185 mTag = buildNotificationTag(policy, type);
4186 mId = type;
4187 }
4188
4189 @Override
4190 public boolean equals(Object o) {
4191 if (this == o) return true;
4192 if (!(o instanceof NotificationId)) return false;
4193 NotificationId that = (NotificationId) o;
4194 return Objects.equals(mTag, that.mTag);
4195 }
4196
4197 @Override
4198 public int hashCode() {
4199 return Objects.hash(mTag);
4200 }
4201
4202 /**
4203 * Build unique tag that identifies an active {@link NetworkPolicy}
4204 * notification of a specific type, like {@link #TYPE_LIMIT}.
4205 */
4206 private String buildNotificationTag(NetworkPolicy policy, int type) {
4207 return TAG + ":" + policy.template.hashCode() + ":" + type;
4208 }
4209
4210 public String getTag() {
4211 return mTag;
4212 }
4213
4214 public int getId() {
4215 return mId;
4216 }
4217 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004218}