blob: 8b8811e252c07909b0387923db9b755fdf161de7 [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 Sharkey21c9c452011-06-07 12:26:43 -070021import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Jeff Sharkey497e4432011-06-14 17:27:29 -070022import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070023import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070024import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070025import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070026import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070027import static android.content.Intent.ACTION_USER_ADDED;
28import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070029import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090030import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080031import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
32import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060034import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070035import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070036import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070037import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070038import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070039import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080040import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
42import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070043import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060045import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
46import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070047import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070048import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070049import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070050import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070052import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070053import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070055import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Jeff Sharkeycd2ca402011-06-10 15:14:07 -070056import static android.net.NetworkPolicyManager.computeLastCycleBoundary;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080057import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
58import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060059import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070060import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070061import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070062import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
63import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070064import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
65import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070066import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080067import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070068import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060070import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070071import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080072
Jeff Sharkey854b2b12012-04-13 16:03:40 -070073import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070074import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070075import static com.android.internal.util.XmlUtils.readBooleanAttribute;
76import static com.android.internal.util.XmlUtils.readIntAttribute;
77import static com.android.internal.util.XmlUtils.readLongAttribute;
78import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
79import static com.android.internal.util.XmlUtils.writeIntAttribute;
80import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070081import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070082import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060083
Jeff Sharkey21c9c452011-06-07 12:26:43 -070084import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080085import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070087
Dianne Hackborn88e98df2015-03-23 13:29:14 -070088import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070089import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070090import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070091import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080092import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070093import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070094import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070095import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070096import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070097import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.Notification;
99import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700100import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700101import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700102import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700103import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.Intent;
105import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700106import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700107import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700109import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700110import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700111import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700112import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700113import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700114import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700116import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700117import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700118import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700119import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700120import android.net.NetworkPolicy;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700121import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700123import android.net.NetworkTemplate;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700124import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700125import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700126import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700127import android.os.Environment;
128import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700129import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700130import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700131import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700132import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700133import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700134import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700135import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700136import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600137import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800138import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700139import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700140import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600141import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700142import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700143import android.os.ShellCallback;
Felipe Leme873a83a2016-09-07 11:34:10 -0700144import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700145import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700146import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700147import android.provider.Settings;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700148import android.telephony.CarrierConfigManager;
Jeff Sharkey32566012014-12-02 18:30:14 -0800149import android.telephony.SubscriptionManager;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700150import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400151import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700152import android.text.format.Formatter;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700153import android.text.format.Time;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700154import android.util.ArrayMap;
155import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700156import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700157import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700158import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700159import android.util.Pair;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700160import android.util.Slog;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700161import android.util.SparseBooleanArray;
162import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700163import android.util.TrustedTime;
164import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700165
Jeff Sharkey497e4432011-06-14 17:27:29 -0700166import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700167import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800168import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400169import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500170import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700171import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800172import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600173import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700174import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700175import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700176import com.android.server.DeviceIdleController;
177import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700178import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700179import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800180import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800181import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600182
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600183import libcore.io.IoUtils;
184
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700185import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700186
187import org.xmlpull.v1.XmlPullParser;
188import org.xmlpull.v1.XmlPullParserException;
189import org.xmlpull.v1.XmlSerializer;
190
191import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700192import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700193import java.io.FileInputStream;
194import java.io.FileNotFoundException;
195import java.io.FileOutputStream;
196import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700197import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700198import java.lang.annotation.Retention;
199import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100200import java.nio.charset.StandardCharsets;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import java.util.ArrayList;
202import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700203import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600204import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400205import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800206import java.util.concurrent.CountDownLatch;
207import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700208
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700209/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700210 * Service that maintains low-level network policy rules, using
211 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700212 * <p>
213 * Derives active rules by combining a given policy with other system status,
214 * and delivers to listeners, such as {@link ConnectivityManager}, for
215 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700216 *
217 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000218 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700219 * <ul>
220 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
221 * rules).
222 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
223 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000224 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
225 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700226 * </ul>
227 *
228 * <p>
229 * As such, methods that require synchronization have the following prefixes:
230 * <ul>
231 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
232 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000233 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
234 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700235 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700236 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700237public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800238 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900239 private static final boolean LOGD = false;
240 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700241
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700242 private static final int VERSION_INIT = 1;
243 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700244 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800245 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800246 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800247 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700248 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700249 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700250 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700251 private static final int VERSION_SWITCH_UID = 10;
252 private static final int VERSION_LATEST = VERSION_SWITCH_UID;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700253
Sudheer Shankae7361852017-03-07 11:51:46 -0800254 /**
255 * Max items written to {@link #ProcStateSeqHistory}.
256 */
257 @VisibleForTesting
258 public static final int MAX_PROC_STATE_SEQ_HISTORY =
259 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
260
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800261 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400262 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800263 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400264 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800265 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400266 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700267
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268 private static final String TAG_POLICY_LIST = "policy-list";
269 private static final String TAG_NETWORK_POLICY = "network-policy";
270 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700271 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800272 private static final String TAG_WHITELIST = "whitelist";
273 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800274 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700275
276 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700277 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700278 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
279 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700280 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700281 private static final String ATTR_CYCLE_DAY = "cycleDay";
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800282 private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String ATTR_WARNING_BYTES = "warningBytes";
284 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700285 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800286 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
287 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800288 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700289 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700290 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700291 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700292 private static final String ATTR_POLICY = "policy";
293
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800294 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800295 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800296 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800297 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700298
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700299 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
300
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700301 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700302 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800303 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800304 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700305 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700306 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
307 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700308 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700309 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700310 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700311
Makoto Onuki8e777332017-03-28 11:25:47 -0700312 private static final int UID_MSG_STATE_CHANGED = 100;
313 private static final int UID_MSG_GONE = 101;
314
Jeff Sharkey75279902011-05-24 18:39:45 -0700315 private final Context mContext;
316 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700317 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700318 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700319 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700320 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700321 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700322 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700323
324 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700325 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700326 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700327 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800328 @GuardedBy("mUidRulesFirstLock")
329 private PowerSaveState mRestrictBackgroundPowerState;
330
331 // Store the status of restrict background before turning on battery saver.
332 // Used to restore mRestrictBackground when battery saver is turned off.
333 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700334
Felipe Lemef0823852016-06-08 13:43:08 -0700335 // See main javadoc for instructions on how to use these locks.
336 final Object mUidRulesFirstLock = new Object();
337 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700338
Felipe Lemef0823852016-06-08 13:43:08 -0700339 @GuardedBy("allLocks") volatile boolean mSystemReady;
340
Felipe Lemef0823852016-06-08 13:43:08 -0700341 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
342 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
343 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800344 // Store whether user flipped restrict background in battery saver mode
345 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700346
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700347 private final boolean mSuppressDefaultPolicy;
348
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700349 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800350 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700351 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800352 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700353
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700354 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700355 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700356 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700357 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700358
Felipe Lemef0823852016-06-08 13:43:08 -0700359 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700360 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700361 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700362 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700363 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800364 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700365
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700366 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700367 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700368 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
369
Jeff Sharkey32566012014-12-02 18:30:14 -0800370 /**
371 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700372 * in power save mode, except device idle (doze) still applies.
373 * TODO: An int array might be sufficient
374 */
Felipe Lemef0823852016-06-08 13:43:08 -0700375 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700376 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
377
378 /**
379 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800380 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700381 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800382 */
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700384 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700385
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700387 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
388
Felipe Lemeb85a6372016-01-14 16:16:16 -0800389 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800390 * UIDs that have been initially white-listed by system to avoid restricted background.
391 */
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800393 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
394 new SparseBooleanArray();
395
396 /**
397 * UIDs that have been initially white-listed by system to avoid restricted background,
398 * but later revoked by user.
399 */
Felipe Lemef0823852016-06-08 13:43:08 -0700400 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800401 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
402 new SparseBooleanArray();
403
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700404 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700405 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800406 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700407 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700408 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800409 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700410
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700411 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700412 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400413 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700414
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700415 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700416 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800417 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700418
Jeff Sharkey32566012014-12-02 18:30:14 -0800419 private final RemoteCallbackList<INetworkPolicyListener>
420 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700421
Dianne Hackborn497175b2014-07-01 12:56:08 -0700422 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700423 @VisibleForTesting
424 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700425
426 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700427
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700429 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700430
Svet Ganov16a16892015-04-16 10:32:04 -0700431 private final AppOpsManager mAppOps;
432
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800433 private final IPackageManager mIPm;
434
Sudheer Shankae7361852017-03-07 11:51:46 -0800435 private ActivityManagerInternal mActivityManagerInternal;
436
437 /**
438 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
439 * the uid and procStateSeq will be written to this and will be printed as part of dump.
440 */
441 @VisibleForTesting
442 public ProcStateSeqHistory mObservedHistory
443 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800444
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700445 // TODO: keep whitelist of system-critical services that should never have
446 // rules enforced, such as system, phone, and radio UIDs.
447
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700448 // TODO: migrate notifications to SystemUI
449
Jeff Sharkey75279902011-05-24 18:39:45 -0700450 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700451 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
452 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700453 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
454 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700455 }
456
457 private static File getSystemDir() {
458 return new File(Environment.getDataDirectory(), "system");
459 }
460
461 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700462 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700463 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700464 mContext = checkNotNull(context, "missing context");
465 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700466 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700467 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700468 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700469 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700470 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700471 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700472 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700473 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700474
Amith Yamasani450a16b2013-09-18 16:28:50 -0700475 HandlerThread thread = new HandlerThread(TAG);
476 thread.start();
477 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700478
Makoto Onuki8e777332017-03-28 11:25:47 -0700479 // We create another thread for the UID events, which are more time-critical.
480 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
481 /*allowIo=*/ false);
482 mUidEventThread.start();
483 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
484
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700485 mSuppressDefaultPolicy = suppressDefaultPolicy;
486
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700487 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700488
489 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800490
Felipe Lemed17fda42016-04-29 11:12:45 -0700491 // Expose private service for system components to use.
492 LocalServices.addService(NetworkPolicyManagerInternal.class,
493 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700494 }
495
496 public void bindConnectivityManager(IConnectivityManager connManager) {
497 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700498 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700499
Jeff Sharkey497e4432011-06-14 17:27:29 -0700500 public void bindNotificationManager(INotificationManager notifManager) {
501 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
502 }
503
Felipe Lemef0823852016-06-08 13:43:08 -0700504 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700505 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700506 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
507 mPowerSaveWhitelistExceptIdleAppIds.clear();
508 if (whitelist != null) {
509 for (int uid : whitelist) {
510 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
511 }
512 }
513 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700514 mPowerSaveWhitelistAppIds.clear();
515 if (whitelist != null) {
516 for (int uid : whitelist) {
517 mPowerSaveWhitelistAppIds.put(uid, true);
518 }
519 }
520 } catch (RemoteException e) {
521 }
522 }
523
Felipe Lemea9505cc2016-02-26 10:28:41 -0800524 /**
525 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
526 * revoke the whitelist.
527 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700528 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800529 */
Felipe Lemef0823852016-06-08 13:43:08 -0700530 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800531 final List<UserInfo> users = mUserManager.getUsers();
532 final int numberUsers = users.size();
533
Felipe Lemea110eec2016-04-29 09:58:06 -0700534 boolean changed = false;
535 for (int i = 0; i < numberUsers; i++) {
536 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700537 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700538 }
539 return changed;
540 }
541
Felipe Lemef0823852016-06-08 13:43:08 -0700542 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700543 final SystemConfig sysConfig = SystemConfig.getInstance();
544 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800545 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
546 boolean changed = false;
547 for (int i = 0; i < allowDataUsage.size(); i++) {
548 final String pkg = allowDataUsage.valueAt(i);
549 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700550 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
551 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800552 final ApplicationInfo app;
553 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700554 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800555 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700556 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
557 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800558 continue;
559 }
560 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700561 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
562 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800563 continue;
564 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700565 final int uid = UserHandle.getUid(userId, app.uid);
566 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
567 if (LOGD)
568 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
569 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800570 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700571 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700572 if (LOGD)
573 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
574 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700575 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700576 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800577 }
578 }
579 return changed;
580 }
581
Felipe Lemef0823852016-06-08 13:43:08 -0700582 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700583 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700584 // Clear the states of the current whitelist
585 final int N = mPowerSaveTempWhitelistAppIds.size();
586 for (int i = 0; i < N; i++) {
587 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
588 }
589 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700590 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700591 if (whitelist != null) {
592 for (int uid : whitelist) {
593 mPowerSaveTempWhitelistAppIds.put(uid, true);
594 }
595 }
596 } catch (RemoteException e) {
597 }
598 }
599
Amith Yamasani06f08062015-06-12 13:23:33 -0700600 /**
601 * Remove unnecessary entries in the temp whitelist
602 */
Felipe Lemef0823852016-06-08 13:43:08 -0700603 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700604 final int N = mPowerSaveTempWhitelistAppIds.size();
605 for (int i = N - 1; i >= 0; i--) {
606 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
607 mPowerSaveTempWhitelistAppIds.removeAt(i);
608 }
609 }
610 }
611
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800612 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700613 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800614 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700615 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800616 // Boost thread's priority during system server init
617 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700618 if (!isBandwidthControlEnabled()) {
619 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
620 return;
621 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700622
Felipe Leme873a83a2016-09-07 11:34:10 -0700623 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700624
Felipe Leme873a83a2016-09-07 11:34:10 -0700625 synchronized (mUidRulesFirstLock) {
626 synchronized (mNetworkPoliciesSecondLock) {
627 updatePowerSaveWhitelistUL();
628 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
629 mPowerManagerInternal.registerLowPowerModeObserver(
630 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800631 @Override
632 public int getServiceType() {
633 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700634 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800635
636 @Override
637 public void onLowPowerModeChanged(PowerSaveState result) {
638 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800639 if (LOGD) {
640 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
641 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800642 synchronized (mUidRulesFirstLock) {
643 if (mRestrictPower != enabled) {
644 mRestrictPower = enabled;
645 updateRulesForRestrictPowerUL();
646 }
647 }
648 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800649 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800650 mRestrictPower = mPowerManagerInternal.getLowPowerState(
651 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700652
653 mSystemReady = true;
654
655 // read policy from disk
656 readPolicyAL();
657
jackqdyulei29c82ab2017-03-10 14:09:16 -0800658 // Update the restrictBackground if battery saver is turned on
659 mRestrictBackgroundBeforeBsm = mRestrictBackground;
660 mRestrictBackgroundPowerState = mPowerManagerInternal
661 .getLowPowerState(ServiceType.DATA_SAVER);
662 final boolean localRestrictBackground =
663 mRestrictBackgroundPowerState.batterySaverEnabled;
664 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
665 mRestrictBackground = localRestrictBackground;
666 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
667 mRestrictBackground ? 1 : 0, 0).sendToTarget();
668 }
669 mPowerManagerInternal.registerLowPowerModeObserver(
670 new PowerManagerInternal.LowPowerModeListener() {
671 @Override
672 public int getServiceType() {
673 return ServiceType.DATA_SAVER;
674 }
675
676 @Override
677 public void onLowPowerModeChanged(PowerSaveState result) {
678 synchronized (mUidRulesFirstLock) {
679 updateRestrictBackgroundByLowPowerModeUL(result);
680 }
681 }
682 });
683
Felipe Leme873a83a2016-09-07 11:34:10 -0700684 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
685 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700686 }
Felipe Lemef0823852016-06-08 13:43:08 -0700687
Felipe Leme873a83a2016-09-07 11:34:10 -0700688 setRestrictBackgroundUL(mRestrictBackground);
689 updateRulesForGlobalChangeAL(false);
690 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700691 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800692 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700693
Sudheer Shankae7361852017-03-07 11:51:46 -0800694 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700695 try {
696 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000697 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800698 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700699 mNetworkManager.registerObserver(mAlertObserver);
700 } catch (RemoteException e) {
701 // ignored; both services live in system_server
702 }
703
704 // listen for changes to power save whitelist
705 final IntentFilter whitelistFilter = new IntentFilter(
706 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
707 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
708
709 DeviceIdleController.LocalService deviceIdleService
710 = LocalServices.getService(DeviceIdleController.LocalService.class);
711 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
712
713 // watch for network interfaces to be claimed
714 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
715 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
716
717 // listen for package changes to update policy
718 final IntentFilter packageFilter = new IntentFilter();
719 packageFilter.addAction(ACTION_PACKAGE_ADDED);
720 packageFilter.addDataScheme("package");
721 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
722
723 // listen for UID changes to update policy
724 mContext.registerReceiver(
725 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
726
727 // listen for user changes to update policy
728 final IntentFilter userFilter = new IntentFilter();
729 userFilter.addAction(ACTION_USER_ADDED);
730 userFilter.addAction(ACTION_USER_REMOVED);
731 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
732
733 // listen for stats update events
734 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
735 mContext.registerReceiver(
736 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
737
738 // listen for restrict background changes from notifications
739 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
740 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
741
742 // listen for snooze warning from notifications
743 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
744 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
745 MANAGE_NETWORK_POLICY, mHandler);
746
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600747 // listen for configured wifi networks to be loaded
748 final IntentFilter wifiFilter =
749 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
750 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700751
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700752 // listen for carrier config changes to update data cycle information
753 final IntentFilter carrierConfigFilter = new IntentFilter(
754 ACTION_CARRIER_CONFIG_CHANGED);
755 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
756
Felipe Leme873a83a2016-09-07 11:34:10 -0700757 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800758 // tell systemReady() that the service has been initialized
759 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700760 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800761 // Restore the default priority after init is done
762 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700763 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700764 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700765 }
766
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800767 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
768 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
769 mHandler.post(() -> initService(initCompleteSignal));
770 return initCompleteSignal;
771 }
772
773 public void systemReady(CountDownLatch initCompleteSignal) {
774 // wait for initService to complete
775 try {
776 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
777 throw new IllegalStateException("Service " + TAG +" init timeout");
778 }
779 } catch (InterruptedException e) {
780 Thread.currentThread().interrupt();
781 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
782 }
783 }
784
Sudheer Shankac9d94072017-02-22 22:13:55 +0000785 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700786 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700787 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
788 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700789 }
790
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700791 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700792 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700793 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700794
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700795 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700796 }
797
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700798 @Override public void onUidIdle(int uid, boolean disabled) {
799 }
800
801 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700802 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700803 };
804
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700805 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700806 @Override
807 public void onReceive(Context context, Intent intent) {
808 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700809 synchronized (mUidRulesFirstLock) {
810 updatePowerSaveWhitelistUL();
811 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700812 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700813 }
814 }
815 };
816
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700817 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
818 @Override
819 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700820 synchronized (mUidRulesFirstLock) {
821 updatePowerSaveTempWhitelistUL();
822 updateRulesForTempWhitelistChangeUL();
823 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700824 }
825 }
826 };
827
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700828 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700829 @Override
830 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700831 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700832
833 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700834 final int uid = intent.getIntExtra(EXTRA_UID, -1);
835 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700836
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700837 if (ACTION_PACKAGE_ADDED.equals(action)) {
838 // update rules for UID, since it might be subject to
839 // global background data policy
840 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700841 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700842 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700843 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700844 }
845 }
846 };
847
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700848 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700849 @Override
850 public void onReceive(Context context, Intent intent) {
851 // on background handler thread, and UID_REMOVED is protected
852
853 final int uid = intent.getIntExtra(EXTRA_UID, -1);
854 if (uid == -1) return;
855
856 // remove any policy and update rules to clean up
857 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700858 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700859 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700860 synchronized (mNetworkPoliciesSecondLock) {
861 writePolicyAL();
862 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700863 }
864 }
865 };
866
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700867 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700868 @Override
869 public void onReceive(Context context, Intent intent) {
870 // on background handler thread, and USER_ADDED and USER_REMOVED
871 // broadcasts are protected
872
873 final String action = intent.getAction();
874 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
875 if (userId == -1) return;
876
Amith Yamasani15e472352015-04-24 19:06:07 -0700877 switch (action) {
878 case ACTION_USER_REMOVED:
879 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700880 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800881 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700882 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700883 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700884 if (action == ACTION_USER_ADDED) {
885 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700886 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700887 }
888 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700889 synchronized (mNetworkPoliciesSecondLock) {
890 updateRulesForGlobalChangeAL(true);
891 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700892 }
893 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700894 }
895 }
896 };
897
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700898 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700899 * Receiver that watches for {@link INetworkStatsService} updates, which we
900 * use to check against {@link NetworkPolicy#warningBytes}.
901 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700902 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700903 @Override
904 public void onReceive(Context context, Intent intent) {
905 // on background handler thread, and verified
906 // READ_NETWORK_USAGE_HISTORY permission above.
907
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800908 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700909 synchronized (mNetworkPoliciesSecondLock) {
910 updateNetworkEnabledNL();
911 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700912 }
913 }
914 };
915
916 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700917 * Receiver that watches for {@link Notification} control of
918 * {@link #mRestrictBackground}.
919 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700920 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700921 @Override
922 public void onReceive(Context context, Intent intent) {
923 // on background handler thread, and verified MANAGE_NETWORK_POLICY
924 // permission above.
925
926 setRestrictBackground(false);
927 }
928 };
929
930 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800931 * Receiver that watches for {@link Notification} control of
932 * {@link NetworkPolicy#lastWarningSnooze}.
933 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700934 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800935 @Override
936 public void onReceive(Context context, Intent intent) {
937 // on background handler thread, and verified MANAGE_NETWORK_POLICY
938 // permission above.
939
940 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
941 performSnooze(template, TYPE_WARNING);
942 }
943 };
944
945 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600946 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
947 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700948 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600949 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700950 @Override
951 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900952 synchronized (mUidRulesFirstLock) {
953 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600954 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700955 }
956 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600957 // Only need to perform upgrade logic once
958 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700959 }
960 };
961
962 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700963 * Observer that watches for {@link INetworkManagementService} alerts.
964 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700965 final private INetworkManagementEventObserver mAlertObserver
966 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700967 @Override
968 public void limitReached(String limitName, String iface) {
969 // only someone like NMS should be calling us
970 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
971
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800972 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
973 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700974 }
975 }
976 };
977
978 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700979 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
980 * to show visible notifications as needed.
981 */
Felipe Lemef0823852016-06-08 13:43:08 -0700982 void updateNotificationsNL() {
983 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -0700984
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700985 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -0400986 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700987 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700988
989 // TODO: when switching to kernel notifications, compute next future
990 // cycle boundary to recompute notifications.
991
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700992 // examine stats for each active policy
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800993 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700994 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
995 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700996 // ignore policies that aren't relevant to user
997 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700998 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700999
Jeff Sharkey497e4432011-06-14 17:27:29 -07001000 final long start = computeLastCycleBoundary(currentTime, policy);
1001 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001002 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001003
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001004 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001005 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001006 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1007 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001008 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001009 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001010 }
1011
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001013 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001014
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001015 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001016 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001017 }
1018 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001019 }
1020
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001021 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001022 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001023 final NotificationId notificationId = beforeNotifs.valueAt(i);
1024 if (!mActiveNotifs.contains(notificationId)) {
1025 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001026 }
1027 }
1028 }
1029
1030 /**
1031 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001032 * current device state, such as when
1033 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1034 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001035 */
1036 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001037 if (template.isMatchRuleMobile()) {
1038 final TelephonyManager tele = TelephonyManager.from(mContext);
1039 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001040
Jeff Sharkey32566012014-12-02 18:30:14 -08001041 // Mobile template is relevant when any active subscriber matches
1042 final int[] subIds = sub.getActiveSubscriptionIdList();
1043 for (int subId : subIds) {
1044 final String subscriberId = tele.getSubscriberId(subId);
1045 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001046 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001047 if (template.matches(probeIdent)) {
1048 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001049 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001050 }
1051 return false;
1052 } else {
1053 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001055 }
1056
1057 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001058 * Notify that given {@link NetworkTemplate} is over
1059 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1060 */
Felipe Lemef0823852016-06-08 13:43:08 -07001061 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001062 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001063 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001064 mOverLimitNotified.add(template);
1065 }
1066 }
1067
Felipe Lemef0823852016-06-08 13:43:08 -07001068 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001069 mOverLimitNotified.remove(template);
1070 }
1071
1072 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001073 * Show notification for combined {@link NetworkPolicy} and specific type,
1074 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1075 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001077 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001078 final Notification.Builder builder =
1079 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001080 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001081 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001082 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001083 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001084
1085 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001086 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001087 switch (type) {
1088 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001089 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001090 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001091
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001092 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001093 builder.setTicker(title);
1094 builder.setContentTitle(title);
1095 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001096 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001097 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001098
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001099 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1100 builder.setDeleteIntent(PendingIntent.getBroadcast(
1101 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1102
Wei Liu546cb772016-07-21 16:19:01 -07001103 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001104 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001105 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1106
Jeff Sharkey497e4432011-06-14 17:27:29 -07001107 break;
1108 }
1109 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001110 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001111
1112 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001113 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001114 switch (policy.template.getMatchRule()) {
1115 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001116 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001117 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001118 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001120 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001121 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001122 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001123 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001124 case MATCH_WIFI:
1125 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001126 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001127 break;
1128 default:
1129 title = null;
1130 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001131 }
1132
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001133 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001134 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001135 builder.setTicker(title);
1136 builder.setContentTitle(title);
1137 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001138
Wei Liu546cb772016-07-21 16:19:01 -07001139 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001140 builder.setContentIntent(PendingIntent.getActivity(
1141 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1142 break;
1143 }
1144 case TYPE_LIMIT_SNOOZED: {
1145 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001146 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001147 Formatter.formatFileSize(mContext, overBytes));
1148
1149 final CharSequence title;
1150 switch (policy.template.getMatchRule()) {
1151 case MATCH_MOBILE_3G_LOWER:
1152 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1153 break;
1154 case MATCH_MOBILE_4G:
1155 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1156 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001157 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001158 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1159 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001160 case MATCH_WIFI:
1161 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1162 break;
1163 default:
1164 title = null;
1165 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001166 }
1167
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001168 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001169 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001170 builder.setTicker(title);
1171 builder.setContentTitle(title);
1172 builder.setContentText(body);
1173
Wei Liu546cb772016-07-21 16:19:01 -07001174 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001175 builder.setContentIntent(PendingIntent.getActivity(
1176 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001177 break;
1178 }
1179 }
1180
1181 // TODO: move to NotificationManager once we can mock it
1182 try {
1183 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001184 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001185 builder.setStyle(new Notification.BigTextStyle()
1186 .bigText(body));
1187 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001188 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001189 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001190 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001191 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001193 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001194 }
1195 }
1196
Chris Wren193ae6b2017-03-31 15:17:11 -04001197 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001198 // TODO: move to NotificationManager once we can mock it
1199 try {
1200 final String packageName = mContext.getPackageName();
1201 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001202 packageName, notificationId.getTag(), notificationId.getId(),
1203 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001204 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001205 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 }
1207 }
1208
1209 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001210 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001211 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001212 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001213 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001214 @Override
1215 public void onReceive(Context context, Intent intent) {
1216 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1217 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001218
1219 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001220 synchronized (mUidRulesFirstLock) {
1221 synchronized (mNetworkPoliciesSecondLock) {
1222 ensureActiveMobilePolicyAL();
1223 normalizePoliciesNL();
1224 updateNetworkEnabledNL();
1225 updateNetworkRulesNL();
1226 updateNotificationsNL();
1227 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001228 }
1229 }
1230 };
1231
1232 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001233 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1234 * if necessary.
1235 *
1236 * @param subId that has its associated NetworkPolicy updated if necessary
1237 * @return if any policies were updated
1238 */
1239 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1240 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1241 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1242
1243 if (config == null) {
1244 return false;
1245 }
1246
1247 boolean policyUpdated = false;
1248 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1249
1250 // find and update the mobile NetworkPolicy for this subscriber id
1251 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1252 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1253 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1254 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1255 if (template.matches(probeIdent)) {
1256 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1257
1258 // only update the policy if the user didn't change any of the defaults.
1259 if (!policy.inferred) {
1260 // TODO: inferred could be split, so that if a user changes their data limit or
1261 // warning, it doesn't prevent their cycle date from being updated.
1262 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1263 continue;
1264 }
1265
1266 final int cycleDay = getCycleDayFromCarrierConfig(config, policy.cycleDay);
1267 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1268 policy.warningBytes);
1269 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1270 policy.limitBytes);
1271
1272 if (policy.cycleDay == cycleDay &&
1273 policy.warningBytes == warningBytes &&
1274 policy.limitBytes == limitBytes) {
1275 continue;
1276 }
1277
1278 policyUpdated = true;
1279 policy.cycleDay = cycleDay;
1280 policy.warningBytes = warningBytes;
1281 policy.limitBytes = limitBytes;
1282
1283 if (LOGD) {
1284 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1285 + NetworkIdentity.scrubSubscriberId(subscriberId)
1286 + " from CarrierConfigManager");
1287 }
1288 }
1289 }
1290
1291 return policyUpdated;
1292 }
1293
1294 /**
1295 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1296 *
1297 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1298 * to do so, it returns the fallback value.
1299 *
1300 * @param config The CarrierConfig to read the value from.
1301 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1302 * @return cycleDay to use in the mobile NetworkPolicy.
1303 */
1304 @VisibleForTesting
1305 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1306 int fallbackCycleDay) {
1307 if (config == null) {
1308 return fallbackCycleDay;
1309 }
1310 int cycleDay =
1311 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1312 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1313 return fallbackCycleDay;
1314 }
1315 // validate cycleDay value
1316 final Calendar cal = Calendar.getInstance();
1317 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1318 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1319 Slog.e(TAG, "Invalid date in "
1320 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1321 return fallbackCycleDay;
1322 }
1323 return cycleDay;
1324 }
1325
1326 /**
1327 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1328 *
1329 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1330 * to do so, it returns the fallback value.
1331 *
1332 * @param config The CarrierConfig to read the value from.
1333 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1334 * @return warningBytes to use in the mobile NetworkPolicy.
1335 */
1336 @VisibleForTesting
1337 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1338 long fallbackWarningBytes) {
1339 if (config == null) {
1340 return fallbackWarningBytes;
1341 }
1342 long warningBytes =
1343 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1344
1345 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1346 return WARNING_DISABLED;
1347 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1348 return getPlatformDefaultWarningBytes();
1349 } else if (warningBytes < 0) {
1350 Slog.e(TAG, "Invalid value in "
1351 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1352 + "non-negative value but got: " + warningBytes);
1353 return fallbackWarningBytes;
1354 }
1355
1356 return warningBytes;
1357 }
1358
1359 /**
1360 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1361 *
1362 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1363 * to do so, it returns the fallback value.
1364 *
1365 * @param config The CarrierConfig to read the value from.
1366 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1367 * @return limitBytes to use in the mobile NetworkPolicy.
1368 */
1369 @VisibleForTesting
1370 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1371 long fallbackLimitBytes) {
1372 if (config == null) {
1373 return fallbackLimitBytes;
1374 }
1375 long limitBytes =
1376 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1377
1378 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1379 return LIMIT_DISABLED;
1380 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1381 return getPlatformDefaultLimitBytes();
1382 } else if (limitBytes < 0) {
1383 Slog.e(TAG, "Invalid value in "
1384 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1385 + "non-negative value but got: " + limitBytes);
1386 return fallbackLimitBytes;
1387 }
1388 return limitBytes;
1389 }
1390
1391 /**
1392 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1393 */
1394 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1395 @Override
1396 public void onReceive(Context context, Intent intent) {
1397 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1398 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1399
1400 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1401 return;
1402 }
1403 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1404 final TelephonyManager tele = TelephonyManager.from(mContext);
1405 final String subscriberId = tele.getSubscriberId(subId);
1406
1407 maybeRefreshTrustedTime();
1408 synchronized (mUidRulesFirstLock) {
1409 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001410 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001411 if (added) return;
1412 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1413 if (!updated) return;
1414 // update network and notification rules, as the data cycle changed and it's
1415 // possible that we should be triggering warnings/limits now
1416 handleNetworkPoliciesUpdateAL(true);
1417 }
1418 }
1419 }
1420 };
1421
1422 /**
1423 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1424 * one has been updated.
1425 *
1426 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1427 * update.
1428 */
1429 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1430 if (shouldNormalizePolicies) {
1431 normalizePoliciesNL();
1432 }
1433 updateNetworkEnabledNL();
1434 updateNetworkRulesNL();
1435 updateNotificationsNL();
1436 writePolicyAL();
1437 }
1438
1439 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001440 * Proactively control network data connections when they exceed
1441 * {@link NetworkPolicy#limitBytes}.
1442 */
Felipe Lemef0823852016-06-08 13:43:08 -07001443 void updateNetworkEnabledNL() {
1444 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001445
1446 // TODO: reset any policy-disabled networks when any policy is removed
1447 // completely, which is currently rare case.
1448
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001449 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001450 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1451 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001452 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001453 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001454 setNetworkTemplateEnabled(policy.template, true);
1455 continue;
1456 }
1457
1458 final long start = computeLastCycleBoundary(currentTime, policy);
1459 final long end = currentTime;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001460 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001461
1462 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001463 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1464 && policy.lastLimitSnooze < start;
1465 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001466
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001467 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001468 }
1469 }
1470
1471 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001472 * Proactively disable networks that match the given
1473 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001474 */
1475 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001476 // TODO: reach into ConnectivityManager to proactively disable bringing
1477 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001478
1479 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1480 // If mobile data usage hits the limit or if the user resumes the data, we need to
1481 // notify telephony.
1482 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1483 final TelephonyManager tm = TelephonyManager.from(mContext);
1484
1485 final int[] subIds = sm.getActiveSubscriptionIdList();
1486 for (int subId : subIds) {
1487 final String subscriberId = tm.getSubscriberId(subId);
1488 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1489 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1490 // Template is matched when subscriber id matches.
1491 if (template.matches(probeIdent)) {
1492 tm.setPolicyDataEnabled(enabled, subId);
1493 }
1494 }
1495 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001496 }
1497
1498 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499 * Examine all connected {@link NetworkState}, looking for
1500 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1501 * remaining quota based on usage cycle and historical stats.
1502 */
Felipe Lemef0823852016-06-08 13:43:08 -07001503 void updateNetworkRulesNL() {
1504 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505
1506 final NetworkState[] states;
1507 try {
1508 states = mConnManager.getAllNetworkState();
1509 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001510 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001511 return;
1512 }
1513
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001514 // First, generate identities of all connected networks so we can
1515 // quickly compare them against all defined policies below.
1516 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001517 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001518 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001519 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001520 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001521
1522 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001523 if (baseIface != null) {
1524 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001525 }
1526
1527 // Stacked interfaces are considered to have same identity as
1528 // their parent network.
1529 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1530 for (LinkProperties stackedLink : stackedLinks) {
1531 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001532 if (stackedIface != null) {
1533 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001534 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001535 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001536 }
1537 }
1538
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001539 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001540 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001541 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001542 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001543 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001545 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001546 for (int j = connIdents.size() - 1; j >= 0; j--) {
1547 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1548 if (policy.template.matches(ident.second)) {
1549 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001550 }
1551 }
1552
1553 if (ifaceList.size() > 0) {
1554 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001555 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001556 }
1557 }
1558
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001559 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001560 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001561
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001562 // apply each policy that we found ifaces for; compute remaining data
1563 // based on current cycle and historical stats, and push to kernel.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001564 final long currentTime = currentTimeMillis();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001565 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1566 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1567 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001568
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001569 final long start;
1570 final long totalBytes;
1571 if (policy.hasCycle()) {
1572 start = computeLastCycleBoundary(currentTime, policy);
1573 totalBytes = getTotalBytes(policy.template, start, currentTime);
1574 } else {
1575 start = Long.MAX_VALUE;
1576 totalBytes = 0;
1577 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001578
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001579 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001580 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581 }
1582
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001583 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001584 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001585 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001586 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001587 if (!hasLimit) {
1588 // metered network, but no policy limit; we still need to
1589 // restrict apps, so push really high quota.
1590 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001591 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001592 // snoozing past quota, but we still need to restrict apps,
1593 // so push really high quota.
1594 quotaBytes = Long.MAX_VALUE;
1595 } else {
1596 // remaining "quota" bytes are based on total usage in
1597 // current cycle. kernel doesn't like 0-byte rules, so we
1598 // set 1-byte quota and disable the radio later.
1599 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1600 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001601
1602 if (ifaces.length > 1) {
1603 // TODO: switch to shared quota once NMS supports
1604 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001605 }
1606
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001607 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001608 // long quotaBytes split up into two ints to fit in message
1609 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1610 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1611 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001612 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001613 }
1614 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001615
1616 // keep track of lowest warning or limit of active policies
1617 if (hasWarning && policy.warningBytes < lowestRule) {
1618 lowestRule = policy.warningBytes;
1619 }
1620 if (hasLimit && policy.limitBytes < lowestRule) {
1621 lowestRule = policy.limitBytes;
1622 }
1623 }
1624
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001625 for (int i = connIfaces.size()-1; i >= 0; i--) {
1626 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001627 // long quotaBytes split up into two ints to fit in message
1628 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1629 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1630 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001631 newMeteredIfaces.add(iface);
1632 }
1633
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001634 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001635
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001636 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001637 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1638 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001639 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001640 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1641 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001642 }
1643 }
1644 mMeteredIfaces = newMeteredIfaces;
1645
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001646 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001647 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001648 }
1649
1650 /**
1651 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1652 * have at least a default mobile policy defined.
1653 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001654 private void ensureActiveMobilePolicyAL() {
1655 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001656 if (mSuppressDefaultPolicy) return;
1657
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001658 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001659 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001660
Jeff Sharkey32566012014-12-02 18:30:14 -08001661 final int[] subIds = sub.getActiveSubscriptionIdList();
1662 for (int subId : subIds) {
1663 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001664 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001665 }
1666 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001667
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001668 /**
1669 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1670 * have at least a default mobile policy defined.
1671 *
1672 * @param subId to build a default policy for
1673 * @param subscriberId that we check for an existing policy
1674 * @return true if a mobile network policy was added, or false one already existed.
1675 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001676 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001677 // Poke around to see if we already have a policy
1678 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001679 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001680 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1681 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1682 if (template.matches(probeIdent)) {
1683 if (LOGD) {
1684 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1685 + NetworkIdentity.scrubSubscriberId(subscriberId));
1686 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001687 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001688 }
1689 }
1690
Jeff Sharkey32566012014-12-02 18:30:14 -08001691 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1692 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001693 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001694 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001695 return true;
1696 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001697
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001698 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001699 final int dataWarningConfig = mContext.getResources().getInteger(
1700 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001701 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001702 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001703 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001704 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001705 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001706 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001707
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001708 private long getPlatformDefaultLimitBytes() {
1709 return LIMIT_DISABLED;
1710 }
1711
1712 @VisibleForTesting
1713 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1714 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1715
1716 // assume usage cycle starts today
Jeff Sharkey32566012014-12-02 18:30:14 -08001717 final Time time = new Time();
1718 time.setToNow();
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001719
Jeff Sharkey32566012014-12-02 18:30:14 -08001720 final String cycleTimezone = time.timezone;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001721
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001722 final int cycleDay = getCycleDayFromCarrierConfig(config, time.monthDay);
1723 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1724 getPlatformDefaultWarningBytes());
1725 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1726 getPlatformDefaultLimitBytes());
1727
Jeff Sharkey32566012014-12-02 18:30:14 -08001728 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
1729 final NetworkPolicy policy = new NetworkPolicy(template, cycleDay, cycleTimezone,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001730 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1731 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001732 }
1733
Felipe Lemef0823852016-06-08 13:43:08 -07001734 private void readPolicyAL() {
1735 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001736
1737 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001738 mNetworkPolicy.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001739 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001740
1741 FileInputStream fis = null;
1742 try {
1743 fis = mPolicyFile.openRead();
1744 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001745 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001746
Felipe Leme46b451f2016-08-19 08:46:17 -07001747 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1748 // to skip UIDs that were explicitly blacklisted.
1749 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1750
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001751 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001752 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001753 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001754 while ((type = in.next()) != END_DOCUMENT) {
1755 final String tag = in.getName();
1756 if (type == START_TAG) {
1757 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001758 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001759 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001760 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1761 mRestrictBackground = readBooleanAttribute(
1762 in, ATTR_RESTRICT_BACKGROUND);
1763 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001764 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001765 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001766 if (mRestrictBackground != oldValue) {
1767 // Some early services may have read the default value,
1768 // so notify them that it's changed
1769 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1770 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1771 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001772
1773 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1774 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1775 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001776 final String networkId;
1777 if (version >= VERSION_ADDED_NETWORK_ID) {
1778 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1779 } else {
1780 networkId = null;
1781 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001782 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001783 final String cycleTimezone;
1784 if (version >= VERSION_ADDED_TIMEZONE) {
1785 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1786 } else {
1787 cycleTimezone = Time.TIMEZONE_UTC;
1788 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001789 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1790 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001791 final long lastLimitSnooze;
1792 if (version >= VERSION_SPLIT_SNOOZE) {
1793 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1794 } else if (version >= VERSION_ADDED_SNOOZE) {
1795 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001796 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001797 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001798 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001799 final boolean metered;
1800 if (version >= VERSION_ADDED_METERED) {
1801 metered = readBooleanAttribute(in, ATTR_METERED);
1802 } else {
1803 switch (networkTemplate) {
1804 case MATCH_MOBILE_3G_LOWER:
1805 case MATCH_MOBILE_4G:
1806 case MATCH_MOBILE_ALL:
1807 metered = true;
1808 break;
1809 default:
1810 metered = false;
1811 }
1812 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001813 final long lastWarningSnooze;
1814 if (version >= VERSION_SPLIT_SNOOZE) {
1815 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1816 } else {
1817 lastWarningSnooze = SNOOZE_NEVER;
1818 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001819 final boolean inferred;
1820 if (version >= VERSION_ADDED_INFERRED) {
1821 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1822 } else {
1823 inferred = false;
1824 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001825
Jeff Sharkey32566012014-12-02 18:30:14 -08001826 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1827 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001828 if (template.isPersistable()) {
1829 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleDay,
1830 cycleTimezone, warningBytes, limitBytes, lastWarningSnooze,
1831 lastLimitSnooze, metered, inferred));
1832 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001833 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001834 final int uid = readIntAttribute(in, ATTR_UID);
1835 final int policy = readIntAttribute(in, ATTR_POLICY);
1836
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001837 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001838 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001839 } else {
1840 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1841 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001842 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001843 final int appId = readIntAttribute(in, ATTR_APP_ID);
1844 final int policy = readIntAttribute(in, ATTR_POLICY);
1845
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001846 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001847 // app policy is deprecated so this is only used in pre system user split.
1848 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001849 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001850 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001851 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001852 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001853 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001854 } else if (TAG_WHITELIST.equals(tag)) {
1855 insideWhitelist = true;
1856 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1857 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001858 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001859 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1860 final int uid = readIntAttribute(in, ATTR_UID);
1861 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001862 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001863 } else if (type == END_TAG) {
1864 if (TAG_WHITELIST.equals(tag)) {
1865 insideWhitelist = false;
1866 }
1867
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001868 }
1869 }
1870
Felipe Leme46b451f2016-08-19 08:46:17 -07001871 final int size = whitelistedRestrictBackground.size();
1872 for (int i = 0; i < size; i++) {
1873 final int uid = whitelistedRestrictBackground.keyAt(i);
1874 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1875 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1876 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1877 + " because its policy is " + uidPoliciesToString(policy));
1878 continue;
1879 }
1880 if (UserHandle.isApp(uid)) {
1881 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1882 if (LOGV)
1883 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1884 setUidPolicyUncheckedUL(uid, newPolicy, false);
1885 } else {
1886 Slog.w(TAG, "unable to update policy on UID " + uid);
1887 }
1888 }
1889
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001890 } catch (FileNotFoundException e) {
1891 // missing policy is okay, probably first boot
Felipe Lemef0823852016-06-08 13:43:08 -07001892 upgradeLegacyBackgroundDataUL();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001893 } catch (IOException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001894 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001895 } catch (XmlPullParserException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001896 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001897 } finally {
1898 IoUtils.closeQuietly(fis);
1899 }
1900 }
1901
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001902 /**
1903 * Upgrade legacy background data flags, notifying listeners of one last
1904 * change to always-true.
1905 */
Felipe Lemef0823852016-06-08 13:43:08 -07001906 private void upgradeLegacyBackgroundDataUL() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001907 mRestrictBackground = Settings.Secure.getInt(
1908 mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, 1) != 1;
1909
1910 // kick off one last broadcast if restricted
1911 if (mRestrictBackground) {
1912 final Intent broadcast = new Intent(
1913 ConnectivityManager.ACTION_BACKGROUND_DATA_SETTING_CHANGED);
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001914 mContext.sendBroadcastAsUser(broadcast, UserHandle.ALL);
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001915 }
1916 }
1917
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001918 /**
1919 * Perform upgrade step of moving any user-defined meterness overrides over
1920 * into {@link WifiConfiguration}.
1921 */
1922 private void upgradeWifiMeteredOverrideAL() {
1923 boolean modified = false;
1924 final WifiManager wm = mContext.getSystemService(WifiManager.class);
1925 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
1926 for (int i = 0; i < mNetworkPolicy.size(); ) {
1927 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1928 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
1929 && !policy.inferred) {
1930 mNetworkPolicy.removeAt(i);
1931 modified = true;
1932
1933 final String networkId = resolveNetworkId(policy.template.getNetworkId());
1934 for (WifiConfiguration config : configs) {
1935 if (Objects.equals(resolveNetworkId(config), networkId)) {
1936 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
1937 config.meteredOverride = policy.metered
1938 ? WifiConfiguration.METERED_OVERRIDE_METERED
1939 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
1940 wm.updateNetwork(config);
1941 }
1942 }
1943 } else {
1944 i++;
1945 }
1946 }
1947 if (modified) {
1948 writePolicyAL();
1949 }
1950 }
1951
Felipe Lemef0823852016-06-08 13:43:08 -07001952 void writePolicyAL() {
1953 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001954
1955 FileOutputStream fos = null;
1956 try {
1957 fos = mPolicyFile.startWrite();
1958
1959 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001960 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 out.startDocument(null, true);
1962
1963 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001964 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07001965 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001966
1967 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001968 for (int i = 0; i < mNetworkPolicy.size(); i++) {
1969 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001970 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001971 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001972
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001973 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001974 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
1975 final String subscriberId = template.getSubscriberId();
1976 if (subscriberId != null) {
1977 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001978 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001979 final String networkId = template.getNetworkId();
1980 if (networkId != null) {
1981 out.attribute(null, ATTR_NETWORK_ID, networkId);
1982 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001983 writeIntAttribute(out, ATTR_CYCLE_DAY, policy.cycleDay);
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001984 out.attribute(null, ATTR_CYCLE_TIMEZONE, policy.cycleTimezone);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001985 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
1986 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001987 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
1988 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001989 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07001990 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001991 out.endTag(null, TAG_NETWORK_POLICY);
1992 }
1993
1994 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001995 for (int i = 0; i < mUidPolicy.size(); i++) {
1996 final int uid = mUidPolicy.keyAt(i);
1997 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001998
Jeff Sharkey497e4432011-06-14 17:27:29 -07001999 // skip writing empty policies
2000 if (policy == POLICY_NONE) continue;
2001
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002002 out.startTag(null, TAG_UID_POLICY);
2003 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002004 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002005 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002006 }
2007
2008 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002009
2010 // write all whitelists
2011 out.startTag(null, TAG_WHITELIST);
2012
Felipe Lemea9505cc2016-02-26 10:28:41 -08002013 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002014 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002015 for (int i = 0; i < size; i++) {
2016 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2017 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2018 writeIntAttribute(out, ATTR_UID, uid);
2019 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2020 }
2021
Felipe Lemeb85a6372016-01-14 16:16:16 -08002022 out.endTag(null, TAG_WHITELIST);
2023
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002024 out.endDocument();
2025
2026 mPolicyFile.finishWrite(fos);
2027 } catch (IOException e) {
2028 if (fos != null) {
2029 mPolicyFile.failWrite(fos);
2030 }
2031 }
2032 }
2033
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002034 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002035 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002036 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002037
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002038 if (!UserHandle.isApp(uid)) {
2039 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002040 }
Felipe Lemef0823852016-06-08 13:43:08 -07002041 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002042 final long token = Binder.clearCallingIdentity();
2043 try {
2044 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2045 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002046 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002047 }
2048 } finally {
2049 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002050 }
2051 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002052 }
2053
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002054 @Override
2055 public void addUidPolicy(int uid, int policy) {
2056 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002057
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002058 if (!UserHandle.isApp(uid)) {
2059 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2060 }
2061
Felipe Lemef0823852016-06-08 13:43:08 -07002062 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002063 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2064 policy |= oldPolicy;
2065 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002066 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002067 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002068 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002069 }
2070
2071 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002072 public void removeUidPolicy(int uid, int policy) {
2073 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2074
2075 if (!UserHandle.isApp(uid)) {
2076 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2077 }
2078
Felipe Lemef0823852016-06-08 13:43:08 -07002079 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002080 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2081 policy = oldPolicy & ~policy;
2082 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002083 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002084 }
2085 }
2086 }
2087
Felipe Lemef0823852016-06-08 13:43:08 -07002088 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2089 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002090
Felipe Leme57e3d312016-08-23 14:42:52 -07002091 final boolean notifyApp;
2092 if (!isUidValidForWhitelistRules(uid)) {
2093 notifyApp = false;
2094 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002095 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2096 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2097 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2098 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002099 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2100 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002101 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2102 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2103 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2104 if (LOGD)
2105 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2106 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2107 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002108 notifyApp = wasBlocked != isBlocked;
2109 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002110 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2111 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002112 }
2113
Felipe Lemef0823852016-06-08 13:43:08 -07002114 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002115 if (policy == POLICY_NONE) {
2116 mUidPolicy.delete(uid);
2117 } else {
2118 mUidPolicy.put(uid, policy);
2119 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002120
2121 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002122 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002123 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002124 synchronized (mNetworkPoliciesSecondLock) {
2125 writePolicyAL();
2126 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002127 }
2128 }
2129
2130 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002131 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002132 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2133
Felipe Lemef0823852016-06-08 13:43:08 -07002134 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002135 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002136 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002137 }
2138
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002139 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002140 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002141 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2142
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002143 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002144 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002145 for (int i = 0; i < mUidPolicy.size(); i++) {
2146 final int uid = mUidPolicy.keyAt(i);
2147 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002148 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2149 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002150 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002151 }
2152 }
2153 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002154 return uids;
2155 }
2156
2157 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002158 * Removes any persistable state associated with given {@link UserHandle}, persisting
2159 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002160 */
Felipe Lemef0823852016-06-08 13:43:08 -07002161 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002162
Felipe Lemef0823852016-06-08 13:43:08 -07002163 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002164 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002165
Felipe Lemea110eec2016-04-29 09:58:06 -07002166 // Remove entries from revoked default restricted background UID whitelist
2167 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2168 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2169 if (UserHandle.getUserId(uid) == userId) {
2170 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002171 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002172 }
2173 }
2174
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002175 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002176 int[] uids = new int[0];
2177 for (int i = 0; i < mUidPolicy.size(); i++) {
2178 final int uid = mUidPolicy.keyAt(i);
2179 if (UserHandle.getUserId(uid) == userId) {
2180 uids = appendInt(uids, uid);
2181 }
2182 }
2183
2184 if (uids.length > 0) {
2185 for (int uid : uids) {
2186 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002187 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002188 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002189 }
Felipe Lemef0823852016-06-08 13:43:08 -07002190 synchronized (mNetworkPoliciesSecondLock) {
2191 updateRulesForGlobalChangeAL(true);
2192 if (writePolicy && changed) {
2193 writePolicyAL();
2194 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002195 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002196 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002197 }
2198
2199 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002200 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002201 // TODO: create permission for observing network policy
2202 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002203 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002204 }
2205
2206 @Override
2207 public void unregisterListener(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.unregister(listener);
2211 }
2212
Jeff Sharkey1b861272011-05-22 00:34:52 -07002213 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002214 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002215 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2216
Felipe Leme6a05eee2016-02-19 14:43:51 -08002217 final long token = Binder.clearCallingIdentity();
2218 try {
2219 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002220 synchronized (mUidRulesFirstLock) {
2221 synchronized (mNetworkPoliciesSecondLock) {
2222 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002223 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002224 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002225 }
2226 } finally {
2227 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002228 }
2229 }
2230
Hugo Benichi446c9c92017-04-10 09:41:10 +09002231 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002232 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002233 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2234 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002235 }
2236
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002237 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002238 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002239 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002240 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002241 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2242 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2243 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002244 } catch (SecurityException e) {
2245 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002246
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002247 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2248 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2249 return new NetworkPolicy[0];
2250 }
Svet Ganov16a16892015-04-16 10:32:04 -07002251 }
2252
Felipe Lemef0823852016-06-08 13:43:08 -07002253 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002254 final int size = mNetworkPolicy.size();
2255 final NetworkPolicy[] policies = new NetworkPolicy[size];
2256 for (int i = 0; i < size; i++) {
2257 policies[i] = mNetworkPolicy.valueAt(i);
2258 }
2259 return policies;
2260 }
2261 }
2262
Felipe Lemef0823852016-06-08 13:43:08 -07002263 private void normalizePoliciesNL() {
2264 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002265 }
2266
Felipe Lemef0823852016-06-08 13:43:08 -07002267 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002268 final TelephonyManager tele = TelephonyManager.from(mContext);
2269 final String[] merged = tele.getMergedSubscriberIds();
2270
2271 mNetworkPolicy.clear();
2272 for (NetworkPolicy policy : policies) {
2273 // When two normalized templates conflict, prefer the most
2274 // restrictive policy
2275 policy.template = NetworkTemplate.normalize(policy.template, merged);
2276 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2277 if (existing == null || existing.compareTo(policy) > 0) {
2278 if (existing != null) {
2279 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2280 }
2281 mNetworkPolicy.put(policy.template, policy);
2282 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002283 }
2284 }
2285
2286 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002287 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002288 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002289
2290 final long token = Binder.clearCallingIdentity();
2291 try {
2292 performSnooze(template, TYPE_LIMIT);
2293 } finally {
2294 Binder.restoreCallingIdentity(token);
2295 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002296 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002297
Dianne Hackborn497175b2014-07-01 12:56:08 -07002298 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002299 maybeRefreshTrustedTime();
2300 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002301 synchronized (mUidRulesFirstLock) {
2302 synchronized (mNetworkPoliciesSecondLock) {
2303 // find and snooze local policy that matches
2304 final NetworkPolicy policy = mNetworkPolicy.get(template);
2305 if (policy == null) {
2306 throw new IllegalArgumentException("unable to find policy for " + template);
2307 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002308
Felipe Lemef0823852016-06-08 13:43:08 -07002309 switch (type) {
2310 case TYPE_WARNING:
2311 policy.lastWarningSnooze = currentTime;
2312 break;
2313 case TYPE_LIMIT:
2314 policy.lastLimitSnooze = currentTime;
2315 break;
2316 default:
2317 throw new IllegalArgumentException("unexpected type");
2318 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002319
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002320 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002321 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002322 }
2323 }
2324
2325 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002326 public void onTetheringChanged(String iface, boolean tethering) {
2327 // No need to enforce permission because setRestrictBackground() will do it.
2328 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002329 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002330 if (mRestrictBackground && tethering) {
2331 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2332 setRestrictBackground(false);
2333 }
2334 }
2335 }
2336
2337 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002338 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002339 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002340 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002341 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2342 final long token = Binder.clearCallingIdentity();
2343 try {
2344 maybeRefreshTrustedTime();
2345 synchronized (mUidRulesFirstLock) {
2346 if (restrictBackground == mRestrictBackground) {
2347 // Ideally, UI should never allow this scenario...
2348 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2349 return;
2350 }
2351 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002352 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002353
2354 } finally {
2355 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002356 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002357
Felipe Leme29e72ea2016-09-08 13:26:55 -07002358 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2359 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002360 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002361 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002362 }
2363 }
2364
Felipe Lemef0823852016-06-08 13:43:08 -07002365 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002366 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002367 final boolean oldRestrictBackground = mRestrictBackground;
2368 mRestrictBackground = restrictBackground;
2369 // Must whitelist foreground apps before turning data saver mode on.
2370 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2371 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002372 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002373 try {
2374 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2375 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2376 mRestrictBackground = oldRestrictBackground;
2377 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002378 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002379 return;
2380 }
2381 } catch (RemoteException e) {
2382 // ignored; service lives in system_server
2383 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002384
2385 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2386 mRestrictBackgroundChangedInBsm = true;
2387 }
Felipe Lemef0823852016-06-08 13:43:08 -07002388 synchronized (mNetworkPoliciesSecondLock) {
2389 updateNotificationsNL();
2390 writePolicyAL();
2391 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002392 }
2393
Felipe Lemeb85a6372016-01-14 16:16:16 -08002394 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002395 public int getRestrictBackgroundByCaller() {
2396 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2397 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002398
Felipe Lemef0823852016-06-08 13:43:08 -07002399 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002400 // Must clear identity because getUidPolicy() is restricted to system.
2401 final long token = Binder.clearCallingIdentity();
2402 final int policy;
2403 try {
2404 policy = getUidPolicy(uid);
2405 } finally {
2406 Binder.restoreCallingIdentity(token);
2407 }
2408 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2409 // App is blacklisted.
2410 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2411 }
Felipe Leme1b103232016-01-22 09:44:57 -08002412 if (!mRestrictBackground) {
2413 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2414 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002415 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002416 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2417 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2418 }
2419 }
2420
2421 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002422 public boolean getRestrictBackground() {
2423 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2424
Felipe Lemef0823852016-06-08 13:43:08 -07002425 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002426 return mRestrictBackground;
2427 }
2428 }
2429
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002430 @Override
2431 public void setDeviceIdleMode(boolean enabled) {
2432 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002433 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2434 try {
2435 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002436 if (mDeviceIdleMode == enabled) {
2437 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002438 }
Felipe Lemeea014392016-09-06 13:59:54 -07002439 mDeviceIdleMode = enabled;
2440 if (mSystemReady) {
2441 // Device idle change means we need to rebuild rules for all
2442 // known apps, so do a global refresh.
2443 updateRulesForRestrictPowerUL();
2444 }
2445 }
2446 if (enabled) {
2447 EventLogTags.writeDeviceIdleOnPhase("net");
2448 } else {
2449 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002450 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002451 } finally {
2452 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002453 }
2454 }
2455
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002456 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002457 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2458 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002459 final long token = Binder.clearCallingIdentity();
2460 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002461 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2462 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2463 for (WifiConfiguration config : configs) {
2464 if (Objects.equals(resolveNetworkId(config), networkId)) {
2465 config.meteredOverride = meteredOverride;
2466 wm.updateNetwork(config);
2467 }
2468 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002469 } finally {
2470 Binder.restoreCallingIdentity(token);
2471 }
2472 }
2473
Jeff Sharkey46645002011-07-27 21:11:21 -07002474 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002475 @Deprecated
2476 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2477 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2478 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2479 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002480 }
2481
2482 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002483 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002484 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002485
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002486 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2487
Dianne Hackborn497175b2014-07-01 12:56:08 -07002488 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002489 for (String arg : args) {
2490 argSet.add(arg);
2491 }
2492
Felipe Lemef0823852016-06-08 13:43:08 -07002493 synchronized (mUidRulesFirstLock) {
2494 synchronized (mNetworkPoliciesSecondLock) {
2495 if (argSet.contains("--unsnooze")) {
2496 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2497 mNetworkPolicy.valueAt(i).clearSnooze();
2498 }
2499
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002500 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002501
2502 fout.println("Cleared snooze timestamps");
2503 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002504 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002505
Felipe Lemef0823852016-06-08 13:43:08 -07002506 fout.print("System ready: "); fout.println(mSystemReady);
2507 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2508 fout.print("Restrict power: "); fout.println(mRestrictPower);
2509 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2510 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002511 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002512 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2513 fout.println(mNetworkPolicy.valueAt(i).toString());
2514 }
2515 fout.decreaseIndent();
2516
2517 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2518
2519 fout.println("Policy for UIDs:");
2520 fout.increaseIndent();
2521 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002522 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002523 final int uid = mUidPolicy.keyAt(i);
2524 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002525 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002526 fout.print(uid);
2527 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002528 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002529 fout.println();
2530 }
2531 fout.decreaseIndent();
2532
2533 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2534 if (size > 0) {
2535 fout.println("Power save whitelist (except idle) app ids:");
2536 fout.increaseIndent();
2537 for (int i = 0; i < size; i++) {
2538 fout.print("UID=");
2539 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2540 fout.print(": ");
2541 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2542 fout.println();
2543 }
2544 fout.decreaseIndent();
2545 }
2546
2547 size = mPowerSaveWhitelistAppIds.size();
2548 if (size > 0) {
2549 fout.println("Power save whitelist app ids:");
2550 fout.increaseIndent();
2551 for (int i = 0; i < size; i++) {
2552 fout.print("UID=");
2553 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2554 fout.print(": ");
2555 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2556 fout.println();
2557 }
2558 fout.decreaseIndent();
2559 }
2560
Felipe Lemef0823852016-06-08 13:43:08 -07002561 size = mDefaultRestrictBackgroundWhitelistUids.size();
2562 if (size > 0) {
2563 fout.println("Default restrict background whitelist uids:");
2564 fout.increaseIndent();
2565 for (int i = 0; i < size; i++) {
2566 fout.print("UID=");
2567 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2568 fout.println();
2569 }
2570 fout.decreaseIndent();
2571 }
2572
2573 size = mRestrictBackgroundWhitelistRevokedUids.size();
2574 if (size > 0) {
2575 fout.println("Default restrict background whitelist uids revoked by users:");
2576 fout.increaseIndent();
2577 for (int i = 0; i < size; i++) {
2578 fout.print("UID=");
2579 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2580 fout.println();
2581 }
2582 fout.decreaseIndent();
2583 }
2584
2585 final SparseBooleanArray knownUids = new SparseBooleanArray();
2586 collectKeys(mUidState, knownUids);
2587 collectKeys(mUidRules, knownUids);
2588
2589 fout.println("Status for all known UIDs:");
2590 fout.increaseIndent();
2591 size = knownUids.size();
2592 for (int i = 0; i < size; i++) {
2593 final int uid = knownUids.keyAt(i);
2594 fout.print("UID=");
2595 fout.print(uid);
2596
2597 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2598 fout.print(" state=");
2599 fout.print(state);
2600 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2601 fout.print(" (fg)");
2602 } else {
2603 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2604 ? " (fg svc)" : " (bg)");
2605 }
2606
2607 final int uidRules = mUidRules.get(uid, RULE_NONE);
2608 fout.print(" rules=");
2609 fout.print(uidRulesToString(uidRules));
2610 fout.println();
2611 }
2612 fout.decreaseIndent();
2613
2614 fout.println("Status for just UIDs with rules:");
2615 fout.increaseIndent();
2616 size = mUidRules.size();
2617 for (int i = 0; i < size; i++) {
2618 final int uid = mUidRules.keyAt(i);
2619 fout.print("UID=");
2620 fout.print(uid);
2621 final int uidRules = mUidRules.get(uid, RULE_NONE);
2622 fout.print(" rules=");
2623 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002624 fout.println();
2625 }
2626 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002627
2628 fout.println("Observed uid state changes:");
2629 fout.increaseIndent();
2630 mObservedHistory.dumpUL(fout);
2631 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002632 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002633 }
2634 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002635
2636 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002637 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002638 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002639 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002640 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002641 }
2642
2643 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002644 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002645 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2646
Felipe Lemef0823852016-06-08 13:43:08 -07002647 synchronized (mUidRulesFirstLock) {
2648 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002649 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002650 }
2651
Felipe Lemef0823852016-06-08 13:43:08 -07002652 private boolean isUidForegroundUL(int uid) {
2653 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002654 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2655 }
2656
Felipe Lemef0823852016-06-08 13:43:08 -07002657 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002658 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002659 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002660 }
2661
Felipe Lemef0823852016-06-08 13:43:08 -07002662 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002663 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2664 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2665 }
2666
Felipe Lemef0823852016-06-08 13:43:08 -07002667 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002668 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002669 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002670 }
2671
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002672 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002673 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002674 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2675 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002676 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002677 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002678 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2679 try {
2680 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2681 if (oldUidState != uidState) {
2682 // state changed, push updated rules
2683 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002684 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2685 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2686 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2687 if (isUidIdle(uid)) {
2688 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002689 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002690 if (mDeviceIdleMode) {
2691 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002692 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002693 if (mRestrictPower) {
2694 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002695 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002696 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002697 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002698 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002699 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002700 } finally {
2701 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002702 }
2703 }
2704
Felipe Lemef0823852016-06-08 13:43:08 -07002705 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002706 final int index = mUidState.indexOfKey(uid);
2707 if (index >= 0) {
2708 final int oldUidState = mUidState.valueAt(index);
2709 mUidState.removeAt(index);
2710 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002711 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002712 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002713 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002714 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002715 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002716 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002717 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002718 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002719 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002720 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002721 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002722 }
2723 }
2724
Felipe Lemef28983d2016-03-25 12:18:23 -07002725 // adjust stats accounting based on foreground status
2726 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002727 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2728 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2729 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
2730 }
Felipe Lemef28983d2016-03-25 12:18:23 -07002731 try {
2732 mNetworkStats.setUidForeground(uid, uidForeground);
2733 } catch (RemoteException e) {
2734 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002735 } finally {
2736 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07002737 }
2738 }
2739
Sudheer Shankac9d94072017-02-22 22:13:55 +00002740 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
2741 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002742 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002743 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002744 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00002745 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002746 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00002747 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002748 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002749 }
2750
Felipe Lemef0823852016-06-08 13:43:08 -07002751 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002752 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
2753 try {
2754 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
2755 mUidFirewallPowerSaveRules);
2756 } finally {
2757 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2758 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002759 }
2760
Felipe Lemef0823852016-06-08 13:43:08 -07002761 void updateRuleForRestrictPowerUL(int uid) {
2762 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002763 }
2764
Felipe Lemef0823852016-06-08 13:43:08 -07002765 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002766 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
2767 try {
2768 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
2769 mUidFirewallDozableRules);
2770 } finally {
2771 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2772 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002773 }
2774
Felipe Lemef0823852016-06-08 13:43:08 -07002775 void updateRuleForDeviceIdleUL(int uid) {
2776 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08002777 }
2778
Felipe Lemef28983d2016-03-25 12:18:23 -07002779 // NOTE: since both fw_dozable and fw_powersave uses the same map
2780 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002781 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08002782 SparseIntArray rules) {
2783 if (enabled) {
2784 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002785 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08002786 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07002787 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002788 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002789 for (int ui = users.size() - 1; ui >= 0; ui--) {
2790 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002791 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
2792 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
2793 if (chain == FIREWALL_CHAIN_POWERSAVE) {
2794 updateRulesForWhitelistedAppIds(uidRules,
2795 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002796 }
2797 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002798 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002799 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002800 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
2801 }
2802 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07002803 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
2804 } else {
2805 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002806 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07002807 }
2808
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002809 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
2810 final SparseBooleanArray whitelistedAppIds, int userId) {
2811 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
2812 if (whitelistedAppIds.valueAt(i)) {
2813 final int appId = whitelistedAppIds.keyAt(i);
2814 final int uid = UserHandle.getUid(userId, appId);
2815 uidRules.put(uid, FIREWALL_RULE_ALLOW);
2816 }
2817 }
2818 }
2819
2820 /**
2821 * @param deviceIdleMode if true then we don't consider
2822 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
2823 * whitelisted.
2824 */
2825 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07002826 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002827 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
2828 || mPowerSaveWhitelistAppIds.get(appId);
2829 if (!deviceIdleMode) {
2830 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
2831 }
2832 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07002833 }
2834
Felipe Lemef28983d2016-03-25 12:18:23 -07002835 // NOTE: since both fw_dozable and fw_powersave uses the same map
2836 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07002837 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002838 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07002839 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
2840 chain == FIREWALL_CHAIN_DOZABLE);
2841 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08002842 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002843 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08002844 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002845 }
2846 }
2847 }
2848
Felipe Lemef0823852016-06-08 13:43:08 -07002849 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002850 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
2851 try {
2852 final SparseIntArray uidRules = mUidFirewallStandbyRules;
2853 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07002854
Felipe Leme873a83a2016-09-07 11:34:10 -07002855 // Fully update the app idle firewall chain.
2856 final List<UserInfo> users = mUserManager.getUsers();
2857 for (int ui = users.size() - 1; ui >= 0; ui--) {
2858 UserInfo user = users.get(ui);
2859 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
2860 for (int uid : idleUids) {
2861 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
2862 // quick check: if this uid doesn't have INTERNET permission, it
2863 // doesn't have network access anyway, so it is a waste to mess
2864 // with it here.
2865 if (hasInternetPermissions(uid)) {
2866 uidRules.put(uid, FIREWALL_RULE_DENY);
2867 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09002868 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002869 }
2870 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07002871
Felipe Lemebc853dd2016-09-08 13:26:55 -07002872 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07002873 } finally {
2874 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2875 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002876 }
2877
Felipe Lemef0823852016-06-08 13:43:08 -07002878 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07002879 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002880
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002881 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2882 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
2883 }
2884 try {
2885 int appId = UserHandle.getAppId(uid);
2886 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
2887 && !isUidForegroundOnRestrictPowerUL(uid)) {
2888 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
2889 } else {
2890 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
2891 }
2892 } finally {
2893 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002894 }
2895 }
2896
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002897 /**
2898 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
2899 * changed.
2900 */
Felipe Lemef0823852016-06-08 13:43:08 -07002901 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002902 boolean paroled = mUsageStats.isAppIdleParoleOn();
2903 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07002904 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002905
2906 int ruleCount = mUidFirewallStandbyRules.size();
2907 for (int i = 0; i < ruleCount; i++) {
2908 int uid = mUidFirewallStandbyRules.keyAt(i);
2909 int oldRules = mUidRules.get(uid);
2910 if (enableChain) {
2911 // Chain wasn't enabled before and the other power-related
2912 // chains are whitelists, so we can clear the
2913 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
2914 // the effective rules result in blocking network access.
2915 oldRules &= MASK_METERED_NETWORKS;
2916 } else {
2917 // Skip if it had no restrictions to begin with
2918 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
2919 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07002920 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
2921 if (newUidRules == RULE_NONE) {
2922 mUidRules.delete(uid);
2923 } else {
2924 mUidRules.put(uid, newUidRules);
2925 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07002926 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07002927 }
2928
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002929 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002930 * Update rules that might be changed by {@link #mRestrictBackground},
2931 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07002932 */
Felipe Lemef0823852016-06-08 13:43:08 -07002933 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002934 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2935 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
2936 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
2937 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002938 try {
Felipe Leme09700462016-09-08 09:33:48 -07002939 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002940 updateRulesForRestrictPowerUL();
2941 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08002942
Felipe Leme873a83a2016-09-07 11:34:10 -07002943 // If the set of restricted networks may have changed, re-evaluate those.
2944 if (restrictedNetworksChanged) {
2945 normalizePoliciesNL();
2946 updateNetworkRulesNL();
2947 }
2948 } finally {
2949 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07002950 }
2951 }
2952
Felipe Leme09700462016-09-08 09:33:48 -07002953 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07002954 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002955 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
2956 try {
2957 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07002958 updateRulesForPowerSaveUL();
2959 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
2960 } finally {
2961 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2962 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002963 }
2964
Felipe Lemef0823852016-06-08 13:43:08 -07002965 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07002966 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
2967 try {
2968 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
2969 } finally {
2970 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
2971 }
Felipe Lemef3e40642016-06-07 17:28:08 -07002972 }
2973
2974 private static final int TYPE_RESTRICT_BACKGROUND = 1;
2975 private static final int TYPE_RESTRICT_POWER = 2;
2976 @Retention(RetentionPolicy.SOURCE)
2977 @IntDef(flag = false, value = {
2978 TYPE_RESTRICT_BACKGROUND,
2979 TYPE_RESTRICT_POWER,
2980 })
2981 public @interface RestrictType {
2982 }
2983
2984 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07002985 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002986 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
2987 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
2988 }
2989 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07002990 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07002991
2992 final PackageManager pm = mContext.getPackageManager();
2993 final List<UserInfo> users;
2994 final List<ApplicationInfo> apps;
2995
2996 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
2997 try {
2998 users = mUserManager.getUsers();
2999 } finally {
3000 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3001 }
3002 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3003 try {
3004 apps = pm.getInstalledApplications(
3005 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3006 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3007 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3008 } finally {
3009 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3010 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003011
Felipe Leme873a83a2016-09-07 11:34:10 -07003012 final int usersSize = users.size();
3013 final int appsSize = apps.size();
3014 for (int i = 0; i < usersSize; i++) {
3015 final UserInfo user = users.get(i);
3016 for (int j = 0; j < appsSize; j++) {
3017 final ApplicationInfo app = apps.get(j);
3018 final int uid = UserHandle.getUid(user.id, app.uid);
3019 switch (type) {
3020 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003021 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003022 break;
3023 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003024 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003025 break;
3026 default:
3027 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3028 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003029 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003030 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003031 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003032 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003033 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003034 }
3035
Felipe Lemef0823852016-06-08 13:43:08 -07003036 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003037 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003038 for (int i = 0; i < users.size(); i++) {
3039 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003040 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003041 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003042 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003043 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003044 updateRuleForAppIdleUL(uid);
3045 updateRuleForDeviceIdleUL(uid);
3046 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003047 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003048 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003049 }
3050 }
3051 }
3052
Felipe Leme70c57c22016-03-29 10:45:13 -07003053 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3054 // methods below could be merged into a isUidValidForRules() method.
3055 private boolean isUidValidForBlacklistRules(int uid) {
3056 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003057 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003058 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003059 return true;
3060 }
3061
3062 return false;
3063 }
3064
Felipe Leme70c57c22016-03-29 10:45:13 -07003065 private boolean isUidValidForWhitelistRules(int uid) {
3066 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3067 }
3068
Amith Yamasani15e472352015-04-24 19:06:07 -07003069 private boolean isUidIdle(int uid) {
3070 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3071 final int userId = UserHandle.getUserId(uid);
3072
songjinshi0655edd2016-05-18 19:55:32 +08003073 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003074 for (String packageName : packages) {
3075 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3076 return false;
3077 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003078 }
3079 }
3080 return true;
3081 }
3082
3083 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003084 * Checks if an uid has INTERNET permissions.
3085 * <p>
3086 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003087 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003088 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003089 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003090 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003091 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003092 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003093 }
3094 } catch (RemoteException e) {
3095 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003096 return true;
3097 }
3098
3099 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003100 * Clears all state - internal and external - associated with an UID.
3101 */
3102 private void onUidDeletedUL(int uid) {
3103 // First cleanup in-memory state synchronously...
3104 mUidRules.delete(uid);
3105 mUidPolicy.delete(uid);
3106 mUidFirewallStandbyRules.delete(uid);
3107 mUidFirewallDozableRules.delete(uid);
3108 mUidFirewallPowerSaveRules.delete(uid);
3109 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3110 mPowerSaveWhitelistAppIds.delete(uid);
3111 mPowerSaveTempWhitelistAppIds.delete(uid);
3112
3113 // ...then update iptables asynchronously.
3114 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3115 }
3116
3117 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003118 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003119 *
Felipe Leme781ba142016-05-09 16:24:48 -07003120 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003121 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003122 * <li>Doze mode
3123 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003124 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003125 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003126 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003127 *
3128 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003129 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003130 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003131 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003132 updateRuleForDeviceIdleUL(uid);
3133 updateRuleForAppIdleUL(uid);
3134 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003135
3136 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003137 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003138
3139 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003140 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003141 }
3142
Felipe Leme70c57c22016-03-29 10:45:13 -07003143 /**
3144 * Applies network rules to bandwidth controllers based on process state and user-defined
3145 * restrictions (blacklist / whitelist).
3146 *
3147 * <p>
3148 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3149 * networks:
3150 * <ul>
3151 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3152 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3153 * also blacklisted.
3154 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3155 * no UIDs other those whitelisted will have access.
3156 * <ul>
3157 *
3158 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3159 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3160 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3161 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003162 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003163 * {@link INetworkManagementService}, but this method should also be called in events (like
3164 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3165 * following rules should also be applied:
3166 *
3167 * <ul>
3168 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3169 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3170 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3171 * {@code bw_penalty_box}.
3172 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3173 * </ul>
3174 *
3175 * <p>For optimization, the rules are only applied on user apps that have internet access
3176 * permission, since there is no need to change the {@code iptables} rule if the app does not
3177 * have permission to use the internet.
3178 *
3179 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003180 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003181 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003182 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003183 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3184 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3185 "updateRulesForDataUsageRestrictionsUL: " + uid);
3186 }
3187 try {
3188 updateRulesForDataUsageRestrictionsULInner(uid);
3189 } finally {
3190 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3191 }
3192 }
3193
3194 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003195 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003196 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003197 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003198 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003199
Dianne Hackborn497175b2014-07-01 12:56:08 -07003200 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003201 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003202 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003203
Felipe Leme781ba142016-05-09 16:24:48 -07003204 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003205 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003206 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3207 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003208
Felipe Leme70c57c22016-03-29 10:45:13 -07003209 // First step: define the new rule based on user restrictions and foreground state.
3210 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003211 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3212 newRule = RULE_TEMPORARY_ALLOW_METERED;
3213 } else if (isWhitelisted) {
3214 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003215 }
3216 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003217 if (isBlacklisted) {
3218 newRule = RULE_REJECT_METERED;
3219 } else if (mRestrictBackground && isWhitelisted) {
3220 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003221 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003222 }
Felipe Leme781ba142016-05-09 16:24:48 -07003223 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003224
Felipe Lemef28983d2016-03-25 12:18:23 -07003225 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003226 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003227 + ": isForeground=" +isForeground
3228 + ", isBlacklisted=" + isBlacklisted
3229 + ", isWhitelisted=" + isWhitelisted
3230 + ", oldRule=" + uidRulesToString(oldRule)
3231 + ", newRule=" + uidRulesToString(newRule)
3232 + ", newUidRules=" + uidRulesToString(newUidRules)
3233 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003234 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003235
Felipe Leme46c4fc32016-05-04 09:21:43 -07003236 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003237 mUidRules.delete(uid);
3238 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003239 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003240 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003241
Felipe Leme70c57c22016-03-29 10:45:13 -07003242 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003243 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003244 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003245 // Temporarily whitelist foreground app, removing from blacklist if necessary
3246 // (since bw_penalty_box prevails over bw_happy_box).
3247
3248 setMeteredNetworkWhitelist(uid, true);
3249 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3250 // but ideally it should be just:
3251 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003252 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003253 setMeteredNetworkBlacklist(uid, false);
3254 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003255 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003256 // Remove temporary whitelist from app that is not on foreground anymore.
3257
3258 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3259 // but ideally they should be just:
3260 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3261 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003262 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003263 setMeteredNetworkWhitelist(uid, false);
3264 }
Felipe Leme781ba142016-05-09 16:24:48 -07003265 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003266 setMeteredNetworkBlacklist(uid, true);
3267 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003268 } else if (hasRule(newRule, RULE_REJECT_METERED)
3269 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003270 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003271 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003272 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003273 // Since blacklist prevails over whitelist, we need to handle the special case
3274 // where app is whitelisted and blacklisted at the same time (although such
3275 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003276 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003277 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003278 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3279 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003280 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003281 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003282 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003283 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003284 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3285 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003286 + ", whitelisted=" + isWhitelisted
3287 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003288 + ", newRule=" + uidRulesToString(newUidRules)
3289 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003290 }
Felipe Leme781ba142016-05-09 16:24:48 -07003291
Sudheer Shankac9d94072017-02-22 22:13:55 +00003292 // Dispatch changed rule to existing listeners.
3293 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003294 }
3295 }
3296
3297 /**
3298 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3299 * listeners in case of change.
3300 * <p>
3301 * There are 3 power-related rules that affects whether an app has background access on
3302 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3303 * restriction, it's added to the equivalent firewall chain:
3304 * <ul>
3305 * <li>App is idle: {@code fw_standby} firewall chain.
3306 * <li>Device is idle: {@code fw_dozable} firewall chain.
3307 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3308 * </ul>
3309 * <p>
3310 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3311 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3312 * <p>
3313 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3314 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003315 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003316 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3317
Sudheer Shankac9d94072017-02-22 22:13:55 +00003318 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003319
Sudheer Shankac9d94072017-02-22 22:13:55 +00003320 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003321 mUidRules.delete(uid);
3322 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003323 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003324 }
3325 }
3326
3327 /**
3328 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3329 *
3330 * @param uid the uid of the app to update rules for
3331 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3332 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3333 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003334 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003335 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003336 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003337 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3338 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3339 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3340 + (paroled ? "P" : "-"));
3341 }
3342 try {
3343 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3344 } finally {
3345 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3346 }
3347 }
3348
3349 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003350 if (!isUidValidForBlacklistRules(uid)) {
3351 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003352 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003353 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003354
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003355 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003356 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003357 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003358
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003359 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003360 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3361 int newRule = RULE_NONE;
3362
3363 // First step: define the new rule based on user restrictions and foreground state.
3364
3365 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3366 // by considering the foreground and non-foreground states.
3367 if (isForeground) {
3368 if (restrictMode) {
3369 newRule = RULE_ALLOW_ALL;
3370 }
3371 } else if (restrictMode) {
3372 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3373 }
3374
3375 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3376
3377 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003378 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003379 + ", isIdle: " + isIdle
3380 + ", mRestrictPower: " + mRestrictPower
3381 + ", mDeviceIdleMode: " + mDeviceIdleMode
3382 + ", isForeground=" + isForeground
3383 + ", isWhitelisted=" + isWhitelisted
3384 + ", oldRule=" + uidRulesToString(oldRule)
3385 + ", newRule=" + uidRulesToString(newRule)
3386 + ", newUidRules=" + uidRulesToString(newUidRules)
3387 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3388 }
3389
Felipe Leme781ba142016-05-09 16:24:48 -07003390 // Second step: notify listeners if state changed.
3391 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003392 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003393 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003394 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003395 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3396 } else {
3397 // All scenarios should have been covered above
3398 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3399 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003400 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003401 + ", newRule=" + uidRulesToString(newUidRules)
3402 + ", oldRule=" + uidRulesToString(oldUidRules));
3403 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003404 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003405 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003406
Sudheer Shankac9d94072017-02-22 22:13:55 +00003407 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003408 }
3409
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003410 private class AppIdleStateChangeListener
3411 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3412
3413 @Override
3414 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3415 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003416 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3417 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003418 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003419 synchronized (mUidRulesFirstLock) {
3420 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003421 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003422 }
3423 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003424 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003425 }
3426
3427 @Override
3428 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003429 synchronized (mUidRulesFirstLock) {
3430 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003431 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003432 }
3433 }
3434
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003435 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3436 if (listener != null) {
3437 try {
3438 listener.onUidRulesChanged(uid, uidRules);
3439 } catch (RemoteException ignored) {
3440 }
3441 }
3442 }
3443
3444 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3445 String[] meteredIfaces) {
3446 if (listener != null) {
3447 try {
3448 listener.onMeteredIfacesChanged(meteredIfaces);
3449 } catch (RemoteException ignored) {
3450 }
3451 }
3452 }
3453
3454 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3455 boolean restrictBackground) {
3456 if (listener != null) {
3457 try {
3458 listener.onRestrictBackgroundChanged(restrictBackground);
3459 } catch (RemoteException ignored) {
3460 }
3461 }
3462 }
3463
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003464 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3465 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003466 if (listener != null) {
3467 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003468 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003469 } catch (RemoteException ignored) {
3470 }
3471 }
3472 }
3473
Makoto Onuki8e777332017-03-28 11:25:47 -07003474 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003475 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003476 public boolean handleMessage(Message msg) {
3477 switch (msg.what) {
3478 case MSG_RULES_CHANGED: {
3479 final int uid = msg.arg1;
3480 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003481 final int length = mListeners.beginBroadcast();
3482 for (int i = 0; i < length; i++) {
3483 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3484 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003485 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003486 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003487 return true;
3488 }
3489 case MSG_METERED_IFACES_CHANGED: {
3490 final String[] meteredIfaces = (String[]) msg.obj;
3491 final int length = mListeners.beginBroadcast();
3492 for (int i = 0; i < length; i++) {
3493 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003494 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003495 }
3496 mListeners.finishBroadcast();
3497 return true;
3498 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003499 case MSG_LIMIT_REACHED: {
3500 final String iface = (String) msg.obj;
3501
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003502 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003503 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003504 if (mMeteredIfaces.contains(iface)) {
3505 try {
3506 // force stats update to make sure we have
3507 // numbers that caused alert to trigger.
3508 mNetworkStats.forceUpdate();
3509 } catch (RemoteException e) {
3510 // ignored; service lives in system_server
3511 }
3512
Felipe Lemef0823852016-06-08 13:43:08 -07003513 updateNetworkEnabledNL();
3514 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003515 }
3516 }
3517 return true;
3518 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003519 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3520 final boolean restrictBackground = msg.arg1 != 0;
3521 final int length = mListeners.beginBroadcast();
3522 for (int i = 0; i < length; i++) {
3523 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003524 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003525 }
3526 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003527 final Intent intent =
3528 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3529 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3530 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3531 return true;
3532 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003533 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003534 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003535 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003536 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003537 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003538 final int length = mListeners.beginBroadcast();
3539 for (int i = 0; i < length; i++) {
3540 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003541 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003542 }
3543 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003544 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3545 if (notifyApp.booleanValue()) {
3546 broadcastRestrictBackgroundChanged(uid, notifyApp);
3547 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003548 return true;
3549 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003550 case MSG_ADVISE_PERSIST_THRESHOLD: {
3551 final long lowestRule = (Long) msg.obj;
3552 try {
3553 // make sure stats are recorded frequently enough; we aim
3554 // for 2MB threshold for 2GB/month rules.
3555 final long persistThreshold = lowestRule / 1000;
3556 mNetworkStats.advisePersistThreshold(persistThreshold);
3557 } catch (RemoteException e) {
3558 // ignored; service lives in system_server
3559 }
3560 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003561 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003562 case MSG_UPDATE_INTERFACE_QUOTA: {
3563 removeInterfaceQuota((String) msg.obj);
3564 // int params need to be stitched back into a long
3565 setInterfaceQuota((String) msg.obj,
3566 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3567 return true;
3568 }
3569 case MSG_REMOVE_INTERFACE_QUOTA: {
3570 removeInterfaceQuota((String) msg.obj);
3571 return true;
3572 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003573 case MSG_SET_FIREWALL_RULES: {
3574 final int chain = msg.arg1;
3575 final int toggle = msg.arg2;
3576 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3577 if (uidRules != null) {
3578 setUidFirewallRules(chain, uidRules);
3579 }
3580 if (toggle != CHAIN_TOGGLE_NONE) {
3581 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3582 }
3583 return true;
3584 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003585 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3586 resetUidFirewallRules(msg.arg1);
3587 return true;
3588 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003589 default: {
3590 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003591 }
3592 }
3593 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003594 };
3595
3596 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3597 @Override
3598 public boolean handleMessage(Message msg) {
3599 switch (msg.what) {
3600 case UID_MSG_STATE_CHANGED: {
3601 final int uid = msg.arg1;
3602 final int procState = msg.arg2;
3603 final long procStateSeq = (Long) msg.obj;
3604
3605 handleUidChanged(uid, procState, procStateSeq);
3606 return true;
3607 }
3608 case UID_MSG_GONE: {
3609 final int uid = msg.arg1;
3610 handleUidGone(uid);
3611 return true;
3612 }
3613 default: {
3614 return false;
3615 }
3616 }
3617 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003618
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003619 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003620
Makoto Onuki8e777332017-03-28 11:25:47 -07003621 void handleUidChanged(int uid, int procState, long procStateSeq) {
3622 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3623 try {
3624 synchronized (mUidRulesFirstLock) {
3625 // We received a uid state change callback, add it to the history so that it
3626 // will be useful for debugging.
3627 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3628 // Now update the network policy rules as per the updated uid state.
3629 updateUidStateUL(uid, procState);
3630 // Updating the network rules is done, so notify AMS about this.
3631 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3632 }
3633 } finally {
3634 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3635 }
3636 }
3637
3638 void handleUidGone(int uid) {
3639 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3640 try {
3641 synchronized (mUidRulesFirstLock) {
3642 removeUidStateUL(uid);
3643 }
3644 } finally {
3645 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3646 }
3647 }
3648
Felipe Leme57e3d312016-08-23 14:42:52 -07003649 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3650 final PackageManager pm = mContext.getPackageManager();
3651 final String[] packages = pm.getPackagesForUid(uid);
3652 if (packages != null) {
3653 final int userId = UserHandle.getUserId(uid);
3654 for (String packageName : packages) {
3655 final Intent intent =
3656 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3657 intent.setPackage(packageName);
3658 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3659 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3660 }
3661 }
3662 }
3663
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003664 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003665 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003666 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003667 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003668 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003669 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003670 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003671 }
3672 }
3673
3674 private void removeInterfaceQuota(String iface) {
3675 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003676 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003677 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003678 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003679 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003680 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003681 }
3682 }
3683
Felipe Leme70c57c22016-03-29 10:45:13 -07003684 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3685 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003686 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003687 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003688 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003689 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3690 } catch (RemoteException e) {
3691 // ignored; service lives in system_server
3692 }
3693 }
3694
3695 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3696 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3697 try {
3698 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3699 } catch (IllegalStateException e) {
3700 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003701 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003702 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003703 }
3704 }
3705
Felipe Lemebc853dd2016-09-08 13:26:55 -07003706 private static final int CHAIN_TOGGLE_NONE = 0;
3707 private static final int CHAIN_TOGGLE_ENABLE = 1;
3708 private static final int CHAIN_TOGGLE_DISABLE = 2;
3709 @Retention(RetentionPolicy.SOURCE)
3710 @IntDef(flag = false, value = {
3711 CHAIN_TOGGLE_NONE,
3712 CHAIN_TOGGLE_ENABLE,
3713 CHAIN_TOGGLE_DISABLE
3714 })
3715 public @interface ChainToggleType {
3716 }
3717
3718 /**
3719 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3720 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3721 *
3722 * @param chain firewall chain.
3723 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3724 * @param toggle whether the chain should be enabled, disabled, or not changed.
3725 */
3726 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
3727 @ChainToggleType int toggle) {
3728 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
3729 }
3730
Amith Yamasani15e472352015-04-24 19:06:07 -07003731 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003732 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
3733 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
3734 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07003735 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003736 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003737 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003738 int size = uidRules.size();
3739 int[] uids = new int[size];
3740 int[] rules = new int[size];
3741 for(int index = size - 1; index >= 0; --index) {
3742 uids[index] = uidRules.keyAt(index);
3743 rules[index] = uidRules.valueAt(index);
3744 }
3745 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07003746 } catch (IllegalStateException e) {
3747 Log.wtf(TAG, "problem setting firewall uid rules", e);
3748 } catch (RemoteException e) {
3749 // ignored; service lives in system_server
3750 }
3751 }
3752
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003753 /**
3754 * Add or remove a uid to the firewall blacklist for all network ifaces.
3755 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003756 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003757 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3758 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3759 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07003760 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003761 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003762 if (chain == FIREWALL_CHAIN_DOZABLE) {
3763 mUidFirewallDozableRules.put(uid, rule);
3764 } else if (chain == FIREWALL_CHAIN_STANDBY) {
3765 mUidFirewallStandbyRules.put(uid, rule);
3766 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
3767 mUidFirewallPowerSaveRules.put(uid, rule);
3768 }
3769
3770 try {
3771 mNetworkManager.setFirewallUidRule(chain, uid, rule);
3772 } catch (IllegalStateException e) {
3773 Log.wtf(TAG, "problem setting firewall uid rules", e);
3774 } catch (RemoteException e) {
3775 // ignored; service lives in system_server
3776 }
3777 } finally {
3778 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003779 }
3780 }
3781
3782 /**
3783 * Add or remove a uid to the firewall blacklist for all network ifaces.
3784 */
Felipe Lemef0823852016-06-08 13:43:08 -07003785 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003786 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
3787 mFirewallChainStates.get(chain) == enable) {
3788 // All is the same, nothing to do.
3789 return;
3790 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003791 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003792 try {
3793 mNetworkManager.setFirewallChainEnabled(chain, enable);
3794 } catch (IllegalStateException e) {
3795 Log.wtf(TAG, "problem enable firewall chain", e);
3796 } catch (RemoteException e) {
3797 // ignored; service lives in system_server
3798 }
3799 }
3800
Felipe Leme03e95e22016-09-09 09:25:31 -07003801 /**
3802 * Resets all firewall rules associated with an UID.
3803 */
3804 private void resetUidFirewallRules(int uid) {
3805 try {
3806 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
3807 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3808 mNetworkManager
3809 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
3810 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
3811 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
3812 } catch (IllegalStateException e) {
3813 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
3814 } catch (RemoteException e) {
3815 // ignored; service lives in system_server
3816 }
3817 }
3818
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003819 private long getTotalBytes(NetworkTemplate template, long start, long end) {
3820 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07003821 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08003822 } catch (RuntimeException e) {
3823 Slog.w(TAG, "problem reading network stats: " + e);
3824 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003825 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003826 // ignored; service lives in system_server
3827 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003828 }
3829 }
3830
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07003831 private boolean isBandwidthControlEnabled() {
3832 final long token = Binder.clearCallingIdentity();
3833 try {
3834 return mNetworkManager.isBandwidthControlEnabled();
3835 } catch (RemoteException e) {
3836 // ignored; service lives in system_server
3837 return false;
3838 } finally {
3839 Binder.restoreCallingIdentity(token);
3840 }
3841 }
3842
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003843 /**
3844 * Try refreshing {@link #mTime} when stale.
3845 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07003846 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003847 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003848 mTime.forceRefresh();
3849 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003850 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003851
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003852 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07003853 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
3854 }
3855
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07003856 private static Intent buildAllowBackgroundDataIntent() {
3857 return new Intent(ACTION_ALLOW_BACKGROUND);
3858 }
3859
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08003860 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
3861 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
3862 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3863 return intent;
3864 }
3865
Wei Liu546cb772016-07-21 16:19:01 -07003866 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003867 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003868 intent.setComponent(ComponentName.unflattenFromString(
3869 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003870 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3871 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3872 return intent;
3873 }
3874
Wei Liu546cb772016-07-21 16:19:01 -07003875 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003876 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07003877 intent.setComponent(ComponentName.unflattenFromString(
3878 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003879 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
3880 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
3881 return intent;
3882 }
3883
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08003884 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07003885 public void addIdleHandler(IdleHandler handler) {
3886 mHandler.getLooper().getQueue().addIdleHandler(handler);
3887 }
3888
jackqdyulei29c82ab2017-03-10 14:09:16 -08003889 @VisibleForTesting
3890 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
3891 mRestrictBackgroundPowerState = result;
3892
3893 boolean restrictBackground = result.batterySaverEnabled;
3894 boolean shouldInvokeRestrictBackground;
3895 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
3896 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
3897
3898 if (result.globalBatterySaverEnabled) {
3899 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
3900 // turn it on.
3901 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
3902 mRestrictBackgroundBeforeBsm = mRestrictBackground;
3903 localRestrictBgChangedInBsm = false;
3904 } else {
3905 // Try to restore the restrictBackground if it doesn't change in bsm
3906 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
3907 restrictBackground = mRestrictBackgroundBeforeBsm;
3908 }
3909
3910 if (shouldInvokeRestrictBackground) {
3911 setRestrictBackground(restrictBackground);
3912 }
3913
3914 // Change it at last so setRestrictBackground() won't affect this variable
3915 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
3916 }
3917
Jeff Sharkey1b861272011-05-22 00:34:52 -07003918 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
3919 final int size = source.size();
3920 for (int i = 0; i < size; i++) {
3921 target.put(source.keyAt(i), true);
3922 }
3923 }
3924
Stuart Scottf1fb3972015-04-02 18:00:02 -07003925 @Override
3926 public void factoryReset(String subscriber) {
3927 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
3928
Stuart Scotte3e314d2015-04-20 14:07:45 -07003929 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
3930 return;
3931 }
3932
Stuart Scottf1fb3972015-04-02 18:00:02 -07003933 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07003934 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07003935 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
3936 for (NetworkPolicy policy : policies) {
3937 if (policy.template.equals(template)) {
3938 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
3939 policy.inferred = false;
3940 policy.clearSnooze();
3941 }
3942 }
3943 setNetworkPolicies(policies);
3944
3945 // Turn restrict background data off
3946 setRestrictBackground(false);
3947
Stuart Scotte3e314d2015-04-20 14:07:45 -07003948 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
3949 // Remove app's "restrict background data" flag
3950 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
3951 setUidPolicy(uid, POLICY_NONE);
3952 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07003953 }
3954 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08003955
Felipe Lemed17fda42016-04-29 11:12:45 -07003956 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
3957
3958 @Override
3959 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07003960 synchronized (mUidRulesFirstLock) {
3961 boolean changed = removeUserStateUL(userId, false);
3962 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07003963 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07003964 synchronized (mNetworkPoliciesSecondLock) {
3965 writePolicyAL();
3966 }
Felipe Lemed17fda42016-04-29 11:12:45 -07003967 }
3968 }
3969 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003970
3971 /**
3972 * @return true if the given uid is restricted from doing networking on metered networks.
3973 */
3974 @Override
3975 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
3976 final int uidRules;
3977 final boolean isBackgroundRestricted;
3978 synchronized (mUidRulesFirstLock) {
3979 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3980 isBackgroundRestricted = mRestrictBackground;
3981 }
3982 return isBackgroundRestricted
3983 && !hasRule(uidRules, RULE_ALLOW_METERED)
3984 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
3985 }
3986
3987 /**
3988 * @return true if networking is blocked on the given interface for the given uid according
3989 * to current networking policies.
3990 */
3991 @Override
3992 public boolean isUidNetworkingBlocked(int uid, String ifname) {
3993 final int uidRules;
3994 final boolean isBackgroundRestricted;
3995 final boolean isNetworkMetered;
3996 synchronized (mUidRulesFirstLock) {
3997 uidRules = mUidRules.get(uid, RULE_NONE);
3998 isBackgroundRestricted = mRestrictBackground;
3999 synchronized (mNetworkPoliciesSecondLock) {
4000 isNetworkMetered = mMeteredIfaces.contains(ifname);
4001 }
4002 }
4003 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4004 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4005 return true;
4006 }
4007 if (!isNetworkMetered) {
4008 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4009 return false;
4010 }
4011 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4012 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4013 return true;
4014 }
4015 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4016 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4017 return false;
4018 }
4019 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4020 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4021 return false;
4022 }
4023 if (isBackgroundRestricted) {
4024 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4025 return true;
4026 }
4027 if (LOGV) logUidStatus(uid, "allowed by default");
4028 return false;
4029 }
4030 }
4031
4032 private static boolean hasRule(int uidRules, int rule) {
4033 return (uidRules & rule) != 0;
4034 }
4035
4036 private static void logUidStatus(int uid, String descr) {
4037 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004038 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004039
4040 /**
4041 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4042 * (uid, procStateSeq) pairs.
4043 */
4044 @VisibleForTesting
4045 public static final class ProcStateSeqHistory {
4046 private static final int INVALID_UID = -1;
4047
4048 /**
4049 * Denotes maximum number of items this history can hold.
4050 */
4051 private final int mMaxCapacity;
4052 /**
4053 * Used for storing the uid information.
4054 */
4055 private final int[] mUids;
4056 /**
4057 * Used for storing the sequence numbers associated with {@link #mUids}.
4058 */
4059 private final long[] mProcStateSeqs;
4060 /**
4061 * Points to the next available slot for writing (uid, procStateSeq) pair.
4062 */
4063 private int mHistoryNext;
4064
4065 public ProcStateSeqHistory(int maxCapacity) {
4066 mMaxCapacity = maxCapacity;
4067 mUids = new int[mMaxCapacity];
4068 Arrays.fill(mUids, INVALID_UID);
4069 mProcStateSeqs = new long[mMaxCapacity];
4070 }
4071
4072 @GuardedBy("mUidRulesFirstLock")
4073 public void addProcStateSeqUL(int uid, long procStateSeq) {
4074 mUids[mHistoryNext] = uid;
4075 mProcStateSeqs[mHistoryNext] = procStateSeq;
4076 mHistoryNext = increaseNext(mHistoryNext, 1);
4077 }
4078
4079 @GuardedBy("mUidRulesFirstLock")
4080 public void dumpUL(IndentingPrintWriter fout) {
4081 if (mUids[0] == INVALID_UID) {
4082 fout.println("NONE");
4083 return;
4084 }
4085 int index = mHistoryNext;
4086 do {
4087 index = increaseNext(index, -1);
4088 if (mUids[index] == INVALID_UID) {
4089 break;
4090 }
4091 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4092 } while (index != mHistoryNext);
4093 }
4094
4095 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004096 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004097 }
4098
4099 private int increaseNext(int next, int increment) {
4100 next += increment;
4101 if (next >= mMaxCapacity) {
4102 next = 0;
4103 } else if (next < 0) {
4104 next = mMaxCapacity - 1;
4105 }
4106 return next;
4107 }
4108 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004109
4110 private class NotificationId {
4111 private final String mTag;
4112 private final int mId;
4113
4114 NotificationId(NetworkPolicy policy, int type) {
4115 mTag = buildNotificationTag(policy, type);
4116 mId = type;
4117 }
4118
4119 @Override
4120 public boolean equals(Object o) {
4121 if (this == o) return true;
4122 if (!(o instanceof NotificationId)) return false;
4123 NotificationId that = (NotificationId) o;
4124 return Objects.equals(mTag, that.mTag);
4125 }
4126
4127 @Override
4128 public int hashCode() {
4129 return Objects.hash(mTag);
4130 }
4131
4132 /**
4133 * Build unique tag that identifies an active {@link NetworkPolicy}
4134 * notification of a specific type, like {@link #TYPE_LIMIT}.
4135 */
4136 private String buildNotificationTag(NetworkPolicy policy, int type) {
4137 return TAG + ":" + policy.template.hashCode() + ":" + type;
4138 }
4139
4140 public String getTag() {
4141 return mTag;
4142 }
4143
4144 public int getId() {
4145 return mId;
4146 }
4147 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004148}