blob: 9b032e251be950bb705b8bb8012fd6469159c8ee [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 Sharkey53313d72017-07-13 16:47:32 -060021import static android.Manifest.permission.MANAGE_FALLBACK_SUBSCRIPTION_PLANS;
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;
Jeff Sharkey53313d72017-07-13 16:47:32 -060031import static android.content.pm.PackageManager.PERMISSION_GRANTED;
Erik Klinef851d6d2015-04-20 16:03:48 +090032import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080033import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
35import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060036import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
44import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060047import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
48import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
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.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070057import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080058import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
59import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060060import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070070import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060071import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080073
Jeff Sharkey854b2b12012-04-13 16:03:40 -070074import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070076import static com.android.internal.util.XmlUtils.readBooleanAttribute;
77import static com.android.internal.util.XmlUtils.readIntAttribute;
78import static com.android.internal.util.XmlUtils.readLongAttribute;
79import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
80import static com.android.internal.util.XmlUtils.writeIntAttribute;
81import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070082import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070083import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060084
Jeff Sharkey21c9c452011-06-07 12:26:43 -070085import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080086import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070088
Dianne Hackborn88e98df2015-03-23 13:29:14 -070089import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070090import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070091import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070092import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080093import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070094import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070095import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070096import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070097import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070098import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.Notification;
100import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700101import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700102import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700103import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700104import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700105import android.content.Intent;
106import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700107import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700108import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700110import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700111import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700112import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700114import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700115import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700117import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700118import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700120import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700121import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600122import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700123import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700124import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600126import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700127import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700129import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.os.Environment;
131import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700132import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700133import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700134import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700135import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700136import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700137import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700138import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700139import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600140import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800141import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700142import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700143import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600144import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700145import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700146import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600147import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700148import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700149import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700150import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700151import android.provider.Settings;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700152import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600153import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800154import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600155import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700156import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400157import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700158import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700159import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700160import android.util.ArrayMap;
161import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700162import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700163import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700164import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700165import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700166import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700167import android.util.SparseBooleanArray;
168import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700169import android.util.TrustedTime;
170import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700171
Jeff Sharkey497e4432011-06-14 17:27:29 -0700172import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700173import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800174import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400175import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500176import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700177import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800178import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600179import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700180import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700181import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700182import com.android.server.DeviceIdleController;
183import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700184import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700185import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800186import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800187import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600188
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600189import libcore.io.IoUtils;
190
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700191import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700192
193import org.xmlpull.v1.XmlPullParser;
194import org.xmlpull.v1.XmlPullParserException;
195import org.xmlpull.v1.XmlSerializer;
196
197import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700198import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700199import java.io.FileInputStream;
200import java.io.FileNotFoundException;
201import java.io.FileOutputStream;
202import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700203import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700204import java.lang.annotation.Retention;
205import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100206import java.nio.charset.StandardCharsets;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600207import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208import java.util.ArrayList;
209import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700210import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600211import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400212import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800213import java.util.concurrent.CountDownLatch;
214import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700216/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700217 * Service that maintains low-level network policy rules, using
218 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700219 * <p>
220 * Derives active rules by combining a given policy with other system status,
221 * and delivers to listeners, such as {@link ConnectivityManager}, for
222 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700223 *
224 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000225 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700226 * <ul>
227 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
228 * rules).
229 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
230 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000231 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
232 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700233 * </ul>
234 *
235 * <p>
236 * As such, methods that require synchronization have the following prefixes:
237 * <ul>
238 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
239 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000240 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
241 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700242 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700243 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700244public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800245 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900246 private static final boolean LOGD = false;
247 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700248
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700249 private static final int VERSION_INIT = 1;
250 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700251 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800252 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800253 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800254 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700255 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700256 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700257 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700258 private static final int VERSION_SWITCH_UID = 10;
259 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700260
Sudheer Shankae7361852017-03-07 11:51:46 -0800261 /**
262 * Max items written to {@link #ProcStateSeqHistory}.
263 */
264 @VisibleForTesting
265 public static final int MAX_PROC_STATE_SEQ_HISTORY =
266 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
267
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800268 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400269 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800270 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400271 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800272 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400273 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700274
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700275 private static final String TAG_POLICY_LIST = "policy-list";
276 private static final String TAG_NETWORK_POLICY = "network-policy";
277 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700278 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800279 private static final String TAG_WHITELIST = "whitelist";
280 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800281 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700282
283 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700284 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700285 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
286 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700287 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700288 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800289 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_WARNING_BYTES = "warningBytes";
291 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700292 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800293 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
294 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800295 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700296 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700297 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700298 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700299 private static final String ATTR_POLICY = "policy";
300
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800301 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800302 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800303 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800304 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700305
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
307
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700308 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700309 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800310 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800311 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700312 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700313 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
314 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700315 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700316 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700317 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700318
Makoto Onuki8e777332017-03-28 11:25:47 -0700319 private static final int UID_MSG_STATE_CHANGED = 100;
320 private static final int UID_MSG_GONE = 101;
321
Jeff Sharkey75279902011-05-24 18:39:45 -0700322 private final Context mContext;
323 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700324 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700325 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700326 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700327 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700328 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700329 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700330
331 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700332 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700333 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700334 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800335 @GuardedBy("mUidRulesFirstLock")
336 private PowerSaveState mRestrictBackgroundPowerState;
337
338 // Store the status of restrict background before turning on battery saver.
339 // Used to restore mRestrictBackground when battery saver is turned off.
340 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700341
Felipe Lemef0823852016-06-08 13:43:08 -0700342 // See main javadoc for instructions on how to use these locks.
343 final Object mUidRulesFirstLock = new Object();
344 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700345
Felipe Lemef0823852016-06-08 13:43:08 -0700346 @GuardedBy("allLocks") volatile boolean mSystemReady;
347
Felipe Lemef0823852016-06-08 13:43:08 -0700348 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
349 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
350 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800351 // Store whether user flipped restrict background in battery saver mode
352 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700353
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700354 private final boolean mSuppressDefaultPolicy;
355
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700356 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800357 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700358 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800359 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700360
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700361 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700363 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700365
Felipe Lemef0823852016-06-08 13:43:08 -0700366 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700367 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700368 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700369 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700370 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800371 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700372
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700373 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700374 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700375 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
376
Jeff Sharkey32566012014-12-02 18:30:14 -0800377 /**
378 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700379 * in power save mode, except device idle (doze) still applies.
380 * TODO: An int array might be sufficient
381 */
Felipe Lemef0823852016-06-08 13:43:08 -0700382 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700383 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
384
385 /**
386 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800387 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700388 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800389 */
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700391 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700392
Felipe Lemef0823852016-06-08 13:43:08 -0700393 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700394 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
395
Felipe Lemeb85a6372016-01-14 16:16:16 -0800396 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800397 * UIDs that have been initially white-listed by system to avoid restricted background.
398 */
Felipe Lemef0823852016-06-08 13:43:08 -0700399 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800400 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
401 new SparseBooleanArray();
402
403 /**
404 * UIDs that have been initially white-listed by system to avoid restricted background,
405 * but later revoked by user.
406 */
Felipe Lemef0823852016-06-08 13:43:08 -0700407 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800408 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
409 new SparseBooleanArray();
410
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700411 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700412 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800413 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700414 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700415 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800416 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700417
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700418 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700419 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400420 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700421
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700422 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800424 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700425
Jeff Sharkey32566012014-12-02 18:30:14 -0800426 private final RemoteCallbackList<INetworkPolicyListener>
427 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700428
Dianne Hackborn497175b2014-07-01 12:56:08 -0700429 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700430 @VisibleForTesting
431 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700432
433 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700434
Felipe Lemef0823852016-06-08 13:43:08 -0700435 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700436 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700437
Svet Ganov16a16892015-04-16 10:32:04 -0700438 private final AppOpsManager mAppOps;
439
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800440 private final IPackageManager mIPm;
441
Sudheer Shankae7361852017-03-07 11:51:46 -0800442 private ActivityManagerInternal mActivityManagerInternal;
443
444 /**
445 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
446 * the uid and procStateSeq will be written to this and will be printed as part of dump.
447 */
448 @VisibleForTesting
449 public ProcStateSeqHistory mObservedHistory
450 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800451
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700452 // TODO: keep whitelist of system-critical services that should never have
453 // rules enforced, such as system, phone, and radio UIDs.
454
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700455 // TODO: migrate notifications to SystemUI
456
Jeff Sharkey75279902011-05-24 18:39:45 -0700457 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700458 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
459 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700460 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
461 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700462 }
463
464 private static File getSystemDir() {
465 return new File(Environment.getDataDirectory(), "system");
466 }
467
468 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700469 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700470 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700471 mContext = checkNotNull(context, "missing context");
472 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700473 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700474 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700475 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700476 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700477 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700478 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700479 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700480 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700481
Amith Yamasani450a16b2013-09-18 16:28:50 -0700482 HandlerThread thread = new HandlerThread(TAG);
483 thread.start();
484 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700485
Makoto Onuki8e777332017-03-28 11:25:47 -0700486 // We create another thread for the UID events, which are more time-critical.
487 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
488 /*allowIo=*/ false);
489 mUidEventThread.start();
490 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
491
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700492 mSuppressDefaultPolicy = suppressDefaultPolicy;
493
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700494 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700495
496 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800497
Felipe Lemed17fda42016-04-29 11:12:45 -0700498 // Expose private service for system components to use.
499 LocalServices.addService(NetworkPolicyManagerInternal.class,
500 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700501 }
502
503 public void bindConnectivityManager(IConnectivityManager connManager) {
504 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700505 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700506
Jeff Sharkey497e4432011-06-14 17:27:29 -0700507 public void bindNotificationManager(INotificationManager notifManager) {
508 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
509 }
510
Felipe Lemef0823852016-06-08 13:43:08 -0700511 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700512 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700513 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
514 mPowerSaveWhitelistExceptIdleAppIds.clear();
515 if (whitelist != null) {
516 for (int uid : whitelist) {
517 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
518 }
519 }
520 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700521 mPowerSaveWhitelistAppIds.clear();
522 if (whitelist != null) {
523 for (int uid : whitelist) {
524 mPowerSaveWhitelistAppIds.put(uid, true);
525 }
526 }
527 } catch (RemoteException e) {
528 }
529 }
530
Felipe Lemea9505cc2016-02-26 10:28:41 -0800531 /**
532 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
533 * revoke the whitelist.
534 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700535 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800536 */
Felipe Lemef0823852016-06-08 13:43:08 -0700537 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800538 final List<UserInfo> users = mUserManager.getUsers();
539 final int numberUsers = users.size();
540
Felipe Lemea110eec2016-04-29 09:58:06 -0700541 boolean changed = false;
542 for (int i = 0; i < numberUsers; i++) {
543 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700544 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700545 }
546 return changed;
547 }
548
Felipe Lemef0823852016-06-08 13:43:08 -0700549 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700550 final SystemConfig sysConfig = SystemConfig.getInstance();
551 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800552 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
553 boolean changed = false;
554 for (int i = 0; i < allowDataUsage.size(); i++) {
555 final String pkg = allowDataUsage.valueAt(i);
556 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700557 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
558 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 final ApplicationInfo app;
560 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700561 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800562 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700563 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
564 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800565 continue;
566 }
567 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700568 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
569 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800570 continue;
571 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700572 final int uid = UserHandle.getUid(userId, app.uid);
573 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
574 if (LOGD)
575 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
576 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800577 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700578 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700579 if (LOGD)
580 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
581 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700582 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700583 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800584 }
585 }
586 return changed;
587 }
588
Felipe Lemef0823852016-06-08 13:43:08 -0700589 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700590 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700591 // Clear the states of the current whitelist
592 final int N = mPowerSaveTempWhitelistAppIds.size();
593 for (int i = 0; i < N; i++) {
594 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
595 }
596 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700597 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700598 if (whitelist != null) {
599 for (int uid : whitelist) {
600 mPowerSaveTempWhitelistAppIds.put(uid, true);
601 }
602 }
603 } catch (RemoteException e) {
604 }
605 }
606
Amith Yamasani06f08062015-06-12 13:23:33 -0700607 /**
608 * Remove unnecessary entries in the temp whitelist
609 */
Felipe Lemef0823852016-06-08 13:43:08 -0700610 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700611 final int N = mPowerSaveTempWhitelistAppIds.size();
612 for (int i = N - 1; i >= 0; i--) {
613 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
614 mPowerSaveTempWhitelistAppIds.removeAt(i);
615 }
616 }
617 }
618
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800619 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700620 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800621 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700622 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800623 // Boost thread's priority during system server init
624 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 if (!isBandwidthControlEnabled()) {
626 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
627 return;
628 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700629
Felipe Leme873a83a2016-09-07 11:34:10 -0700630 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700631
Felipe Leme873a83a2016-09-07 11:34:10 -0700632 synchronized (mUidRulesFirstLock) {
633 synchronized (mNetworkPoliciesSecondLock) {
634 updatePowerSaveWhitelistUL();
635 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
636 mPowerManagerInternal.registerLowPowerModeObserver(
637 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800638 @Override
639 public int getServiceType() {
640 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700641 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800642
643 @Override
644 public void onLowPowerModeChanged(PowerSaveState result) {
645 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800646 if (LOGD) {
647 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
648 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800649 synchronized (mUidRulesFirstLock) {
650 if (mRestrictPower != enabled) {
651 mRestrictPower = enabled;
652 updateRulesForRestrictPowerUL();
653 }
654 }
655 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800656 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800657 mRestrictPower = mPowerManagerInternal.getLowPowerState(
658 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700659
660 mSystemReady = true;
661
662 // read policy from disk
663 readPolicyAL();
664
jackqdyulei29c82ab2017-03-10 14:09:16 -0800665 // Update the restrictBackground if battery saver is turned on
666 mRestrictBackgroundBeforeBsm = mRestrictBackground;
667 mRestrictBackgroundPowerState = mPowerManagerInternal
668 .getLowPowerState(ServiceType.DATA_SAVER);
669 final boolean localRestrictBackground =
670 mRestrictBackgroundPowerState.batterySaverEnabled;
671 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
672 mRestrictBackground = localRestrictBackground;
673 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
674 mRestrictBackground ? 1 : 0, 0).sendToTarget();
675 }
676 mPowerManagerInternal.registerLowPowerModeObserver(
677 new PowerManagerInternal.LowPowerModeListener() {
678 @Override
679 public int getServiceType() {
680 return ServiceType.DATA_SAVER;
681 }
682
683 @Override
684 public void onLowPowerModeChanged(PowerSaveState result) {
685 synchronized (mUidRulesFirstLock) {
686 updateRestrictBackgroundByLowPowerModeUL(result);
687 }
688 }
689 });
690
Felipe Leme873a83a2016-09-07 11:34:10 -0700691 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
692 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700693 }
Felipe Lemef0823852016-06-08 13:43:08 -0700694
Felipe Leme873a83a2016-09-07 11:34:10 -0700695 setRestrictBackgroundUL(mRestrictBackground);
696 updateRulesForGlobalChangeAL(false);
697 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700698 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800699 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700700
Sudheer Shankae7361852017-03-07 11:51:46 -0800701 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700702 try {
703 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000704 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800705 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700706 mNetworkManager.registerObserver(mAlertObserver);
707 } catch (RemoteException e) {
708 // ignored; both services live in system_server
709 }
710
711 // listen for changes to power save whitelist
712 final IntentFilter whitelistFilter = new IntentFilter(
713 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
714 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
715
716 DeviceIdleController.LocalService deviceIdleService
717 = LocalServices.getService(DeviceIdleController.LocalService.class);
718 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
719
720 // watch for network interfaces to be claimed
721 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
722 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
723
724 // listen for package changes to update policy
725 final IntentFilter packageFilter = new IntentFilter();
726 packageFilter.addAction(ACTION_PACKAGE_ADDED);
727 packageFilter.addDataScheme("package");
728 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
729
730 // listen for UID changes to update policy
731 mContext.registerReceiver(
732 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
733
734 // listen for user changes to update policy
735 final IntentFilter userFilter = new IntentFilter();
736 userFilter.addAction(ACTION_USER_ADDED);
737 userFilter.addAction(ACTION_USER_REMOVED);
738 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
739
740 // listen for stats update events
741 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
742 mContext.registerReceiver(
743 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
744
745 // listen for restrict background changes from notifications
746 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
747 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
748
749 // listen for snooze warning from notifications
750 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
751 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
752 MANAGE_NETWORK_POLICY, mHandler);
753
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600754 // listen for configured wifi networks to be loaded
755 final IntentFilter wifiFilter =
756 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
757 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700758
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700759 // listen for carrier config changes to update data cycle information
760 final IntentFilter carrierConfigFilter = new IntentFilter(
761 ACTION_CARRIER_CONFIG_CHANGED);
762 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
763
Felipe Leme873a83a2016-09-07 11:34:10 -0700764 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800765 // tell systemReady() that the service has been initialized
766 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700767 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800768 // Restore the default priority after init is done
769 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700770 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700771 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700772 }
773
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800774 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
775 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
776 mHandler.post(() -> initService(initCompleteSignal));
777 return initCompleteSignal;
778 }
779
780 public void systemReady(CountDownLatch initCompleteSignal) {
781 // wait for initService to complete
782 try {
783 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
784 throw new IllegalStateException("Service " + TAG +" init timeout");
785 }
786 } catch (InterruptedException e) {
787 Thread.currentThread().interrupt();
788 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
789 }
790 }
791
Sudheer Shankac9d94072017-02-22 22:13:55 +0000792 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700793 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700794 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
795 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700796 }
797
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700798 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700799 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700800 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700801
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700802 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700803 }
804
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700805 @Override public void onUidIdle(int uid, boolean disabled) {
806 }
807
808 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700809 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700810 };
811
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700812 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700813 @Override
814 public void onReceive(Context context, Intent intent) {
815 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700816 synchronized (mUidRulesFirstLock) {
817 updatePowerSaveWhitelistUL();
818 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700819 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700820 }
821 }
822 };
823
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700824 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
825 @Override
826 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700827 synchronized (mUidRulesFirstLock) {
828 updatePowerSaveTempWhitelistUL();
829 updateRulesForTempWhitelistChangeUL();
830 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700831 }
832 }
833 };
834
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700835 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700836 @Override
837 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700838 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700839
840 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700841 final int uid = intent.getIntExtra(EXTRA_UID, -1);
842 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700843
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700844 if (ACTION_PACKAGE_ADDED.equals(action)) {
845 // update rules for UID, since it might be subject to
846 // global background data policy
847 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700848 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700849 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700850 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700851 }
852 }
853 };
854
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700855 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700856 @Override
857 public void onReceive(Context context, Intent intent) {
858 // on background handler thread, and UID_REMOVED is protected
859
860 final int uid = intent.getIntExtra(EXTRA_UID, -1);
861 if (uid == -1) return;
862
863 // remove any policy and update rules to clean up
864 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700865 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700866 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700867 synchronized (mNetworkPoliciesSecondLock) {
868 writePolicyAL();
869 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700870 }
871 }
872 };
873
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700874 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700875 @Override
876 public void onReceive(Context context, Intent intent) {
877 // on background handler thread, and USER_ADDED and USER_REMOVED
878 // broadcasts are protected
879
880 final String action = intent.getAction();
881 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
882 if (userId == -1) return;
883
Amith Yamasani15e472352015-04-24 19:06:07 -0700884 switch (action) {
885 case ACTION_USER_REMOVED:
886 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700887 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800888 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700889 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700890 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700891 if (action == ACTION_USER_ADDED) {
892 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700893 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700894 }
895 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700896 synchronized (mNetworkPoliciesSecondLock) {
897 updateRulesForGlobalChangeAL(true);
898 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700899 }
900 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700901 }
902 }
903 };
904
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700905 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700906 * Receiver that watches for {@link INetworkStatsService} updates, which we
907 * use to check against {@link NetworkPolicy#warningBytes}.
908 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700909 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700910 @Override
911 public void onReceive(Context context, Intent intent) {
912 // on background handler thread, and verified
913 // READ_NETWORK_USAGE_HISTORY permission above.
914
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800915 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700916 synchronized (mNetworkPoliciesSecondLock) {
917 updateNetworkEnabledNL();
918 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700919 }
920 }
921 };
922
923 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700924 * Receiver that watches for {@link Notification} control of
925 * {@link #mRestrictBackground}.
926 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700927 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700928 @Override
929 public void onReceive(Context context, Intent intent) {
930 // on background handler thread, and verified MANAGE_NETWORK_POLICY
931 // permission above.
932
933 setRestrictBackground(false);
934 }
935 };
936
937 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800938 * Receiver that watches for {@link Notification} control of
939 * {@link NetworkPolicy#lastWarningSnooze}.
940 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800942 @Override
943 public void onReceive(Context context, Intent intent) {
944 // on background handler thread, and verified MANAGE_NETWORK_POLICY
945 // permission above.
946
947 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
948 performSnooze(template, TYPE_WARNING);
949 }
950 };
951
952 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600953 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
954 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700955 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600956 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700957 @Override
958 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900959 synchronized (mUidRulesFirstLock) {
960 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600961 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700962 }
963 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600964 // Only need to perform upgrade logic once
965 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700966 }
967 };
968
969 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700970 * Observer that watches for {@link INetworkManagementService} alerts.
971 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700972 final private INetworkManagementEventObserver mAlertObserver
973 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700974 @Override
975 public void limitReached(String limitName, String iface) {
976 // only someone like NMS should be calling us
977 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
978
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800979 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
980 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700981 }
982 }
983 };
984
985 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700986 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
987 * to show visible notifications as needed.
988 */
Felipe Lemef0823852016-06-08 13:43:08 -0700989 void updateNotificationsNL() {
990 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700991
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700992 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -0400993 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700994 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700995
996 // TODO: when switching to kernel notifications, compute next future
997 // cycle boundary to recompute notifications.
998
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700999 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001000 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001001 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1002 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001003 // ignore policies that aren't relevant to user
1004 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001005 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001006
Jeff Sharkey53313d72017-07-13 16:47:32 -06001007 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1008 .cycleIterator(policy).next();
1009 final long start = cycle.first.toInstant().toEpochMilli();
1010 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001011 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001013 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001014 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001015 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1016 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001017 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001018 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001019 }
1020
Jeff Sharkey497e4432011-06-14 17:27:29 -07001021 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001022 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001023
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001024 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001025 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001026 }
1027 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001028 }
1029
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001030 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001031 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001032 final NotificationId notificationId = beforeNotifs.valueAt(i);
1033 if (!mActiveNotifs.contains(notificationId)) {
1034 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001035 }
1036 }
1037 }
1038
1039 /**
1040 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001041 * current device state, such as when
1042 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1043 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001044 */
1045 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001046 if (template.isMatchRuleMobile()) {
1047 final TelephonyManager tele = TelephonyManager.from(mContext);
1048 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001049
Jeff Sharkey32566012014-12-02 18:30:14 -08001050 // Mobile template is relevant when any active subscriber matches
1051 final int[] subIds = sub.getActiveSubscriptionIdList();
1052 for (int subId : subIds) {
1053 final String subscriberId = tele.getSubscriberId(subId);
1054 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001055 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001056 if (template.matches(probeIdent)) {
1057 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001058 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001059 }
1060 return false;
1061 } else {
1062 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001063 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001064 }
1065
1066 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001067 * Notify that given {@link NetworkTemplate} is over
1068 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1069 */
Felipe Lemef0823852016-06-08 13:43:08 -07001070 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001071 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001072 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001073 mOverLimitNotified.add(template);
1074 }
1075 }
1076
Felipe Lemef0823852016-06-08 13:43:08 -07001077 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001078 mOverLimitNotified.remove(template);
1079 }
1080
1081 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001082 * Show notification for combined {@link NetworkPolicy} and specific type,
1083 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1084 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001085 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001086 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001087 final Notification.Builder builder =
1088 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001089 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001090 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001091 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001092 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001093
1094 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001095 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001096 switch (type) {
1097 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001099 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001100
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001101 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 builder.setTicker(title);
1103 builder.setContentTitle(title);
1104 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001105 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001106 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001107
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001108 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1109 builder.setDeleteIntent(PendingIntent.getBroadcast(
1110 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1111
Wei Liu546cb772016-07-21 16:19:01 -07001112 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001113 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001114 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1115
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 break;
1117 }
1118 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001119 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001120
1121 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001122 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001123 switch (policy.template.getMatchRule()) {
1124 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001126 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001127 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001128 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001129 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001130 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001131 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001132 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001133 case MATCH_WIFI:
1134 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001135 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001136 break;
1137 default:
1138 title = null;
1139 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001140 }
1141
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001142 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001143 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001144 builder.setTicker(title);
1145 builder.setContentTitle(title);
1146 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001147
Wei Liu546cb772016-07-21 16:19:01 -07001148 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001149 builder.setContentIntent(PendingIntent.getActivity(
1150 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1151 break;
1152 }
1153 case TYPE_LIMIT_SNOOZED: {
1154 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001155 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001156 Formatter.formatFileSize(mContext, overBytes));
1157
1158 final CharSequence title;
1159 switch (policy.template.getMatchRule()) {
1160 case MATCH_MOBILE_3G_LOWER:
1161 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1162 break;
1163 case MATCH_MOBILE_4G:
1164 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1165 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001166 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001167 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1168 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001169 case MATCH_WIFI:
1170 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1171 break;
1172 default:
1173 title = null;
1174 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001175 }
1176
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001177 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001178 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001179 builder.setTicker(title);
1180 builder.setContentTitle(title);
1181 builder.setContentText(body);
1182
Wei Liu546cb772016-07-21 16:19:01 -07001183 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001184 builder.setContentIntent(PendingIntent.getActivity(
1185 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001186 break;
1187 }
1188 }
1189
1190 // TODO: move to NotificationManager once we can mock it
1191 try {
1192 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001193 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001194 builder.setStyle(new Notification.BigTextStyle()
1195 .bigText(body));
1196 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001197 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001198 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001199 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001200 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001201 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001202 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001203 }
1204 }
1205
Chris Wren193ae6b2017-03-31 15:17:11 -04001206 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001207 // TODO: move to NotificationManager once we can mock it
1208 try {
1209 final String packageName = mContext.getPackageName();
1210 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001211 packageName, notificationId.getTag(), notificationId.getId(),
1212 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001213 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001214 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001215 }
1216 }
1217
1218 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001219 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001220 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001221 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001222 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001223 @Override
1224 public void onReceive(Context context, Intent intent) {
1225 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1226 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001227
1228 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001229 synchronized (mUidRulesFirstLock) {
1230 synchronized (mNetworkPoliciesSecondLock) {
1231 ensureActiveMobilePolicyAL();
1232 normalizePoliciesNL();
1233 updateNetworkEnabledNL();
1234 updateNetworkRulesNL();
1235 updateNotificationsNL();
1236 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001237 }
1238 }
1239 };
1240
1241 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001242 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1243 * if necessary.
1244 *
1245 * @param subId that has its associated NetworkPolicy updated if necessary
1246 * @return if any policies were updated
1247 */
1248 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1249 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1250 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1251
1252 if (config == null) {
1253 return false;
1254 }
1255
1256 boolean policyUpdated = false;
1257 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1258
1259 // find and update the mobile NetworkPolicy for this subscriber id
1260 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1261 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1262 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1263 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1264 if (template.matches(probeIdent)) {
1265 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1266
1267 // only update the policy if the user didn't change any of the defaults.
1268 if (!policy.inferred) {
1269 // TODO: inferred could be split, so that if a user changes their data limit or
1270 // warning, it doesn't prevent their cycle date from being updated.
1271 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1272 continue;
1273 }
1274
1275 final int cycleDay = getCycleDayFromCarrierConfig(config, policy.cycleDay);
1276 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1277 policy.warningBytes);
1278 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1279 policy.limitBytes);
1280
1281 if (policy.cycleDay == cycleDay &&
1282 policy.warningBytes == warningBytes &&
1283 policy.limitBytes == limitBytes) {
1284 continue;
1285 }
1286
1287 policyUpdated = true;
1288 policy.cycleDay = cycleDay;
1289 policy.warningBytes = warningBytes;
1290 policy.limitBytes = limitBytes;
1291
1292 if (LOGD) {
1293 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1294 + NetworkIdentity.scrubSubscriberId(subscriberId)
1295 + " from CarrierConfigManager");
1296 }
1297 }
1298 }
1299
1300 return policyUpdated;
1301 }
1302
1303 /**
1304 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1305 *
1306 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1307 * to do so, it returns the fallback value.
1308 *
1309 * @param config The CarrierConfig to read the value from.
1310 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1311 * @return cycleDay to use in the mobile NetworkPolicy.
1312 */
1313 @VisibleForTesting
1314 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1315 int fallbackCycleDay) {
1316 if (config == null) {
1317 return fallbackCycleDay;
1318 }
1319 int cycleDay =
1320 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1321 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1322 return fallbackCycleDay;
1323 }
1324 // validate cycleDay value
1325 final Calendar cal = Calendar.getInstance();
1326 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1327 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1328 Slog.e(TAG, "Invalid date in "
1329 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1330 return fallbackCycleDay;
1331 }
1332 return cycleDay;
1333 }
1334
1335 /**
1336 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1337 *
1338 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1339 * to do so, it returns the fallback value.
1340 *
1341 * @param config The CarrierConfig to read the value from.
1342 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1343 * @return warningBytes to use in the mobile NetworkPolicy.
1344 */
1345 @VisibleForTesting
1346 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1347 long fallbackWarningBytes) {
1348 if (config == null) {
1349 return fallbackWarningBytes;
1350 }
1351 long warningBytes =
1352 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1353
1354 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1355 return WARNING_DISABLED;
1356 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1357 return getPlatformDefaultWarningBytes();
1358 } else if (warningBytes < 0) {
1359 Slog.e(TAG, "Invalid value in "
1360 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1361 + "non-negative value but got: " + warningBytes);
1362 return fallbackWarningBytes;
1363 }
1364
1365 return warningBytes;
1366 }
1367
1368 /**
1369 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1370 *
1371 * It attempts to get an appropriate value 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 fallbackLimitBytes to return if the CarrierConfig can't be read.
1376 * @return limitBytes to use in the mobile NetworkPolicy.
1377 */
1378 @VisibleForTesting
1379 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1380 long fallbackLimitBytes) {
1381 if (config == null) {
1382 return fallbackLimitBytes;
1383 }
1384 long limitBytes =
1385 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1386
1387 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1388 return LIMIT_DISABLED;
1389 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1390 return getPlatformDefaultLimitBytes();
1391 } else if (limitBytes < 0) {
1392 Slog.e(TAG, "Invalid value in "
1393 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1394 + "non-negative value but got: " + limitBytes);
1395 return fallbackLimitBytes;
1396 }
1397 return limitBytes;
1398 }
1399
1400 /**
1401 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1402 */
1403 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1404 @Override
1405 public void onReceive(Context context, Intent intent) {
1406 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1407 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1408
1409 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1410 return;
1411 }
1412 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1413 final TelephonyManager tele = TelephonyManager.from(mContext);
1414 final String subscriberId = tele.getSubscriberId(subId);
1415
1416 maybeRefreshTrustedTime();
1417 synchronized (mUidRulesFirstLock) {
1418 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001419 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001420 if (added) return;
1421 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1422 if (!updated) return;
1423 // update network and notification rules, as the data cycle changed and it's
1424 // possible that we should be triggering warnings/limits now
1425 handleNetworkPoliciesUpdateAL(true);
1426 }
1427 }
1428 }
1429 };
1430
1431 /**
1432 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1433 * one has been updated.
1434 *
1435 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1436 * update.
1437 */
1438 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1439 if (shouldNormalizePolicies) {
1440 normalizePoliciesNL();
1441 }
1442 updateNetworkEnabledNL();
1443 updateNetworkRulesNL();
1444 updateNotificationsNL();
1445 writePolicyAL();
1446 }
1447
1448 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001449 * Proactively control network data connections when they exceed
1450 * {@link NetworkPolicy#limitBytes}.
1451 */
Felipe Lemef0823852016-06-08 13:43:08 -07001452 void updateNetworkEnabledNL() {
1453 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001454
1455 // TODO: reset any policy-disabled networks when any policy is removed
1456 // completely, which is currently rare case.
1457
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001458 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001459 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1460 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001461 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001462 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001463 setNetworkTemplateEnabled(policy.template, true);
1464 continue;
1465 }
1466
Jeff Sharkey53313d72017-07-13 16:47:32 -06001467 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1468 .cycleIterator(policy).next();
1469 final long start = cycle.first.toInstant().toEpochMilli();
1470 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001471 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001472
1473 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001474 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1475 && policy.lastLimitSnooze < start;
1476 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001477
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001478 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001479 }
1480 }
1481
1482 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001483 * Proactively disable networks that match the given
1484 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001485 */
1486 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001487 // TODO: reach into ConnectivityManager to proactively disable bringing
1488 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001489
1490 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1491 // If mobile data usage hits the limit or if the user resumes the data, we need to
1492 // notify telephony.
1493 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1494 final TelephonyManager tm = TelephonyManager.from(mContext);
1495
1496 final int[] subIds = sm.getActiveSubscriptionIdList();
1497 for (int subId : subIds) {
1498 final String subscriberId = tm.getSubscriberId(subId);
1499 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1500 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1501 // Template is matched when subscriber id matches.
1502 if (template.matches(probeIdent)) {
1503 tm.setPolicyDataEnabled(enabled, subId);
1504 }
1505 }
1506 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001507 }
1508
1509 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001510 * Examine all connected {@link NetworkState}, looking for
1511 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1512 * remaining quota based on usage cycle and historical stats.
1513 */
Felipe Lemef0823852016-06-08 13:43:08 -07001514 void updateNetworkRulesNL() {
1515 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001516
1517 final NetworkState[] states;
1518 try {
1519 states = mConnManager.getAllNetworkState();
1520 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001521 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001522 return;
1523 }
1524
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001525 // First, generate identities of all connected networks so we can
1526 // quickly compare them against all defined policies below.
1527 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001528 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001529 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001530 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001531 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001532
1533 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001534 if (baseIface != null) {
1535 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001536 }
1537
1538 // Stacked interfaces are considered to have same identity as
1539 // their parent network.
1540 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1541 for (LinkProperties stackedLink : stackedLinks) {
1542 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001543 if (stackedIface != null) {
1544 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001545 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001546 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001547 }
1548 }
1549
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001550 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001551 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001552 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001553 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001554 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001556 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001557 for (int j = connIdents.size() - 1; j >= 0; j--) {
1558 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1559 if (policy.template.matches(ident.second)) {
1560 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561 }
1562 }
1563
1564 if (ifaceList.size() > 0) {
1565 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001566 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001567 }
1568 }
1569
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001570 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001571 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001572
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 // apply each policy that we found ifaces for; compute remaining data
1574 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001575 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001576 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1577 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1578 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579
Jeff Sharkey53313d72017-07-13 16:47:32 -06001580 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1581 .cycleIterator(policy).next();
1582 final long start = cycle.first.toInstant().toEpochMilli();
1583 final long end = cycle.second.toInstant().toEpochMilli();
1584 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001586 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001587 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001588 }
1589
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001590 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001591 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001592 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001593 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001594 if (!hasLimit) {
1595 // metered network, but no policy limit; we still need to
1596 // restrict apps, so push really high quota.
1597 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001598 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001599 // snoozing past quota, but we still need to restrict apps,
1600 // so push really high quota.
1601 quotaBytes = Long.MAX_VALUE;
1602 } else {
1603 // remaining "quota" bytes are based on total usage in
1604 // current cycle. kernel doesn't like 0-byte rules, so we
1605 // set 1-byte quota and disable the radio later.
1606 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1607 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001608
1609 if (ifaces.length > 1) {
1610 // TODO: switch to shared quota once NMS supports
1611 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001612 }
1613
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001614 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001615 // long quotaBytes split up into two ints to fit in message
1616 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1617 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1618 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001619 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001620 }
1621 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001622
1623 // keep track of lowest warning or limit of active policies
1624 if (hasWarning && policy.warningBytes < lowestRule) {
1625 lowestRule = policy.warningBytes;
1626 }
1627 if (hasLimit && policy.limitBytes < lowestRule) {
1628 lowestRule = policy.limitBytes;
1629 }
1630 }
1631
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001632 for (int i = connIfaces.size()-1; i >= 0; i--) {
1633 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001634 // long quotaBytes split up into two ints to fit in message
1635 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1636 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1637 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001638 newMeteredIfaces.add(iface);
1639 }
1640
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001641 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001642
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001643 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001644 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1645 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001646 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001647 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1648 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001649 }
1650 }
1651 mMeteredIfaces = newMeteredIfaces;
1652
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001653 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001654 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001655 }
1656
1657 /**
1658 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1659 * have at least a default mobile policy defined.
1660 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001661 private void ensureActiveMobilePolicyAL() {
1662 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001663 if (mSuppressDefaultPolicy) return;
1664
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001665 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001666 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001667
Jeff Sharkey32566012014-12-02 18:30:14 -08001668 final int[] subIds = sub.getActiveSubscriptionIdList();
1669 for (int subId : subIds) {
1670 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001671 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001672 }
1673 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001674
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001675 /**
1676 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1677 * have at least a default mobile policy defined.
1678 *
1679 * @param subId to build a default policy for
1680 * @param subscriberId that we check for an existing policy
1681 * @return true if a mobile network policy was added, or false one already existed.
1682 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001683 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001684 // Poke around to see if we already have a policy
1685 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001686 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001687 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1688 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1689 if (template.matches(probeIdent)) {
1690 if (LOGD) {
1691 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1692 + NetworkIdentity.scrubSubscriberId(subscriberId));
1693 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001694 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001695 }
1696 }
1697
Jeff Sharkey32566012014-12-02 18:30:14 -08001698 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1699 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001700 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001701 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001702 return true;
1703 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001704
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001705 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001706 final int dataWarningConfig = mContext.getResources().getInteger(
1707 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001708 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001709 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001710 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001711 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001712 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001713 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001714
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001715 private long getPlatformDefaultLimitBytes() {
1716 return LIMIT_DISABLED;
1717 }
1718
1719 @VisibleForTesting
1720 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1721 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1722
1723 // assume usage cycle starts today
Jeff Sharkey32566012014-12-02 18:30:14 -08001724 final Time time = new Time();
1725 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001726
Jeff Sharkey32566012014-12-02 18:30:14 -08001727 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001728
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001729 final int cycleDay = getCycleDayFromCarrierConfig(config, time.monthDay);
1730 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1731 getPlatformDefaultWarningBytes());
1732 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1733 getPlatformDefaultLimitBytes());
1734
Jeff Sharkey32566012014-12-02 18:30:14 -08001735 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1736 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001737 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1738 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001739 }
1740
Felipe Lemef0823852016-06-08 13:43:08 -07001741 private void readPolicyAL() {
1742 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001743
1744 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001745 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001746 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001747
1748 FileInputStream fis = null;
1749 try {
1750 fis = mPolicyFile.openRead();
1751 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001752 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001753
Felipe Leme46b451f2016-08-19 08:46:17 -07001754 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1755 // to skip UIDs that were explicitly blacklisted.
1756 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1757
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001758 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001759 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001760 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001761 while ((type = in.next()) != END_DOCUMENT) {
1762 final String tag = in.getName();
1763 if (type == START_TAG) {
1764 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001765 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001766 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001767 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1768 mRestrictBackground = readBooleanAttribute(
1769 in, ATTR_RESTRICT_BACKGROUND);
1770 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001771 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001772 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001773 if (mRestrictBackground != oldValue) {
1774 // Some early services may have read the default value,
1775 // so notify them that it's changed
1776 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1777 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1778 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001779
1780 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1781 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1782 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001783 final String networkId;
1784 if (version >= VERSION_ADDED_NETWORK_ID) {
1785 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1786 } else {
1787 networkId = null;
1788 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001789 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001790 final String cycleTimezone;
1791 if (version >= VERSION_ADDED_TIMEZONE) {
1792 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1793 } else {
1794 cycleTimezone = Time.TIMEZONE_UTC;
1795 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001796 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1797 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001798 final long lastLimitSnooze;
1799 if (version >= VERSION_SPLIT_SNOOZE) {
1800 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1801 } else if (version >= VERSION_ADDED_SNOOZE) {
1802 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001803 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001804 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001805 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001806 final boolean metered;
1807 if (version >= VERSION_ADDED_METERED) {
1808 metered = readBooleanAttribute(in, ATTR_METERED);
1809 } else {
1810 switch (networkTemplate) {
1811 case MATCH_MOBILE_3G_LOWER:
1812 case MATCH_MOBILE_4G:
1813 case MATCH_MOBILE_ALL:
1814 metered = true;
1815 break;
1816 default:
1817 metered = false;
1818 }
1819 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001820 final long lastWarningSnooze;
1821 if (version >= VERSION_SPLIT_SNOOZE) {
1822 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1823 } else {
1824 lastWarningSnooze = SNOOZE_NEVER;
1825 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001826 final boolean inferred;
1827 if (version >= VERSION_ADDED_INFERRED) {
1828 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1829 } else {
1830 inferred = false;
1831 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001832
Jeff Sharkey32566012014-12-02 18:30:14 -08001833 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1834 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001835 if (template.isPersistable()) {
1836 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1837 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1838 lastLimitSnooze, metered, inferred));
1839 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001840 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001841 final int uid = readIntAttribute(in, ATTR_UID);
1842 final int policy = readIntAttribute(in, ATTR_POLICY);
1843
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001844 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001845 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001846 } else {
1847 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1848 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001849 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001850 final int appId = readIntAttribute(in, ATTR_APP_ID);
1851 final int policy = readIntAttribute(in, ATTR_POLICY);
1852
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001853 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001854 // app policy is deprecated so this is only used in pre system user split.
1855 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001856 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001857 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001858 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001859 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001860 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001861 } else if (TAG_WHITELIST.equals(tag)) {
1862 insideWhitelist = true;
1863 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1864 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001865 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001866 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1867 final int uid = readIntAttribute(in, ATTR_UID);
1868 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001869 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001870 } else if (type == END_TAG) {
1871 if (TAG_WHITELIST.equals(tag)) {
1872 insideWhitelist = false;
1873 }
1874
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001875 }
1876 }
1877
Felipe Leme46b451f2016-08-19 08:46:17 -07001878 final int size = whitelistedRestrictBackground.size();
1879 for (int i = 0; i < size; i++) {
1880 final int uid = whitelistedRestrictBackground.keyAt(i);
1881 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1882 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1883 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1884 + " because its policy is " + uidPoliciesToString(policy));
1885 continue;
1886 }
1887 if (UserHandle.isApp(uid)) {
1888 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1889 if (LOGV)
1890 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1891 setUidPolicyUncheckedUL(uid, newPolicy, false);
1892 } else {
1893 Slog.w(TAG, "unable to update policy on UID " + uid);
1894 }
1895 }
1896
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001897 } catch (FileNotFoundException e) {
1898 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001899 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001900 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001901 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001902 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001903 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001904 } finally {
1905 IoUtils.closeQuietly(fis);
1906 }
1907 }
1908
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001909 /**
1910 * Upgrade legacy background data flags, notifying listeners of one last
1911 * change to always-true.
1912 */
Felipe Lemef0823852016-06-08 13:43:08 -07001913 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001914 mRestrictBackground = Settings.Secure.getInt(
1915 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1916
1917 // kick off one last broadcast if restricted
1918 if (mRestrictBackground) {
1919 final Intent broadcast = new Intent(
1920 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001921 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001922 }
1923 }
1924
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001925 /**
1926 * Perform upgrade step of moving any user-defined meterness overrides over
1927 * into {@link WifiConfiguration}.
1928 */
1929 private void upgradeWifiMeteredOverrideAL() {
1930 boolean modified = false;
1931 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1932 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1933 for (int i = 0; i < mNetworkPolicy.size(); ) {
1934 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1935 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
1936 && !policy.inferred) {
1937 mNetworkPolicy.removeAt(i);
1938 modified = true;
1939
1940 final String networkId = resolveNetworkId(policy.template.getNetworkId());
1941 for (WifiConfiguration config : configs) {
1942 if (Objects.equals(resolveNetworkId(config), networkId)) {
1943 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
1944 config.meteredOverride = policy.metered
1945 ? WifiConfiguration.METERED_OVERRIDE_METERED
1946 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
1947 wm.updateNetwork(config);
1948 }
1949 }
1950 } else {
1951 i++;
1952 }
1953 }
1954 if (modified) {
1955 writePolicyAL();
1956 }
1957 }
1958
Felipe Lemef0823852016-06-08 13:43:08 -07001959 void writePolicyAL() {
1960 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961
1962 FileOutputStream fos = null;
1963 try {
1964 fos = mPolicyFile.startWrite();
1965
1966 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001967 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001968 out.startDocument(null, true);
1969
1970 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001971 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001972 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001973
1974 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001975 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1976 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001977 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001978 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001979
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001980 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001981 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1982 final String subscriberId = template.getSubscriberId();
1983 if (subscriberId != null) {
1984 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001985 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001986 final String networkId = template.getNetworkId();
1987 if (networkId != null) {
1988 out.attribute(null, ATTR_NETWORK_ID, networkId);
1989 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001990 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001991 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001992 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1993 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001994 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1995 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001996 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001997 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998 out.endTag(null, TAG_NETWORK_POLICY);
1999 }
2000
2001 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002002 for (int i = 0; i < mUidPolicy.size(); i++) {
2003 final int uid = mUidPolicy.keyAt(i);
2004 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002005
Jeff Sharkey497e4432011-06-14 17:27:29 -07002006 // skip writing empty policies
2007 if (policy == POLICY_NONE) continue;
2008
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002009 out.startTag(null, TAG_UID_POLICY);
2010 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002011 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002012 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002013 }
2014
2015 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002016
2017 // write all whitelists
2018 out.startTag(null, TAG_WHITELIST);
2019
Felipe Lemea9505cc2016-02-26 10:28:41 -08002020 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002021 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002022 for (int i = 0; i < size; i++) {
2023 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2024 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2025 writeIntAttribute(out, ATTR_UID, uid);
2026 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2027 }
2028
Felipe Lemeb85a6372016-01-14 16:16:16 -08002029 out.endTag(null, TAG_WHITELIST);
2030
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002031 out.endDocument();
2032
2033 mPolicyFile.finishWrite(fos);
2034 } catch (IOException e) {
2035 if (fos != null) {
2036 mPolicyFile.failWrite(fos);
2037 }
2038 }
2039 }
2040
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002041 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002042 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002043 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002044
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002045 if (!UserHandle.isApp(uid)) {
2046 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002047 }
Felipe Lemef0823852016-06-08 13:43:08 -07002048 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002049 final long token = Binder.clearCallingIdentity();
2050 try {
2051 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2052 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002053 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002054 }
2055 } finally {
2056 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002057 }
2058 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002059 }
2060
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002061 @Override
2062 public void addUidPolicy(int uid, int policy) {
2063 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002064
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002065 if (!UserHandle.isApp(uid)) {
2066 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2067 }
2068
Felipe Lemef0823852016-06-08 13:43:08 -07002069 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002070 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2071 policy |= oldPolicy;
2072 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002073 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002074 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002075 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002076 }
2077
2078 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002079 public void removeUidPolicy(int uid, int policy) {
2080 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2081
2082 if (!UserHandle.isApp(uid)) {
2083 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2084 }
2085
Felipe Lemef0823852016-06-08 13:43:08 -07002086 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002087 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2088 policy = oldPolicy & ~policy;
2089 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002090 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002091 }
2092 }
2093 }
2094
Felipe Lemef0823852016-06-08 13:43:08 -07002095 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2096 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002097
Felipe Leme57e3d312016-08-23 14:42:52 -07002098 final boolean notifyApp;
2099 if (!isUidValidForWhitelistRules(uid)) {
2100 notifyApp = false;
2101 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002102 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2103 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2104 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2105 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002106 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2107 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002108 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2109 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2110 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2111 if (LOGD)
2112 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2113 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2114 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002115 notifyApp = wasBlocked != isBlocked;
2116 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002117 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2118 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002119 }
2120
Felipe Lemef0823852016-06-08 13:43:08 -07002121 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002122 if (policy == POLICY_NONE) {
2123 mUidPolicy.delete(uid);
2124 } else {
2125 mUidPolicy.put(uid, policy);
2126 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002127
2128 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002129 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002130 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002131 synchronized (mNetworkPoliciesSecondLock) {
2132 writePolicyAL();
2133 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002134 }
2135 }
2136
2137 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002138 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002139 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2140
Felipe Lemef0823852016-06-08 13:43:08 -07002141 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002142 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002143 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002144 }
2145
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002146 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002147 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002148 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2149
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002150 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002151 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002152 for (int i = 0; i < mUidPolicy.size(); i++) {
2153 final int uid = mUidPolicy.keyAt(i);
2154 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002155 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2156 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002157 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002158 }
2159 }
2160 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002161 return uids;
2162 }
2163
2164 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002165 * Removes any persistable state associated with given {@link UserHandle}, persisting
2166 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002167 */
Felipe Lemef0823852016-06-08 13:43:08 -07002168 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002169
Felipe Lemef0823852016-06-08 13:43:08 -07002170 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002171 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002172
Felipe Lemea110eec2016-04-29 09:58:06 -07002173 // Remove entries from revoked default restricted background UID whitelist
2174 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2175 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2176 if (UserHandle.getUserId(uid) == userId) {
2177 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002178 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002179 }
2180 }
2181
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002182 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002183 int[] uids = new int[0];
2184 for (int i = 0; i < mUidPolicy.size(); i++) {
2185 final int uid = mUidPolicy.keyAt(i);
2186 if (UserHandle.getUserId(uid) == userId) {
2187 uids = appendInt(uids, uid);
2188 }
2189 }
2190
2191 if (uids.length > 0) {
2192 for (int uid : uids) {
2193 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002194 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002195 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002196 }
Felipe Lemef0823852016-06-08 13:43:08 -07002197 synchronized (mNetworkPoliciesSecondLock) {
2198 updateRulesForGlobalChangeAL(true);
2199 if (writePolicy && changed) {
2200 writePolicyAL();
2201 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002202 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002203 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002204 }
2205
2206 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002207 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002208 // TODO: create permission for observing network policy
2209 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002210 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002211 }
2212
2213 @Override
2214 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002215 // TODO: create permission for observing network policy
2216 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002217 mListeners.unregister(listener);
2218 }
2219
Jeff Sharkey1b861272011-05-22 00:34:52 -07002220 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002221 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002222 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2223
Felipe Leme6a05eee2016-02-19 14:43:51 -08002224 final long token = Binder.clearCallingIdentity();
2225 try {
2226 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002227 synchronized (mUidRulesFirstLock) {
2228 synchronized (mNetworkPoliciesSecondLock) {
2229 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002230 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002231 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002232 }
2233 } finally {
2234 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002235 }
2236 }
2237
Hugo Benichi446c9c92017-04-10 09:41:10 +09002238 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002239 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002240 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2241 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002242 }
2243
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002244 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002245 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002246 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002247 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002248 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2249 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2250 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002251 } catch (SecurityException e) {
2252 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002253
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002254 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2255 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2256 return new NetworkPolicy[0];
2257 }
Svet Ganov16a16892015-04-16 10:32:04 -07002258 }
2259
Felipe Lemef0823852016-06-08 13:43:08 -07002260 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002261 final int size = mNetworkPolicy.size();
2262 final NetworkPolicy[] policies = new NetworkPolicy[size];
2263 for (int i = 0; i < size; i++) {
2264 policies[i] = mNetworkPolicy.valueAt(i);
2265 }
2266 return policies;
2267 }
2268 }
2269
Felipe Lemef0823852016-06-08 13:43:08 -07002270 private void normalizePoliciesNL() {
2271 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002272 }
2273
Felipe Lemef0823852016-06-08 13:43:08 -07002274 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002275 final TelephonyManager tele = TelephonyManager.from(mContext);
2276 final String[] merged = tele.getMergedSubscriberIds();
2277
2278 mNetworkPolicy.clear();
2279 for (NetworkPolicy policy : policies) {
2280 // When two normalized templates conflict, prefer the most
2281 // restrictive policy
2282 policy.template = NetworkTemplate.normalize(policy.template, merged);
2283 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2284 if (existing == null || existing.compareTo(policy) > 0) {
2285 if (existing != null) {
2286 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2287 }
2288 mNetworkPolicy.put(policy.template, policy);
2289 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002290 }
2291 }
2292
2293 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002294 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002295 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002296
2297 final long token = Binder.clearCallingIdentity();
2298 try {
2299 performSnooze(template, TYPE_LIMIT);
2300 } finally {
2301 Binder.restoreCallingIdentity(token);
2302 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002303 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002304
Dianne Hackborn497175b2014-07-01 12:56:08 -07002305 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002306 maybeRefreshTrustedTime();
2307 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002308 synchronized (mUidRulesFirstLock) {
2309 synchronized (mNetworkPoliciesSecondLock) {
2310 // find and snooze local policy that matches
2311 final NetworkPolicy policy = mNetworkPolicy.get(template);
2312 if (policy == null) {
2313 throw new IllegalArgumentException("unable to find policy for " + template);
2314 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002315
Felipe Lemef0823852016-06-08 13:43:08 -07002316 switch (type) {
2317 case TYPE_WARNING:
2318 policy.lastWarningSnooze = currentTime;
2319 break;
2320 case TYPE_LIMIT:
2321 policy.lastLimitSnooze = currentTime;
2322 break;
2323 default:
2324 throw new IllegalArgumentException("unexpected type");
2325 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002326
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002327 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002328 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002329 }
2330 }
2331
2332 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002333 public void onTetheringChanged(String iface, boolean tethering) {
2334 // No need to enforce permission because setRestrictBackground() will do it.
2335 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002336 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002337 if (mRestrictBackground && tethering) {
2338 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2339 setRestrictBackground(false);
2340 }
2341 }
2342 }
2343
2344 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002345 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002346 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002347 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002348 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2349 final long token = Binder.clearCallingIdentity();
2350 try {
2351 maybeRefreshTrustedTime();
2352 synchronized (mUidRulesFirstLock) {
2353 if (restrictBackground == mRestrictBackground) {
2354 // Ideally, UI should never allow this scenario...
2355 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2356 return;
2357 }
2358 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002359 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002360
2361 } finally {
2362 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002363 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002364
Felipe Leme29e72ea2016-09-08 13:26:55 -07002365 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2366 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002367 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002368 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002369 }
2370 }
2371
Felipe Lemef0823852016-06-08 13:43:08 -07002372 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002373 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002374 final boolean oldRestrictBackground = mRestrictBackground;
2375 mRestrictBackground = restrictBackground;
2376 // Must whitelist foreground apps before turning data saver mode on.
2377 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2378 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002379 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002380 try {
2381 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2382 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2383 mRestrictBackground = oldRestrictBackground;
2384 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002385 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002386 return;
2387 }
2388 } catch (RemoteException e) {
2389 // ignored; service lives in system_server
2390 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002391
2392 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2393 mRestrictBackgroundChangedInBsm = true;
2394 }
Felipe Lemef0823852016-06-08 13:43:08 -07002395 synchronized (mNetworkPoliciesSecondLock) {
2396 updateNotificationsNL();
2397 writePolicyAL();
2398 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002399 }
2400
Felipe Lemeb85a6372016-01-14 16:16:16 -08002401 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002402 public int getRestrictBackgroundByCaller() {
2403 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2404 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002405
Felipe Lemef0823852016-06-08 13:43:08 -07002406 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002407 // Must clear identity because getUidPolicy() is restricted to system.
2408 final long token = Binder.clearCallingIdentity();
2409 final int policy;
2410 try {
2411 policy = getUidPolicy(uid);
2412 } finally {
2413 Binder.restoreCallingIdentity(token);
2414 }
2415 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2416 // App is blacklisted.
2417 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2418 }
Felipe Leme1b103232016-01-22 09:44:57 -08002419 if (!mRestrictBackground) {
2420 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2421 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002422 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002423 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2424 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2425 }
2426 }
2427
2428 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002429 public boolean getRestrictBackground() {
2430 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2431
Felipe Lemef0823852016-06-08 13:43:08 -07002432 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002433 return mRestrictBackground;
2434 }
2435 }
2436
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002437 @Override
2438 public void setDeviceIdleMode(boolean enabled) {
2439 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002440 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2441 try {
2442 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002443 if (mDeviceIdleMode == enabled) {
2444 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002445 }
Felipe Lemeea014392016-09-06 13:59:54 -07002446 mDeviceIdleMode = enabled;
2447 if (mSystemReady) {
2448 // Device idle change means we need to rebuild rules for all
2449 // known apps, so do a global refresh.
2450 updateRulesForRestrictPowerUL();
2451 }
2452 }
2453 if (enabled) {
2454 EventLogTags.writeDeviceIdleOnPhase("net");
2455 } else {
2456 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002457 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002458 } finally {
2459 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002460 }
2461 }
2462
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002463 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002464 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2465 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002466 final long token = Binder.clearCallingIdentity();
2467 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002468 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2469 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2470 for (WifiConfiguration config : configs) {
2471 if (Objects.equals(resolveNetworkId(config), networkId)) {
2472 config.meteredOverride = meteredOverride;
2473 wm.updateNetwork(config);
2474 }
2475 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002476 } finally {
2477 Binder.restoreCallingIdentity(token);
2478 }
2479 }
2480
Jeff Sharkey46645002011-07-27 21:11:21 -07002481 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002482 @Deprecated
2483 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2484 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2485 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2486 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002487 }
2488
Jeff Sharkey53313d72017-07-13 16:47:32 -06002489 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2490 // Verify they're not lying about package name
2491 mAppOps.checkPackage(callingUid, callingPackage);
2492
2493 // Verify they have phone permission from user
2494 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
2495 if (mAppOps.checkOp(AppOpsManager.OP_READ_PHONE_STATE, callingUid,
2496 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2497 throw new SecurityException(
2498 "Calling package " + callingPackage + " does not hold " + READ_PHONE_STATE);
2499 }
2500
2501 final SubscriptionInfo si;
2502 final long token = Binder.clearCallingIdentity();
2503 try {
2504 si = mContext.getSystemService(SubscriptionManager.class)
2505 .getActiveSubscriptionInfo(subId);
2506 } finally {
2507 Binder.restoreCallingIdentity(token);
2508 }
2509
2510 // First check: does caller have carrier access?
2511 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2512 Slog.v(TAG, "Granting access because " + callingPackage + " is carrier");
2513 return;
2514 }
2515
2516 // Second check: was caller first to claim this HNI?
2517 // TODO: extend to support external data sources
2518
2519 // Final check: does caller have fallback permission?
2520 if (mContext.checkCallingOrSelfPermission(
2521 MANAGE_FALLBACK_SUBSCRIPTION_PLANS) == PERMISSION_GRANTED) {
2522 Slog.v(TAG, "Granting access because " + callingPackage + " is fallback");
2523 return;
2524 }
2525
2526 throw new SecurityException("Calling package " + callingPackage
2527 + " has no access to subscription plans for " + subId);
2528 }
2529
2530 @Override
2531 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2532 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2533
2534 // TODO: extend to support external data sources
2535 if (!"com.android.settings".equals(callingPackage)) {
2536 throw new UnsupportedOperationException();
2537 }
2538
2539 final String fake = SystemProperties.get("fw.fake_plan");
2540 if (!TextUtils.isEmpty(fake)) {
2541 final List<SubscriptionPlan> plans = new ArrayList<>();
2542 if ("month_hard".equals(fake)) {
2543 plans.add(SubscriptionPlan.Builder
2544 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2545 .setTitle("G-Mobile")
2546 .setDataWarning(2 * TrafficStats.GB_IN_BYTES)
2547 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2548 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2549 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2550 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2551 .build());
2552 } else if ("month_soft".equals(fake)) {
2553 plans.add(SubscriptionPlan.Builder
2554 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2555 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2556 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2557 + "that should be cut off to prevent UI from looking terrible")
2558 .setDataWarning(2 * TrafficStats.GB_IN_BYTES)
2559 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2560 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2561 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2562 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2563 .build());
2564 } else if ("month_none".equals(fake)) {
2565 plans.add(SubscriptionPlan.Builder
2566 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2567 .setTitle("G-Mobile")
2568 .build());
2569 } else if ("prepaid".equals(fake)) {
2570 plans.add(SubscriptionPlan.Builder
2571 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2572 ZonedDateTime.now().plusDays(10))
2573 .setTitle("G-Mobile")
2574 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2575 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2576 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2577 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2578 .build());
2579 } else if ("prepaid_crazy".equals(fake)) {
2580 plans.add(SubscriptionPlan.Builder
2581 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2582 ZonedDateTime.now().plusDays(10))
2583 .setTitle("G-Mobile Anytime")
2584 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2585 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2586 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2587 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2588 .build());
2589 plans.add(SubscriptionPlan.Builder
2590 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2591 ZonedDateTime.now().plusDays(20))
2592 .setTitle("G-Mobile Nickel Nights")
2593 .setSummary("5¢/GB between 1-5AM")
2594 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2595 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2596 .build());
2597 plans.add(SubscriptionPlan.Builder
2598 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2599 ZonedDateTime.now().plusDays(20))
2600 .setTitle("G-Mobile Bonus 3G")
2601 .setSummary("Unlimited 3G data")
2602 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2603 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2604 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2605 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2606 .build());
2607 }
2608 return plans.toArray(new SubscriptionPlan[plans.size()]);
2609 }
2610
2611 final long token = Binder.clearCallingIdentity();
2612 try {
2613 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2614 final NetworkTemplate template = NetworkTemplate
2615 .buildTemplateMobileAll(tm.getSubscriberId(subId));
2616 final NetworkPolicy policy = mNetworkPolicy.get(template);
2617 if (policy != null) {
2618 return new SubscriptionPlan[] { SubscriptionPlan.convert(policy) };
2619 } else {
2620 return new SubscriptionPlan[0];
2621 }
2622 } finally {
2623 Binder.restoreCallingIdentity(token);
2624 }
2625 }
2626
2627 @Override
2628 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2629 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2630
2631 // TODO: extend to support external data sources
2632 if (!"com.android.settings".equals(callingPackage)) {
2633 throw new UnsupportedOperationException();
2634 }
2635
2636 final long token = Binder.clearCallingIdentity();
2637 try {
2638 final TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
2639 final NetworkTemplate template = NetworkTemplate
2640 .buildTemplateMobileAll(tm.getSubscriberId(subId));
2641 if (ArrayUtils.isEmpty(plans)) {
2642 mNetworkPolicy.remove(template);
2643 } else {
2644 final NetworkPolicy policy = SubscriptionPlan.convert(plans[0]);
2645 policy.template = template;
2646 mNetworkPolicy.put(template, policy);
2647 }
2648 } finally {
2649 Binder.restoreCallingIdentity(token);
2650 }
2651 }
2652
2653 @Override
2654 public String getSubscriptionPlanOwner(int subId) {
2655 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2656
2657 // TODO: extend to support external data sources
2658 return "com.android.settings";
2659 }
2660
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002661 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002662 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002663 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002664
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002665 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2666
Dianne Hackborn497175b2014-07-01 12:56:08 -07002667 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002668 for (String arg : args) {
2669 argSet.add(arg);
2670 }
2671
Felipe Lemef0823852016-06-08 13:43:08 -07002672 synchronized (mUidRulesFirstLock) {
2673 synchronized (mNetworkPoliciesSecondLock) {
2674 if (argSet.contains("--unsnooze")) {
2675 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2676 mNetworkPolicy.valueAt(i).clearSnooze();
2677 }
2678
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002679 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002680
2681 fout.println("Cleared snooze timestamps");
2682 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002683 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002684
Felipe Lemef0823852016-06-08 13:43:08 -07002685 fout.print("System ready: "); fout.println(mSystemReady);
2686 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2687 fout.print("Restrict power: "); fout.println(mRestrictPower);
2688 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2689 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002690 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002691 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2692 fout.println(mNetworkPolicy.valueAt(i).toString());
2693 }
2694 fout.decreaseIndent();
2695
2696 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2697
2698 fout.println("Policy for UIDs:");
2699 fout.increaseIndent();
2700 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002701 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002702 final int uid = mUidPolicy.keyAt(i);
2703 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002704 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002705 fout.print(uid);
2706 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002707 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002708 fout.println();
2709 }
2710 fout.decreaseIndent();
2711
2712 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2713 if (size > 0) {
2714 fout.println("Power save whitelist (except idle) app ids:");
2715 fout.increaseIndent();
2716 for (int i = 0; i < size; i++) {
2717 fout.print("UID=");
2718 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2719 fout.print(": ");
2720 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2721 fout.println();
2722 }
2723 fout.decreaseIndent();
2724 }
2725
2726 size = mPowerSaveWhitelistAppIds.size();
2727 if (size > 0) {
2728 fout.println("Power save whitelist app ids:");
2729 fout.increaseIndent();
2730 for (int i = 0; i < size; i++) {
2731 fout.print("UID=");
2732 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2733 fout.print(": ");
2734 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2735 fout.println();
2736 }
2737 fout.decreaseIndent();
2738 }
2739
Felipe Lemef0823852016-06-08 13:43:08 -07002740 size = mDefaultRestrictBackgroundWhitelistUids.size();
2741 if (size > 0) {
2742 fout.println("Default restrict background whitelist uids:");
2743 fout.increaseIndent();
2744 for (int i = 0; i < size; i++) {
2745 fout.print("UID=");
2746 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2747 fout.println();
2748 }
2749 fout.decreaseIndent();
2750 }
2751
2752 size = mRestrictBackgroundWhitelistRevokedUids.size();
2753 if (size > 0) {
2754 fout.println("Default restrict background whitelist uids revoked by users:");
2755 fout.increaseIndent();
2756 for (int i = 0; i < size; i++) {
2757 fout.print("UID=");
2758 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2759 fout.println();
2760 }
2761 fout.decreaseIndent();
2762 }
2763
2764 final SparseBooleanArray knownUids = new SparseBooleanArray();
2765 collectKeys(mUidState, knownUids);
2766 collectKeys(mUidRules, knownUids);
2767
2768 fout.println("Status for all known UIDs:");
2769 fout.increaseIndent();
2770 size = knownUids.size();
2771 for (int i = 0; i < size; i++) {
2772 final int uid = knownUids.keyAt(i);
2773 fout.print("UID=");
2774 fout.print(uid);
2775
2776 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2777 fout.print(" state=");
2778 fout.print(state);
2779 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2780 fout.print(" (fg)");
2781 } else {
2782 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2783 ? " (fg svc)" : " (bg)");
2784 }
2785
2786 final int uidRules = mUidRules.get(uid, RULE_NONE);
2787 fout.print(" rules=");
2788 fout.print(uidRulesToString(uidRules));
2789 fout.println();
2790 }
2791 fout.decreaseIndent();
2792
2793 fout.println("Status for just UIDs with rules:");
2794 fout.increaseIndent();
2795 size = mUidRules.size();
2796 for (int i = 0; i < size; i++) {
2797 final int uid = mUidRules.keyAt(i);
2798 fout.print("UID=");
2799 fout.print(uid);
2800 final int uidRules = mUidRules.get(uid, RULE_NONE);
2801 fout.print(" rules=");
2802 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002803 fout.println();
2804 }
2805 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002806
2807 fout.println("Observed uid state changes:");
2808 fout.increaseIndent();
2809 mObservedHistory.dumpUL(fout);
2810 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002811 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002812 }
2813 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002814
2815 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002816 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002817 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002818 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002819 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002820 }
2821
2822 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002823 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002824 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2825
Felipe Lemef0823852016-06-08 13:43:08 -07002826 synchronized (mUidRulesFirstLock) {
2827 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002828 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002829 }
2830
Felipe Lemef0823852016-06-08 13:43:08 -07002831 private boolean isUidForegroundUL(int uid) {
2832 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002833 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2834 }
2835
Felipe Lemef0823852016-06-08 13:43:08 -07002836 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002837 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002838 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002839 }
2840
Felipe Lemef0823852016-06-08 13:43:08 -07002841 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002842 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2843 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2844 }
2845
Felipe Lemef0823852016-06-08 13:43:08 -07002846 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002847 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002848 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002849 }
2850
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002851 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002852 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002853 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2854 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002855 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002856 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002857 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2858 try {
2859 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2860 if (oldUidState != uidState) {
2861 // state changed, push updated rules
2862 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002863 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2864 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2865 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2866 if (isUidIdle(uid)) {
2867 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002868 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002869 if (mDeviceIdleMode) {
2870 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002871 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002872 if (mRestrictPower) {
2873 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002874 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002875 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002876 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002877 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002878 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002879 } finally {
2880 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002881 }
2882 }
2883
Felipe Lemef0823852016-06-08 13:43:08 -07002884 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002885 final int index = mUidState.indexOfKey(uid);
2886 if (index >= 0) {
2887 final int oldUidState = mUidState.valueAt(index);
2888 mUidState.removeAt(index);
2889 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002890 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002891 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002892 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002893 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002894 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002895 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002896 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002897 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002898 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002899 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002900 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002901 }
2902 }
2903
Felipe Lemef28983d2016-03-25 12:18:23 -07002904 // adjust stats accounting based on foreground status
2905 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002906 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2907 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2908 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2909 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002910 try {
2911 mNetworkStats.setUidForeground(uid, uidForeground);
2912 } catch (RemoteException e) {
2913 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002914 } finally {
2915 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002916 }
2917 }
2918
Sudheer Shankac9d94072017-02-22 22:13:55 +00002919 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2920 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002921 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002922 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002923 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002924 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002925 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002926 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002927 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002928 }
2929
Felipe Lemef0823852016-06-08 13:43:08 -07002930 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002931 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2932 try {
2933 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2934 mUidFirewallPowerSaveRules);
2935 } finally {
2936 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2937 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002938 }
2939
Felipe Lemef0823852016-06-08 13:43:08 -07002940 void updateRuleForRestrictPowerUL(int uid) {
2941 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002942 }
2943
Felipe Lemef0823852016-06-08 13:43:08 -07002944 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002945 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2946 try {
2947 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2948 mUidFirewallDozableRules);
2949 } finally {
2950 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2951 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002952 }
2953
Felipe Lemef0823852016-06-08 13:43:08 -07002954 void updateRuleForDeviceIdleUL(int uid) {
2955 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002956 }
2957
Felipe Lemef28983d2016-03-25 12:18:23 -07002958 // NOTE: since both fw_dozable and fw_powersave uses the same map
2959 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002960 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002961 SparseIntArray rules) {
2962 if (enabled) {
2963 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002964 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002965 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002966 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002967 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002968 for (int ui = users.size() - 1; ui >= 0; ui--) {
2969 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002970 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
2971 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
2972 if (chain == FIREWALL_CHAIN_POWERSAVE) {
2973 updateRulesForWhitelistedAppIds(uidRules,
2974 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002975 }
2976 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002977 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002978 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002979 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2980 }
2981 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002982 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2983 } else {
2984 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002985 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002986 }
2987
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002988 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
2989 final SparseBooleanArray whitelistedAppIds, int userId) {
2990 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
2991 if (whitelistedAppIds.valueAt(i)) {
2992 final int appId = whitelistedAppIds.keyAt(i);
2993 final int uid = UserHandle.getUid(userId, appId);
2994 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2995 }
2996 }
2997 }
2998
2999 /**
3000 * @param deviceIdleMode if true then we don't consider
3001 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3002 * whitelisted.
3003 */
3004 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003005 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003006 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3007 || mPowerSaveWhitelistAppIds.get(appId);
3008 if (!deviceIdleMode) {
3009 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3010 }
3011 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003012 }
3013
Felipe Lemef28983d2016-03-25 12:18:23 -07003014 // NOTE: since both fw_dozable and fw_powersave uses the same map
3015 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003016 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003017 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003018 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3019 chain == FIREWALL_CHAIN_DOZABLE);
3020 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003021 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003022 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003023 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003024 }
3025 }
3026 }
3027
Felipe Lemef0823852016-06-08 13:43:08 -07003028 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003029 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3030 try {
3031 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3032 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003033
Felipe Leme873a83a2016-09-07 11:34:10 -07003034 // Fully update the app idle firewall chain.
3035 final List<UserInfo> users = mUserManager.getUsers();
3036 for (int ui = users.size() - 1; ui >= 0; ui--) {
3037 UserInfo user = users.get(ui);
3038 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3039 for (int uid : idleUids) {
3040 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3041 // quick check: if this uid doesn't have INTERNET permission, it
3042 // doesn't have network access anyway, so it is a waste to mess
3043 // with it here.
3044 if (hasInternetPermissions(uid)) {
3045 uidRules.put(uid, FIREWALL_RULE_DENY);
3046 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003047 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003048 }
3049 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003050
Felipe Lemebc853dd2016-09-08 13:26:55 -07003051 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003052 } finally {
3053 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3054 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003055 }
3056
Felipe Lemef0823852016-06-08 13:43:08 -07003057 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003058 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003059
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003060 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3061 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3062 }
3063 try {
3064 int appId = UserHandle.getAppId(uid);
3065 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3066 && !isUidForegroundOnRestrictPowerUL(uid)) {
3067 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3068 } else {
3069 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3070 }
3071 } finally {
3072 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003073 }
3074 }
3075
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003076 /**
3077 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3078 * changed.
3079 */
Felipe Lemef0823852016-06-08 13:43:08 -07003080 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003081 boolean paroled = mUsageStats.isAppIdleParoleOn();
3082 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003083 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003084
3085 int ruleCount = mUidFirewallStandbyRules.size();
3086 for (int i = 0; i < ruleCount; i++) {
3087 int uid = mUidFirewallStandbyRules.keyAt(i);
3088 int oldRules = mUidRules.get(uid);
3089 if (enableChain) {
3090 // Chain wasn't enabled before and the other power-related
3091 // chains are whitelists, so we can clear the
3092 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3093 // the effective rules result in blocking network access.
3094 oldRules &= MASK_METERED_NETWORKS;
3095 } else {
3096 // Skip if it had no restrictions to begin with
3097 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3098 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003099 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3100 if (newUidRules == RULE_NONE) {
3101 mUidRules.delete(uid);
3102 } else {
3103 mUidRules.put(uid, newUidRules);
3104 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003105 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003106 }
3107
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003108 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003109 * Update rules that might be changed by {@link #mRestrictBackground},
3110 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003111 */
Felipe Lemef0823852016-06-08 13:43:08 -07003112 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003113 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3114 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3115 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3116 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003117 try {
Felipe Leme09700462016-09-08 09:33:48 -07003118 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003119 updateRulesForRestrictPowerUL();
3120 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003121
Felipe Leme873a83a2016-09-07 11:34:10 -07003122 // If the set of restricted networks may have changed, re-evaluate those.
3123 if (restrictedNetworksChanged) {
3124 normalizePoliciesNL();
3125 updateNetworkRulesNL();
3126 }
3127 } finally {
3128 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003129 }
3130 }
3131
Felipe Leme09700462016-09-08 09:33:48 -07003132 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003133 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003134 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3135 try {
3136 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003137 updateRulesForPowerSaveUL();
3138 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3139 } finally {
3140 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3141 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003142 }
3143
Felipe Lemef0823852016-06-08 13:43:08 -07003144 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003145 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3146 try {
3147 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3148 } finally {
3149 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3150 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003151 }
3152
3153 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3154 private static final int TYPE_RESTRICT_POWER = 2;
3155 @Retention(RetentionPolicy.SOURCE)
3156 @IntDef(flag = false, value = {
3157 TYPE_RESTRICT_BACKGROUND,
3158 TYPE_RESTRICT_POWER,
3159 })
3160 public @interface RestrictType {
3161 }
3162
3163 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003164 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003165 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3166 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3167 }
3168 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003169 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003170
3171 final PackageManager pm = mContext.getPackageManager();
3172 final List<UserInfo> users;
3173 final List<ApplicationInfo> apps;
3174
3175 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3176 try {
3177 users = mUserManager.getUsers();
3178 } finally {
3179 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3180 }
3181 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3182 try {
3183 apps = pm.getInstalledApplications(
3184 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3185 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3186 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3187 } finally {
3188 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3189 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003190
Felipe Leme873a83a2016-09-07 11:34:10 -07003191 final int usersSize = users.size();
3192 final int appsSize = apps.size();
3193 for (int i = 0; i < usersSize; i++) {
3194 final UserInfo user = users.get(i);
3195 for (int j = 0; j < appsSize; j++) {
3196 final ApplicationInfo app = apps.get(j);
3197 final int uid = UserHandle.getUid(user.id, app.uid);
3198 switch (type) {
3199 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003200 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003201 break;
3202 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003203 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003204 break;
3205 default:
3206 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3207 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003208 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003209 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003210 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003211 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003212 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003213 }
3214
Felipe Lemef0823852016-06-08 13:43:08 -07003215 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003216 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003217 for (int i = 0; i < users.size(); i++) {
3218 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003219 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003220 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003221 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003222 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003223 updateRuleForAppIdleUL(uid);
3224 updateRuleForDeviceIdleUL(uid);
3225 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003226 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003227 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003228 }
3229 }
3230 }
3231
Felipe Leme70c57c22016-03-29 10:45:13 -07003232 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3233 // methods below could be merged into a isUidValidForRules() method.
3234 private boolean isUidValidForBlacklistRules(int uid) {
3235 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003236 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003237 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003238 return true;
3239 }
3240
3241 return false;
3242 }
3243
Felipe Leme70c57c22016-03-29 10:45:13 -07003244 private boolean isUidValidForWhitelistRules(int uid) {
3245 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3246 }
3247
Amith Yamasani15e472352015-04-24 19:06:07 -07003248 private boolean isUidIdle(int uid) {
3249 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3250 final int userId = UserHandle.getUserId(uid);
3251
songjinshi0655edd2016-05-18 19:55:32 +08003252 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003253 for (String packageName : packages) {
3254 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3255 return false;
3256 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003257 }
3258 }
3259 return true;
3260 }
3261
3262 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003263 * Checks if an uid has INTERNET permissions.
3264 * <p>
3265 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003266 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003267 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003268 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003269 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003270 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003271 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003272 }
3273 } catch (RemoteException e) {
3274 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003275 return true;
3276 }
3277
3278 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003279 * Clears all state - internal and external - associated with an UID.
3280 */
3281 private void onUidDeletedUL(int uid) {
3282 // First cleanup in-memory state synchronously...
3283 mUidRules.delete(uid);
3284 mUidPolicy.delete(uid);
3285 mUidFirewallStandbyRules.delete(uid);
3286 mUidFirewallDozableRules.delete(uid);
3287 mUidFirewallPowerSaveRules.delete(uid);
3288 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3289 mPowerSaveWhitelistAppIds.delete(uid);
3290 mPowerSaveTempWhitelistAppIds.delete(uid);
3291
3292 // ...then update iptables asynchronously.
3293 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3294 }
3295
3296 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003297 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003298 *
Felipe Leme781ba142016-05-09 16:24:48 -07003299 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003300 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003301 * <li>Doze mode
3302 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003303 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003304 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003305 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003306 *
3307 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003308 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003309 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003310 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003311 updateRuleForDeviceIdleUL(uid);
3312 updateRuleForAppIdleUL(uid);
3313 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003314
3315 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003316 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003317
3318 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003319 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003320 }
3321
Felipe Leme70c57c22016-03-29 10:45:13 -07003322 /**
3323 * Applies network rules to bandwidth controllers based on process state and user-defined
3324 * restrictions (blacklist / whitelist).
3325 *
3326 * <p>
3327 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3328 * networks:
3329 * <ul>
3330 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3331 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3332 * also blacklisted.
3333 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3334 * no UIDs other those whitelisted will have access.
3335 * <ul>
3336 *
3337 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3338 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3339 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3340 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003341 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003342 * {@link INetworkManagementService}, but this method should also be called in events (like
3343 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3344 * following rules should also be applied:
3345 *
3346 * <ul>
3347 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3348 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3349 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3350 * {@code bw_penalty_box}.
3351 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3352 * </ul>
3353 *
3354 * <p>For optimization, the rules are only applied on user apps that have internet access
3355 * permission, since there is no need to change the {@code iptables} rule if the app does not
3356 * have permission to use the internet.
3357 *
3358 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003359 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003360 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003361 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003362 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3363 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3364 "updateRulesForDataUsageRestrictionsUL: " + uid);
3365 }
3366 try {
3367 updateRulesForDataUsageRestrictionsULInner(uid);
3368 } finally {
3369 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3370 }
3371 }
3372
3373 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003374 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003375 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003376 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003377 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003378
Dianne Hackborn497175b2014-07-01 12:56:08 -07003379 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003380 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003381 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003382
Felipe Leme781ba142016-05-09 16:24:48 -07003383 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003384 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003385 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3386 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003387
Felipe Leme70c57c22016-03-29 10:45:13 -07003388 // First step: define the new rule based on user restrictions and foreground state.
3389 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003390 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3391 newRule = RULE_TEMPORARY_ALLOW_METERED;
3392 } else if (isWhitelisted) {
3393 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003394 }
3395 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003396 if (isBlacklisted) {
3397 newRule = RULE_REJECT_METERED;
3398 } else if (mRestrictBackground && isWhitelisted) {
3399 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003400 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003401 }
Felipe Leme781ba142016-05-09 16:24:48 -07003402 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003403
Felipe Lemef28983d2016-03-25 12:18:23 -07003404 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003405 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003406 + ": isForeground=" +isForeground
3407 + ", isBlacklisted=" + isBlacklisted
3408 + ", isWhitelisted=" + isWhitelisted
3409 + ", oldRule=" + uidRulesToString(oldRule)
3410 + ", newRule=" + uidRulesToString(newRule)
3411 + ", newUidRules=" + uidRulesToString(newUidRules)
3412 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003413 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003414
Felipe Leme46c4fc32016-05-04 09:21:43 -07003415 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003416 mUidRules.delete(uid);
3417 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003418 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003419 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003420
Felipe Leme70c57c22016-03-29 10:45:13 -07003421 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003422 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003423 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003424 // Temporarily whitelist foreground app, removing from blacklist if necessary
3425 // (since bw_penalty_box prevails over bw_happy_box).
3426
3427 setMeteredNetworkWhitelist(uid, true);
3428 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3429 // but ideally it should be just:
3430 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003431 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003432 setMeteredNetworkBlacklist(uid, false);
3433 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003434 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003435 // Remove temporary whitelist from app that is not on foreground anymore.
3436
3437 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3438 // but ideally they should be just:
3439 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3440 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003441 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003442 setMeteredNetworkWhitelist(uid, false);
3443 }
Felipe Leme781ba142016-05-09 16:24:48 -07003444 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003445 setMeteredNetworkBlacklist(uid, true);
3446 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003447 } else if (hasRule(newRule, RULE_REJECT_METERED)
3448 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003449 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003450 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003451 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003452 // Since blacklist prevails over whitelist, we need to handle the special case
3453 // where app is whitelisted and blacklisted at the same time (although such
3454 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003455 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003456 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003457 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3458 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003459 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003460 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003461 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003462 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003463 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3464 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003465 + ", whitelisted=" + isWhitelisted
3466 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003467 + ", newRule=" + uidRulesToString(newUidRules)
3468 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003469 }
Felipe Leme781ba142016-05-09 16:24:48 -07003470
Sudheer Shankac9d94072017-02-22 22:13:55 +00003471 // Dispatch changed rule to existing listeners.
3472 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003473 }
3474 }
3475
3476 /**
3477 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3478 * listeners in case of change.
3479 * <p>
3480 * There are 3 power-related rules that affects whether an app has background access on
3481 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3482 * restriction, it's added to the equivalent firewall chain:
3483 * <ul>
3484 * <li>App is idle: {@code fw_standby} firewall chain.
3485 * <li>Device is idle: {@code fw_dozable} firewall chain.
3486 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3487 * </ul>
3488 * <p>
3489 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3490 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3491 * <p>
3492 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3493 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003494 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003495 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3496
Sudheer Shankac9d94072017-02-22 22:13:55 +00003497 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003498
Sudheer Shankac9d94072017-02-22 22:13:55 +00003499 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003500 mUidRules.delete(uid);
3501 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003502 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003503 }
3504 }
3505
3506 /**
3507 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3508 *
3509 * @param uid the uid of the app to update rules for
3510 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3511 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3512 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003513 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003514 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003515 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003516 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3517 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3518 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3519 + (paroled ? "P" : "-"));
3520 }
3521 try {
3522 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3523 } finally {
3524 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3525 }
3526 }
3527
3528 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003529 if (!isUidValidForBlacklistRules(uid)) {
3530 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003531 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003532 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003533
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003534 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003535 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003536 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003537
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003538 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003539 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3540 int newRule = RULE_NONE;
3541
3542 // First step: define the new rule based on user restrictions and foreground state.
3543
3544 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3545 // by considering the foreground and non-foreground states.
3546 if (isForeground) {
3547 if (restrictMode) {
3548 newRule = RULE_ALLOW_ALL;
3549 }
3550 } else if (restrictMode) {
3551 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3552 }
3553
3554 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3555
3556 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003557 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003558 + ", isIdle: " + isIdle
3559 + ", mRestrictPower: " + mRestrictPower
3560 + ", mDeviceIdleMode: " + mDeviceIdleMode
3561 + ", isForeground=" + isForeground
3562 + ", isWhitelisted=" + isWhitelisted
3563 + ", oldRule=" + uidRulesToString(oldRule)
3564 + ", newRule=" + uidRulesToString(newRule)
3565 + ", newUidRules=" + uidRulesToString(newUidRules)
3566 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3567 }
3568
Felipe Leme781ba142016-05-09 16:24:48 -07003569 // Second step: notify listeners if state changed.
3570 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003571 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003572 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003573 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003574 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3575 } else {
3576 // All scenarios should have been covered above
3577 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3578 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003579 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003580 + ", newRule=" + uidRulesToString(newUidRules)
3581 + ", oldRule=" + uidRulesToString(oldUidRules));
3582 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003583 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003584 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003585
Sudheer Shankac9d94072017-02-22 22:13:55 +00003586 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003587 }
3588
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003589 private class AppIdleStateChangeListener
3590 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3591
3592 @Override
3593 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3594 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003595 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3596 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003597 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003598 synchronized (mUidRulesFirstLock) {
3599 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003600 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003601 }
3602 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003603 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003604 }
3605
3606 @Override
3607 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003608 synchronized (mUidRulesFirstLock) {
3609 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003610 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003611 }
3612 }
3613
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003614 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3615 if (listener != null) {
3616 try {
3617 listener.onUidRulesChanged(uid, uidRules);
3618 } catch (RemoteException ignored) {
3619 }
3620 }
3621 }
3622
3623 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3624 String[] meteredIfaces) {
3625 if (listener != null) {
3626 try {
3627 listener.onMeteredIfacesChanged(meteredIfaces);
3628 } catch (RemoteException ignored) {
3629 }
3630 }
3631 }
3632
3633 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3634 boolean restrictBackground) {
3635 if (listener != null) {
3636 try {
3637 listener.onRestrictBackgroundChanged(restrictBackground);
3638 } catch (RemoteException ignored) {
3639 }
3640 }
3641 }
3642
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003643 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3644 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003645 if (listener != null) {
3646 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003647 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003648 } catch (RemoteException ignored) {
3649 }
3650 }
3651 }
3652
Makoto Onuki8e777332017-03-28 11:25:47 -07003653 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003654 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003655 public boolean handleMessage(Message msg) {
3656 switch (msg.what) {
3657 case MSG_RULES_CHANGED: {
3658 final int uid = msg.arg1;
3659 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003660 final int length = mListeners.beginBroadcast();
3661 for (int i = 0; i < length; i++) {
3662 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3663 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003664 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003665 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003666 return true;
3667 }
3668 case MSG_METERED_IFACES_CHANGED: {
3669 final String[] meteredIfaces = (String[]) msg.obj;
3670 final int length = mListeners.beginBroadcast();
3671 for (int i = 0; i < length; i++) {
3672 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003673 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003674 }
3675 mListeners.finishBroadcast();
3676 return true;
3677 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003678 case MSG_LIMIT_REACHED: {
3679 final String iface = (String) msg.obj;
3680
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003681 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003682 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003683 if (mMeteredIfaces.contains(iface)) {
3684 try {
3685 // force stats update to make sure we have
3686 // numbers that caused alert to trigger.
3687 mNetworkStats.forceUpdate();
3688 } catch (RemoteException e) {
3689 // ignored; service lives in system_server
3690 }
3691
Felipe Lemef0823852016-06-08 13:43:08 -07003692 updateNetworkEnabledNL();
3693 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003694 }
3695 }
3696 return true;
3697 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003698 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3699 final boolean restrictBackground = msg.arg1 != 0;
3700 final int length = mListeners.beginBroadcast();
3701 for (int i = 0; i < length; i++) {
3702 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003703 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003704 }
3705 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003706 final Intent intent =
3707 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3708 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3709 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3710 return true;
3711 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003712 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003713 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003714 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003715 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003716 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003717 final int length = mListeners.beginBroadcast();
3718 for (int i = 0; i < length; i++) {
3719 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003720 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003721 }
3722 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003723 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3724 if (notifyApp.booleanValue()) {
3725 broadcastRestrictBackgroundChanged(uid, notifyApp);
3726 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003727 return true;
3728 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003729 case MSG_ADVISE_PERSIST_THRESHOLD: {
3730 final long lowestRule = (Long) msg.obj;
3731 try {
3732 // make sure stats are recorded frequently enough; we aim
3733 // for 2MB threshold for 2GB/month rules.
3734 final long persistThreshold = lowestRule / 1000;
3735 mNetworkStats.advisePersistThreshold(persistThreshold);
3736 } catch (RemoteException e) {
3737 // ignored; service lives in system_server
3738 }
3739 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003740 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003741 case MSG_UPDATE_INTERFACE_QUOTA: {
3742 removeInterfaceQuota((String) msg.obj);
3743 // int params need to be stitched back into a long
3744 setInterfaceQuota((String) msg.obj,
3745 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3746 return true;
3747 }
3748 case MSG_REMOVE_INTERFACE_QUOTA: {
3749 removeInterfaceQuota((String) msg.obj);
3750 return true;
3751 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003752 case MSG_SET_FIREWALL_RULES: {
3753 final int chain = msg.arg1;
3754 final int toggle = msg.arg2;
3755 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3756 if (uidRules != null) {
3757 setUidFirewallRules(chain, uidRules);
3758 }
3759 if (toggle != CHAIN_TOGGLE_NONE) {
3760 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3761 }
3762 return true;
3763 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003764 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3765 resetUidFirewallRules(msg.arg1);
3766 return true;
3767 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003768 default: {
3769 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003770 }
3771 }
3772 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003773 };
3774
3775 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3776 @Override
3777 public boolean handleMessage(Message msg) {
3778 switch (msg.what) {
3779 case UID_MSG_STATE_CHANGED: {
3780 final int uid = msg.arg1;
3781 final int procState = msg.arg2;
3782 final long procStateSeq = (Long) msg.obj;
3783
3784 handleUidChanged(uid, procState, procStateSeq);
3785 return true;
3786 }
3787 case UID_MSG_GONE: {
3788 final int uid = msg.arg1;
3789 handleUidGone(uid);
3790 return true;
3791 }
3792 default: {
3793 return false;
3794 }
3795 }
3796 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003797
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003798 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003799
Makoto Onuki8e777332017-03-28 11:25:47 -07003800 void handleUidChanged(int uid, int procState, long procStateSeq) {
3801 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3802 try {
3803 synchronized (mUidRulesFirstLock) {
3804 // We received a uid state change callback, add it to the history so that it
3805 // will be useful for debugging.
3806 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3807 // Now update the network policy rules as per the updated uid state.
3808 updateUidStateUL(uid, procState);
3809 // Updating the network rules is done, so notify AMS about this.
3810 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3811 }
3812 } finally {
3813 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3814 }
3815 }
3816
3817 void handleUidGone(int uid) {
3818 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3819 try {
3820 synchronized (mUidRulesFirstLock) {
3821 removeUidStateUL(uid);
3822 }
3823 } finally {
3824 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3825 }
3826 }
3827
Felipe Leme57e3d312016-08-23 14:42:52 -07003828 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3829 final PackageManager pm = mContext.getPackageManager();
3830 final String[] packages = pm.getPackagesForUid(uid);
3831 if (packages != null) {
3832 final int userId = UserHandle.getUserId(uid);
3833 for (String packageName : packages) {
3834 final Intent intent =
3835 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3836 intent.setPackage(packageName);
3837 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3838 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3839 }
3840 }
3841 }
3842
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003843 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003844 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003845 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003846 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003847 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003848 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003849 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003850 }
3851 }
3852
3853 private void removeInterfaceQuota(String iface) {
3854 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003855 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003856 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003857 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003858 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003859 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003860 }
3861 }
3862
Felipe Leme70c57c22016-03-29 10:45:13 -07003863 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3864 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003865 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003866 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003867 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003868 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3869 } catch (RemoteException e) {
3870 // ignored; service lives in system_server
3871 }
3872 }
3873
3874 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3875 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3876 try {
3877 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3878 } catch (IllegalStateException e) {
3879 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003880 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003881 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003882 }
3883 }
3884
Felipe Lemebc853dd2016-09-08 13:26:55 -07003885 private static final int CHAIN_TOGGLE_NONE = 0;
3886 private static final int CHAIN_TOGGLE_ENABLE = 1;
3887 private static final int CHAIN_TOGGLE_DISABLE = 2;
3888 @Retention(RetentionPolicy.SOURCE)
3889 @IntDef(flag = false, value = {
3890 CHAIN_TOGGLE_NONE,
3891 CHAIN_TOGGLE_ENABLE,
3892 CHAIN_TOGGLE_DISABLE
3893 })
3894 public @interface ChainToggleType {
3895 }
3896
3897 /**
3898 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3899 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3900 *
3901 * @param chain firewall chain.
3902 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3903 * @param toggle whether the chain should be enabled, disabled, or not changed.
3904 */
3905 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3906 @ChainToggleType int toggle) {
3907 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3908 }
3909
Amith Yamasani15e472352015-04-24 19:06:07 -07003910 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003911 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3912 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3913 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003914 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003915 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003916 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003917 int size = uidRules.size();
3918 int[] uids = new int[size];
3919 int[] rules = new int[size];
3920 for(int index = size - 1; index >= 0; --index) {
3921 uids[index] = uidRules.keyAt(index);
3922 rules[index] = uidRules.valueAt(index);
3923 }
3924 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003925 } catch (IllegalStateException e) {
3926 Log.wtf(TAG, "problem setting firewall uid rules", e);
3927 } catch (RemoteException e) {
3928 // ignored; service lives in system_server
3929 }
3930 }
3931
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003932 /**
3933 * Add or remove a uid to the firewall blacklist for all network ifaces.
3934 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003935 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003936 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3937 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3938 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003939 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003940 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003941 if (chain == FIREWALL_CHAIN_DOZABLE) {
3942 mUidFirewallDozableRules.put(uid, rule);
3943 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3944 mUidFirewallStandbyRules.put(uid, rule);
3945 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3946 mUidFirewallPowerSaveRules.put(uid, rule);
3947 }
3948
3949 try {
3950 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3951 } catch (IllegalStateException e) {
3952 Log.wtf(TAG, "problem setting firewall uid rules", e);
3953 } catch (RemoteException e) {
3954 // ignored; service lives in system_server
3955 }
3956 } finally {
3957 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003958 }
3959 }
3960
3961 /**
3962 * Add or remove a uid to the firewall blacklist for all network ifaces.
3963 */
Felipe Lemef0823852016-06-08 13:43:08 -07003964 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003965 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3966 mFirewallChainStates.get(chain) == enable) {
3967 // All is the same, nothing to do.
3968 return;
3969 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003970 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003971 try {
3972 mNetworkManager.setFirewallChainEnabled(chain, enable);
3973 } catch (IllegalStateException e) {
3974 Log.wtf(TAG, "problem enable firewall chain", e);
3975 } catch (RemoteException e) {
3976 // ignored; service lives in system_server
3977 }
3978 }
3979
Felipe Leme03e95e22016-09-09 09:25:31 -07003980 /**
3981 * Resets all firewall rules associated with an UID.
3982 */
3983 private void resetUidFirewallRules(int uid) {
3984 try {
3985 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3986 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3987 mNetworkManager
3988 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3989 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3990 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3991 } catch (IllegalStateException e) {
3992 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3993 } catch (RemoteException e) {
3994 // ignored; service lives in system_server
3995 }
3996 }
3997
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003998 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3999 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004000 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004001 } catch (RuntimeException e) {
4002 Slog.w(TAG, "problem reading network stats: " + e);
4003 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004004 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004005 // ignored; service lives in system_server
4006 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004007 }
4008 }
4009
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004010 private boolean isBandwidthControlEnabled() {
4011 final long token = Binder.clearCallingIdentity();
4012 try {
4013 return mNetworkManager.isBandwidthControlEnabled();
4014 } catch (RemoteException e) {
4015 // ignored; service lives in system_server
4016 return false;
4017 } finally {
4018 Binder.restoreCallingIdentity(token);
4019 }
4020 }
4021
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004022 /**
4023 * Try refreshing {@link #mTime} when stale.
4024 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004025 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004026 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004027 mTime.forceRefresh();
4028 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004029 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004030
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004031 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004032 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4033 }
4034
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004035 private static Intent buildAllowBackgroundDataIntent() {
4036 return new Intent(ACTION_ALLOW_BACKGROUND);
4037 }
4038
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004039 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4040 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4041 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4042 return intent;
4043 }
4044
Wei Liu546cb772016-07-21 16:19:01 -07004045 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004046 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004047 intent.setComponent(ComponentName.unflattenFromString(
4048 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004049 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4050 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4051 return intent;
4052 }
4053
Wei Liu546cb772016-07-21 16:19:01 -07004054 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004055 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004056 intent.setComponent(ComponentName.unflattenFromString(
4057 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004058 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4059 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4060 return intent;
4061 }
4062
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004063 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004064 public void addIdleHandler(IdleHandler handler) {
4065 mHandler.getLooper().getQueue().addIdleHandler(handler);
4066 }
4067
jackqdyulei29c82ab2017-03-10 14:09:16 -08004068 @VisibleForTesting
4069 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4070 mRestrictBackgroundPowerState = result;
4071
4072 boolean restrictBackground = result.batterySaverEnabled;
4073 boolean shouldInvokeRestrictBackground;
4074 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4075 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4076
4077 if (result.globalBatterySaverEnabled) {
4078 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4079 // turn it on.
4080 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4081 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4082 localRestrictBgChangedInBsm = false;
4083 } else {
4084 // Try to restore the restrictBackground if it doesn't change in bsm
4085 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4086 restrictBackground = mRestrictBackgroundBeforeBsm;
4087 }
4088
4089 if (shouldInvokeRestrictBackground) {
4090 setRestrictBackground(restrictBackground);
4091 }
4092
4093 // Change it at last so setRestrictBackground() won't affect this variable
4094 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4095 }
4096
Jeff Sharkey1b861272011-05-22 00:34:52 -07004097 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4098 final int size = source.size();
4099 for (int i = 0; i < size; i++) {
4100 target.put(source.keyAt(i), true);
4101 }
4102 }
4103
Stuart Scottf1fb3972015-04-02 18:00:02 -07004104 @Override
4105 public void factoryReset(String subscriber) {
4106 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4107
Stuart Scotte3e314d2015-04-20 14:07:45 -07004108 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4109 return;
4110 }
4111
Stuart Scottf1fb3972015-04-02 18:00:02 -07004112 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004113 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004114 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4115 for (NetworkPolicy policy : policies) {
4116 if (policy.template.equals(template)) {
4117 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4118 policy.inferred = false;
4119 policy.clearSnooze();
4120 }
4121 }
4122 setNetworkPolicies(policies);
4123
4124 // Turn restrict background data off
4125 setRestrictBackground(false);
4126
Stuart Scotte3e314d2015-04-20 14:07:45 -07004127 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4128 // Remove app's "restrict background data" flag
4129 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4130 setUidPolicy(uid, POLICY_NONE);
4131 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004132 }
4133 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004134
Felipe Lemed17fda42016-04-29 11:12:45 -07004135 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4136
4137 @Override
4138 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004139 synchronized (mUidRulesFirstLock) {
4140 boolean changed = removeUserStateUL(userId, false);
4141 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004142 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004143 synchronized (mNetworkPoliciesSecondLock) {
4144 writePolicyAL();
4145 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004146 }
4147 }
4148 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004149
4150 /**
4151 * @return true if the given uid is restricted from doing networking on metered networks.
4152 */
4153 @Override
4154 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4155 final int uidRules;
4156 final boolean isBackgroundRestricted;
4157 synchronized (mUidRulesFirstLock) {
4158 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4159 isBackgroundRestricted = mRestrictBackground;
4160 }
4161 return isBackgroundRestricted
4162 && !hasRule(uidRules, RULE_ALLOW_METERED)
4163 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4164 }
4165
4166 /**
4167 * @return true if networking is blocked on the given interface for the given uid according
4168 * to current networking policies.
4169 */
4170 @Override
4171 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4172 final int uidRules;
4173 final boolean isBackgroundRestricted;
4174 final boolean isNetworkMetered;
4175 synchronized (mUidRulesFirstLock) {
4176 uidRules = mUidRules.get(uid, RULE_NONE);
4177 isBackgroundRestricted = mRestrictBackground;
4178 synchronized (mNetworkPoliciesSecondLock) {
4179 isNetworkMetered = mMeteredIfaces.contains(ifname);
4180 }
4181 }
4182 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4183 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4184 return true;
4185 }
4186 if (!isNetworkMetered) {
4187 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4188 return false;
4189 }
4190 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4191 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4192 return true;
4193 }
4194 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4195 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4196 return false;
4197 }
4198 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4199 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4200 return false;
4201 }
4202 if (isBackgroundRestricted) {
4203 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4204 return true;
4205 }
4206 if (LOGV) logUidStatus(uid, "allowed by default");
4207 return false;
4208 }
4209 }
4210
4211 private static boolean hasRule(int uidRules, int rule) {
4212 return (uidRules & rule) != 0;
4213 }
4214
4215 private static void logUidStatus(int uid, String descr) {
4216 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004217 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004218
4219 /**
4220 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4221 * (uid, procStateSeq) pairs.
4222 */
4223 @VisibleForTesting
4224 public static final class ProcStateSeqHistory {
4225 private static final int INVALID_UID = -1;
4226
4227 /**
4228 * Denotes maximum number of items this history can hold.
4229 */
4230 private final int mMaxCapacity;
4231 /**
4232 * Used for storing the uid information.
4233 */
4234 private final int[] mUids;
4235 /**
4236 * Used for storing the sequence numbers associated with {@link #mUids}.
4237 */
4238 private final long[] mProcStateSeqs;
4239 /**
4240 * Points to the next available slot for writing (uid, procStateSeq) pair.
4241 */
4242 private int mHistoryNext;
4243
4244 public ProcStateSeqHistory(int maxCapacity) {
4245 mMaxCapacity = maxCapacity;
4246 mUids = new int[mMaxCapacity];
4247 Arrays.fill(mUids, INVALID_UID);
4248 mProcStateSeqs = new long[mMaxCapacity];
4249 }
4250
4251 @GuardedBy("mUidRulesFirstLock")
4252 public void addProcStateSeqUL(int uid, long procStateSeq) {
4253 mUids[mHistoryNext] = uid;
4254 mProcStateSeqs[mHistoryNext] = procStateSeq;
4255 mHistoryNext = increaseNext(mHistoryNext, 1);
4256 }
4257
4258 @GuardedBy("mUidRulesFirstLock")
4259 public void dumpUL(IndentingPrintWriter fout) {
4260 if (mUids[0] == INVALID_UID) {
4261 fout.println("NONE");
4262 return;
4263 }
4264 int index = mHistoryNext;
4265 do {
4266 index = increaseNext(index, -1);
4267 if (mUids[index] == INVALID_UID) {
4268 break;
4269 }
4270 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4271 } while (index != mHistoryNext);
4272 }
4273
4274 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004275 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004276 }
4277
4278 private int increaseNext(int next, int increment) {
4279 next += increment;
4280 if (next >= mMaxCapacity) {
4281 next = 0;
4282 } else if (next < 0) {
4283 next = mMaxCapacity - 1;
4284 }
4285 return next;
4286 }
4287 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004288
4289 private class NotificationId {
4290 private final String mTag;
4291 private final int mId;
4292
4293 NotificationId(NetworkPolicy policy, int type) {
4294 mTag = buildNotificationTag(policy, type);
4295 mId = type;
4296 }
4297
4298 @Override
4299 public boolean equals(Object o) {
4300 if (this == o) return true;
4301 if (!(o instanceof NotificationId)) return false;
4302 NotificationId that = (NotificationId) o;
4303 return Objects.equals(mTag, that.mTag);
4304 }
4305
4306 @Override
4307 public int hashCode() {
4308 return Objects.hash(mTag);
4309 }
4310
4311 /**
4312 * Build unique tag that identifies an active {@link NetworkPolicy}
4313 * notification of a specific type, like {@link #TYPE_LIMIT}.
4314 */
4315 private String buildNotificationTag(NetworkPolicy policy, int type) {
4316 return TAG + ":" + policy.template.hashCode() + ":" + type;
4317 }
4318
4319 public String getTag() {
4320 return mTag;
4321 }
4322
4323 public int getId() {
4324 return mId;
4325 }
4326 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004327}