blob: cfdbb0143243ff8453c4147bc001e8dbe50312b5 [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 Sharkeyb74799882017-07-28 16:55:41 -060022import static android.Manifest.permission.MANAGE_SUBSCRIPTION_PLANS;
Jeff Sharkey497e4432011-06-14 17:27:29 -070023import static android.Manifest.permission.READ_NETWORK_USAGE_HISTORY;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070024import static android.Manifest.permission.READ_PHONE_STATE;
Amit Mahajan7c5befa2015-07-14 10:26:00 -070025import static android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE;
Jeff Sharkey02e21d62011-07-17 15:53:33 -070026import static android.content.Intent.ACTION_PACKAGE_ADDED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070027import static android.content.Intent.ACTION_UID_REMOVED;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -070028import static android.content.Intent.ACTION_USER_ADDED;
29import static android.content.Intent.ACTION_USER_REMOVED;
Jeff Sharkeyb09540f2011-06-19 01:08:12 -070030import static android.content.Intent.EXTRA_UID;
Erik Klinef851d6d2015-04-20 16:03:48 +090031import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Felipe Leme1b103232016-01-22 09:44:57 -080032import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_DISABLED;
33import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_ENABLED;
34import static android.net.ConnectivityManager.RESTRICT_BACKGROUND_STATUS_WHITELISTED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060035import static android.net.ConnectivityManager.TYPE_MOBILE;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070036import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070037import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070038import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070039import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070040import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
43import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070044import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060046import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
47import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070048import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070049import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070050import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070051import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070053import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070054import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070056import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
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;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060078import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070079import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
80import static com.android.internal.util.XmlUtils.writeIntAttribute;
81import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060082import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070083import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070084import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060085
Jeff Sharkey21c9c452011-06-07 12:26:43 -070086import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080087import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070088import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070089
Dianne Hackborn88e98df2015-03-23 13:29:14 -070090import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070091import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070092import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070093import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080094import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070095import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070096import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070097import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070098import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -070099import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700100import android.app.Notification;
101import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700102import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700103import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700104import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700105import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700106import android.content.Intent;
107import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700108import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700109import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700110import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700111import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700112import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700113import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.net.ConnectivityManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700115import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700116import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700118import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700119import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import android.net.LinkProperties;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700121import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700122import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600123import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700124import android.net.NetworkQuotaInfo;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700125import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700126import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600127import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700128import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700129import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700130import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700131import android.os.Environment;
132import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700133import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700134import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700135import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700136import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700137import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700138import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700140import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600141import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800142import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700143import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700144import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600145import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700146import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700147import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600148import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700149import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700150import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700151import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700152import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100153import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700154import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600155import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800156import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600157import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700158import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400159import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700160import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700161import android.util.ArrayMap;
162import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700163import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700164import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700165import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700166import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600167import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700168import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600169import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700170import android.util.SparseBooleanArray;
171import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700172import android.util.TrustedTime;
173import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700174
Jeff Sharkey497e4432011-06-14 17:27:29 -0700175import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700176import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800177import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400178import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500179import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700180import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800181import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600182import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700183import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700184import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600185import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700186import com.android.server.DeviceIdleController;
187import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700188import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700189import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800190import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800191import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600192
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600193import libcore.io.IoUtils;
194
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700195import com.google.android.collect.Lists;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700196
197import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700198import org.xmlpull.v1.XmlSerializer;
199
200import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700201import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700202import java.io.FileInputStream;
203import java.io.FileNotFoundException;
204import java.io.FileOutputStream;
205import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700206import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700207import java.lang.annotation.Retention;
208import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100209import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600210import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600211import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700212import java.util.ArrayList;
213import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700214import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600215import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400216import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800217import java.util.concurrent.CountDownLatch;
218import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700219
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700220/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700221 * Service that maintains low-level network policy rules, using
222 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700223 * <p>
224 * Derives active rules by combining a given policy with other system status,
225 * and delivers to listeners, such as {@link ConnectivityManager}, for
226 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700227 *
228 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000229 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700230 * <ul>
231 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
232 * rules).
233 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
234 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000235 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
236 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700237 * </ul>
238 *
239 * <p>
240 * As such, methods that require synchronization have the following prefixes:
241 * <ul>
242 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
243 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000244 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
245 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700246 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700247 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700248public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800249 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900250 private static final boolean LOGD = false;
251 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700252
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700253 private static final int VERSION_INIT = 1;
254 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700255 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800256 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800257 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800258 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700259 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700260 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700261 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700262 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600263 private static final int VERSION_ADDED_CYCLE = 11;
264 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700265
Sudheer Shankae7361852017-03-07 11:51:46 -0800266 /**
267 * Max items written to {@link #ProcStateSeqHistory}.
268 */
269 @VisibleForTesting
270 public static final int MAX_PROC_STATE_SEQ_HISTORY =
271 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
272
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800273 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400274 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800275 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400276 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800277 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400278 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700279
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700280 private static final String TAG_POLICY_LIST = "policy-list";
281 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600282 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700284 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800285 private static final String TAG_WHITELIST = "whitelist";
286 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800287 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700288
289 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700290 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
292 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700293 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600294 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
295 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
296 private static final String ATTR_CYCLE_START = "cycleStart";
297 private static final String ATTR_CYCLE_END = "cycleEnd";
298 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700299 private static final String ATTR_WARNING_BYTES = "warningBytes";
300 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700301 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800302 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
303 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800304 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700305 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700306 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700307 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700308 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600309 private static final String ATTR_SUB_ID = "subId";
310 private static final String ATTR_TITLE = "title";
311 private static final String ATTR_SUMMARY = "summary";
312 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
313 private static final String ATTR_USAGE_BYTES = "usageBytes";
314 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600315 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700316
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800317 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800318 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800319 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800320 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700321
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700322 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
323
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700324 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700325 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800326 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800327 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700328 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700329 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
330 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700331 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Lemebc853dd2016-09-08 13:26:55 -0700332 private static final int MSG_SET_FIREWALL_RULES = 14;
Felipe Leme03e95e22016-09-09 09:25:31 -0700333 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700334
Makoto Onuki8e777332017-03-28 11:25:47 -0700335 private static final int UID_MSG_STATE_CHANGED = 100;
336 private static final int UID_MSG_GONE = 101;
337
Jeff Sharkey75279902011-05-24 18:39:45 -0700338 private final Context mContext;
339 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700340 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700341 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700342 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700343 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700344 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700345 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700346
347 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700348 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700349 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700350 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800351 @GuardedBy("mUidRulesFirstLock")
352 private PowerSaveState mRestrictBackgroundPowerState;
353
354 // Store the status of restrict background before turning on battery saver.
355 // Used to restore mRestrictBackground when battery saver is turned off.
356 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700357
Felipe Lemef0823852016-06-08 13:43:08 -0700358 // See main javadoc for instructions on how to use these locks.
359 final Object mUidRulesFirstLock = new Object();
360 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700361
Felipe Lemef0823852016-06-08 13:43:08 -0700362 @GuardedBy("allLocks") volatile boolean mSystemReady;
363
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
365 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
366 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800367 // Store whether user flipped restrict background in battery saver mode
368 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700369
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700370 private final boolean mSuppressDefaultPolicy;
371
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700372 /** Defined network policies. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800373 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700374 /** Currently active network rules for ifaces. */
Jeff Sharkey32566012014-12-02 18:30:14 -0800375 final ArrayMap<NetworkPolicy, String[]> mNetworkRules = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700376
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600377 /** Map from subId to subscription plans. */
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600378 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600379 /** Map from subId to package name that owns subscription plans. */
380 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600381
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700382 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700383 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700384 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700385 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700386
Felipe Lemef0823852016-06-08 13:43:08 -0700387 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700388 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700389 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700390 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700391 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800392 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700393
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700394 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700395 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700396 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
397
Jeff Sharkey32566012014-12-02 18:30:14 -0800398 /**
399 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700400 * in power save mode, except device idle (doze) still applies.
401 * TODO: An int array might be sufficient
402 */
Felipe Lemef0823852016-06-08 13:43:08 -0700403 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700404 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
405
406 /**
407 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800408 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700409 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800410 */
Felipe Lemef0823852016-06-08 13:43:08 -0700411 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700412 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700413
Felipe Lemef0823852016-06-08 13:43:08 -0700414 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700415 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
416
Felipe Lemeb85a6372016-01-14 16:16:16 -0800417 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800418 * UIDs that have been initially white-listed by system to avoid restricted background.
419 */
Felipe Lemef0823852016-06-08 13:43:08 -0700420 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800421 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
422 new SparseBooleanArray();
423
424 /**
425 * UIDs that have been initially white-listed by system to avoid restricted background,
426 * but later revoked by user.
427 */
Felipe Lemef0823852016-06-08 13:43:08 -0700428 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800429 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
430 new SparseBooleanArray();
431
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700432 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700433 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800434 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700435 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700436 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800437 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700438
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700439 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700440 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400441 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700442
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700443 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700444 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800445 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700446
Jeff Sharkey32566012014-12-02 18:30:14 -0800447 private final RemoteCallbackList<INetworkPolicyListener>
448 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700449
Dianne Hackborn497175b2014-07-01 12:56:08 -0700450 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700451 @VisibleForTesting
452 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700453
454 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700455
Felipe Lemef0823852016-06-08 13:43:08 -0700456 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700457 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700458
Svet Ganov16a16892015-04-16 10:32:04 -0700459 private final AppOpsManager mAppOps;
460
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800461 private final IPackageManager mIPm;
462
Sudheer Shankae7361852017-03-07 11:51:46 -0800463 private ActivityManagerInternal mActivityManagerInternal;
464
465 /**
466 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
467 * the uid and procStateSeq will be written to this and will be printed as part of dump.
468 */
469 @VisibleForTesting
470 public ProcStateSeqHistory mObservedHistory
471 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800472
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700473 // TODO: keep whitelist of system-critical services that should never have
474 // rules enforced, such as system, phone, and radio UIDs.
475
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700476 // TODO: migrate notifications to SystemUI
477
Jeff Sharkey75279902011-05-24 18:39:45 -0700478 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700479 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
480 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700481 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
482 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700483 }
484
485 private static File getSystemDir() {
486 return new File(Environment.getDataDirectory(), "system");
487 }
488
489 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700490 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700491 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700492 mContext = checkNotNull(context, "missing context");
493 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700494 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700495 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700496 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700497 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700498 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700499 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700500 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700501 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700502
Amith Yamasani450a16b2013-09-18 16:28:50 -0700503 HandlerThread thread = new HandlerThread(TAG);
504 thread.start();
505 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700506
Makoto Onuki8e777332017-03-28 11:25:47 -0700507 // We create another thread for the UID events, which are more time-critical.
508 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
509 /*allowIo=*/ false);
510 mUidEventThread.start();
511 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
512
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700513 mSuppressDefaultPolicy = suppressDefaultPolicy;
514
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700515 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700516
517 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800518
Felipe Lemed17fda42016-04-29 11:12:45 -0700519 // Expose private service for system components to use.
520 LocalServices.addService(NetworkPolicyManagerInternal.class,
521 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700522 }
523
524 public void bindConnectivityManager(IConnectivityManager connManager) {
525 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700526 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700527
Jeff Sharkey497e4432011-06-14 17:27:29 -0700528 public void bindNotificationManager(INotificationManager notifManager) {
529 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
530 }
531
Felipe Lemef0823852016-06-08 13:43:08 -0700532 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700533 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700534 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
535 mPowerSaveWhitelistExceptIdleAppIds.clear();
536 if (whitelist != null) {
537 for (int uid : whitelist) {
538 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
539 }
540 }
541 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700542 mPowerSaveWhitelistAppIds.clear();
543 if (whitelist != null) {
544 for (int uid : whitelist) {
545 mPowerSaveWhitelistAppIds.put(uid, true);
546 }
547 }
548 } catch (RemoteException e) {
549 }
550 }
551
Felipe Lemea9505cc2016-02-26 10:28:41 -0800552 /**
553 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
554 * revoke the whitelist.
555 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700556 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800557 */
Felipe Lemef0823852016-06-08 13:43:08 -0700558 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 final List<UserInfo> users = mUserManager.getUsers();
560 final int numberUsers = users.size();
561
Felipe Lemea110eec2016-04-29 09:58:06 -0700562 boolean changed = false;
563 for (int i = 0; i < numberUsers; i++) {
564 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700565 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700566 }
567 return changed;
568 }
569
Felipe Lemef0823852016-06-08 13:43:08 -0700570 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700571 final SystemConfig sysConfig = SystemConfig.getInstance();
572 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800573 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
574 boolean changed = false;
575 for (int i = 0; i < allowDataUsage.size(); i++) {
576 final String pkg = allowDataUsage.valueAt(i);
577 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700578 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
579 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800580 final ApplicationInfo app;
581 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700582 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800583 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700584 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
585 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800586 continue;
587 }
588 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700589 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
590 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800591 continue;
592 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700593 final int uid = UserHandle.getUid(userId, app.uid);
594 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
595 if (LOGD)
596 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
597 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800598 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700599 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700600 if (LOGD)
601 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
602 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700603 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700604 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800605 }
606 }
607 return changed;
608 }
609
Felipe Lemef0823852016-06-08 13:43:08 -0700610 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700611 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700612 // Clear the states of the current whitelist
613 final int N = mPowerSaveTempWhitelistAppIds.size();
614 for (int i = 0; i < N; i++) {
615 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
616 }
617 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700618 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700619 if (whitelist != null) {
620 for (int uid : whitelist) {
621 mPowerSaveTempWhitelistAppIds.put(uid, true);
622 }
623 }
624 } catch (RemoteException e) {
625 }
626 }
627
Amith Yamasani06f08062015-06-12 13:23:33 -0700628 /**
629 * Remove unnecessary entries in the temp whitelist
630 */
Felipe Lemef0823852016-06-08 13:43:08 -0700631 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700632 final int N = mPowerSaveTempWhitelistAppIds.size();
633 for (int i = N - 1; i >= 0; i--) {
634 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
635 mPowerSaveTempWhitelistAppIds.removeAt(i);
636 }
637 }
638 }
639
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800640 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700641 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800642 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700643 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800644 // Boost thread's priority during system server init
645 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700646 if (!isBandwidthControlEnabled()) {
647 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
648 return;
649 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700650
Felipe Leme873a83a2016-09-07 11:34:10 -0700651 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700652
Felipe Leme873a83a2016-09-07 11:34:10 -0700653 synchronized (mUidRulesFirstLock) {
654 synchronized (mNetworkPoliciesSecondLock) {
655 updatePowerSaveWhitelistUL();
656 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
657 mPowerManagerInternal.registerLowPowerModeObserver(
658 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800659 @Override
660 public int getServiceType() {
661 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700662 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800663
664 @Override
665 public void onLowPowerModeChanged(PowerSaveState result) {
666 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800667 if (LOGD) {
668 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
669 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800670 synchronized (mUidRulesFirstLock) {
671 if (mRestrictPower != enabled) {
672 mRestrictPower = enabled;
673 updateRulesForRestrictPowerUL();
674 }
675 }
676 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800677 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800678 mRestrictPower = mPowerManagerInternal.getLowPowerState(
679 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700680
681 mSystemReady = true;
682
683 // read policy from disk
684 readPolicyAL();
685
jackqdyulei29c82ab2017-03-10 14:09:16 -0800686 // Update the restrictBackground if battery saver is turned on
687 mRestrictBackgroundBeforeBsm = mRestrictBackground;
688 mRestrictBackgroundPowerState = mPowerManagerInternal
689 .getLowPowerState(ServiceType.DATA_SAVER);
690 final boolean localRestrictBackground =
691 mRestrictBackgroundPowerState.batterySaverEnabled;
692 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
693 mRestrictBackground = localRestrictBackground;
694 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
695 mRestrictBackground ? 1 : 0, 0).sendToTarget();
696 }
697 mPowerManagerInternal.registerLowPowerModeObserver(
698 new PowerManagerInternal.LowPowerModeListener() {
699 @Override
700 public int getServiceType() {
701 return ServiceType.DATA_SAVER;
702 }
703
704 @Override
705 public void onLowPowerModeChanged(PowerSaveState result) {
706 synchronized (mUidRulesFirstLock) {
707 updateRestrictBackgroundByLowPowerModeUL(result);
708 }
709 }
710 });
711
Felipe Leme873a83a2016-09-07 11:34:10 -0700712 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
713 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700714 }
Felipe Lemef0823852016-06-08 13:43:08 -0700715
Felipe Leme873a83a2016-09-07 11:34:10 -0700716 setRestrictBackgroundUL(mRestrictBackground);
717 updateRulesForGlobalChangeAL(false);
718 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700719 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800720 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700721
Sudheer Shankae7361852017-03-07 11:51:46 -0800722 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 try {
724 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000725 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800726 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700727 mNetworkManager.registerObserver(mAlertObserver);
728 } catch (RemoteException e) {
729 // ignored; both services live in system_server
730 }
731
732 // listen for changes to power save whitelist
733 final IntentFilter whitelistFilter = new IntentFilter(
734 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
735 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
736
737 DeviceIdleController.LocalService deviceIdleService
738 = LocalServices.getService(DeviceIdleController.LocalService.class);
739 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
740
741 // watch for network interfaces to be claimed
742 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
743 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
744
745 // listen for package changes to update policy
746 final IntentFilter packageFilter = new IntentFilter();
747 packageFilter.addAction(ACTION_PACKAGE_ADDED);
748 packageFilter.addDataScheme("package");
749 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
750
751 // listen for UID changes to update policy
752 mContext.registerReceiver(
753 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
754
755 // listen for user changes to update policy
756 final IntentFilter userFilter = new IntentFilter();
757 userFilter.addAction(ACTION_USER_ADDED);
758 userFilter.addAction(ACTION_USER_REMOVED);
759 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
760
761 // listen for stats update events
762 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
763 mContext.registerReceiver(
764 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
765
766 // listen for restrict background changes from notifications
767 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
768 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
769
770 // listen for snooze warning from notifications
771 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
772 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
773 MANAGE_NETWORK_POLICY, mHandler);
774
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600775 // listen for configured wifi networks to be loaded
776 final IntentFilter wifiFilter =
777 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
778 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700779
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700780 // listen for carrier config changes to update data cycle information
781 final IntentFilter carrierConfigFilter = new IntentFilter(
782 ACTION_CARRIER_CONFIG_CHANGED);
783 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
784
Felipe Leme873a83a2016-09-07 11:34:10 -0700785 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800786 // tell systemReady() that the service has been initialized
787 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700788 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800789 // Restore the default priority after init is done
790 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700791 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700792 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700793 }
794
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800795 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
796 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
797 mHandler.post(() -> initService(initCompleteSignal));
798 return initCompleteSignal;
799 }
800
801 public void systemReady(CountDownLatch initCompleteSignal) {
802 // wait for initService to complete
803 try {
804 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
805 throw new IllegalStateException("Service " + TAG +" init timeout");
806 }
807 } catch (InterruptedException e) {
808 Thread.currentThread().interrupt();
809 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
810 }
811 }
812
Sudheer Shankac9d94072017-02-22 22:13:55 +0000813 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700814 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700815 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
816 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700817 }
818
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700819 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700820 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700821 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700822
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700823 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700824 }
825
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700826 @Override public void onUidIdle(int uid, boolean disabled) {
827 }
828
829 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700830 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700831 };
832
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700833 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700834 @Override
835 public void onReceive(Context context, Intent intent) {
836 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700837 synchronized (mUidRulesFirstLock) {
838 updatePowerSaveWhitelistUL();
839 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700840 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700841 }
842 }
843 };
844
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700845 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
846 @Override
847 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700848 synchronized (mUidRulesFirstLock) {
849 updatePowerSaveTempWhitelistUL();
850 updateRulesForTempWhitelistChangeUL();
851 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700852 }
853 }
854 };
855
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700856 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700857 @Override
858 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700859 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700860
861 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700862 final int uid = intent.getIntExtra(EXTRA_UID, -1);
863 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700864
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700865 if (ACTION_PACKAGE_ADDED.equals(action)) {
866 // update rules for UID, since it might be subject to
867 // global background data policy
868 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700869 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700870 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700871 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700872 }
873 }
874 };
875
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700876 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700877 @Override
878 public void onReceive(Context context, Intent intent) {
879 // on background handler thread, and UID_REMOVED is protected
880
881 final int uid = intent.getIntExtra(EXTRA_UID, -1);
882 if (uid == -1) return;
883
884 // remove any policy and update rules to clean up
885 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700886 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700887 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700888 synchronized (mNetworkPoliciesSecondLock) {
889 writePolicyAL();
890 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700891 }
892 }
893 };
894
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700895 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700896 @Override
897 public void onReceive(Context context, Intent intent) {
898 // on background handler thread, and USER_ADDED and USER_REMOVED
899 // broadcasts are protected
900
901 final String action = intent.getAction();
902 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
903 if (userId == -1) return;
904
Amith Yamasani15e472352015-04-24 19:06:07 -0700905 switch (action) {
906 case ACTION_USER_REMOVED:
907 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700908 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800909 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700910 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700911 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700912 if (action == ACTION_USER_ADDED) {
913 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700914 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700915 }
916 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700917 synchronized (mNetworkPoliciesSecondLock) {
918 updateRulesForGlobalChangeAL(true);
919 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700920 }
921 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700922 }
923 }
924 };
925
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700926 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700927 * Receiver that watches for {@link INetworkStatsService} updates, which we
928 * use to check against {@link NetworkPolicy#warningBytes}.
929 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700930 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700931 @Override
932 public void onReceive(Context context, Intent intent) {
933 // on background handler thread, and verified
934 // READ_NETWORK_USAGE_HISTORY permission above.
935
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800936 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700937 synchronized (mNetworkPoliciesSecondLock) {
938 updateNetworkEnabledNL();
939 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700940 }
941 }
942 };
943
944 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700945 * Receiver that watches for {@link Notification} control of
946 * {@link #mRestrictBackground}.
947 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700948 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700949 @Override
950 public void onReceive(Context context, Intent intent) {
951 // on background handler thread, and verified MANAGE_NETWORK_POLICY
952 // permission above.
953
954 setRestrictBackground(false);
955 }
956 };
957
958 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800959 * Receiver that watches for {@link Notification} control of
960 * {@link NetworkPolicy#lastWarningSnooze}.
961 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700962 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800963 @Override
964 public void onReceive(Context context, Intent intent) {
965 // on background handler thread, and verified MANAGE_NETWORK_POLICY
966 // permission above.
967
968 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
969 performSnooze(template, TYPE_WARNING);
970 }
971 };
972
973 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600974 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
975 * we can perform upgrade logic.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700976 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600977 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700978 @Override
979 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900980 synchronized (mUidRulesFirstLock) {
981 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600982 upgradeWifiMeteredOverrideAL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700983 }
984 }
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600985 // Only need to perform upgrade logic once
986 mContext.unregisterReceiver(this);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700987 }
988 };
989
990 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700991 * Observer that watches for {@link INetworkManagementService} alerts.
992 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700993 final private INetworkManagementEventObserver mAlertObserver
994 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700995 @Override
996 public void limitReached(String limitName, String iface) {
997 // only someone like NMS should be calling us
998 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
999
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001000 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1001 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001002 }
1003 }
1004 };
1005
1006 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001007 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1008 * to show visible notifications as needed.
1009 */
Felipe Lemef0823852016-06-08 13:43:08 -07001010 void updateNotificationsNL() {
1011 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001012
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001013 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001014 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001015 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001016
1017 // TODO: when switching to kernel notifications, compute next future
1018 // cycle boundary to recompute notifications.
1019
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001020 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001021 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1022 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001023 // ignore policies that aren't relevant to user
1024 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001025 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001026
Jeff Sharkey53313d72017-07-13 16:47:32 -06001027 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1028 .cycleIterator(policy).next();
1029 final long start = cycle.first.toInstant().toEpochMilli();
1030 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001031 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001032
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001033 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001034 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001035 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1036 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001037 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001038 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001039 }
1040
Jeff Sharkey497e4432011-06-14 17:27:29 -07001041 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001042 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001044 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001045 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001046 }
1047 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001048 }
1049
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001050 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001051 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001052 final NotificationId notificationId = beforeNotifs.valueAt(i);
1053 if (!mActiveNotifs.contains(notificationId)) {
1054 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001055 }
1056 }
1057 }
1058
1059 /**
1060 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001061 * current device state, such as when
1062 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1063 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001064 */
1065 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001066 if (template.isMatchRuleMobile()) {
1067 final TelephonyManager tele = TelephonyManager.from(mContext);
1068 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001069
Jeff Sharkey32566012014-12-02 18:30:14 -08001070 // Mobile template is relevant when any active subscriber matches
1071 final int[] subIds = sub.getActiveSubscriptionIdList();
1072 for (int subId : subIds) {
1073 final String subscriberId = tele.getSubscriberId(subId);
1074 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001075 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001076 if (template.matches(probeIdent)) {
1077 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001078 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001079 }
1080 return false;
1081 } else {
1082 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001083 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001084 }
1085
1086 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001087 * Notify that given {@link NetworkTemplate} is over
1088 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1089 */
Felipe Lemef0823852016-06-08 13:43:08 -07001090 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001091 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001092 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001093 mOverLimitNotified.add(template);
1094 }
1095 }
1096
Felipe Lemef0823852016-06-08 13:43:08 -07001097 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001098 mOverLimitNotified.remove(template);
1099 }
1100
1101 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001102 * Show notification for combined {@link NetworkPolicy} and specific type,
1103 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1104 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001105 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001106 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001107 final Notification.Builder builder =
1108 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001109 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001110 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001111 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001112 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001113
1114 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001115 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 switch (type) {
1117 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001118 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001119 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001120
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001121 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001122 builder.setTicker(title);
1123 builder.setContentTitle(title);
1124 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001125 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001126 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001127
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001128 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1129 builder.setDeleteIntent(PendingIntent.getBroadcast(
1130 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1131
Wei Liu546cb772016-07-21 16:19:01 -07001132 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001133 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001134 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1135
Jeff Sharkey497e4432011-06-14 17:27:29 -07001136 break;
1137 }
1138 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001139 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001140
1141 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001142 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001143 switch (policy.template.getMatchRule()) {
1144 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001145 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001146 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001147 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001148 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001149 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001150 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001151 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001153 case MATCH_WIFI:
1154 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001155 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001156 break;
1157 default:
1158 title = null;
1159 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001160 }
1161
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001162 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001163 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001164 builder.setTicker(title);
1165 builder.setContentTitle(title);
1166 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001167
Wei Liu546cb772016-07-21 16:19:01 -07001168 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001169 builder.setContentIntent(PendingIntent.getActivity(
1170 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1171 break;
1172 }
1173 case TYPE_LIMIT_SNOOZED: {
1174 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001175 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001176 Formatter.formatFileSize(mContext, overBytes));
1177
1178 final CharSequence title;
1179 switch (policy.template.getMatchRule()) {
1180 case MATCH_MOBILE_3G_LOWER:
1181 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1182 break;
1183 case MATCH_MOBILE_4G:
1184 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1185 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001186 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001187 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1188 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001189 case MATCH_WIFI:
1190 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1191 break;
1192 default:
1193 title = null;
1194 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001195 }
1196
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001197 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001198 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001199 builder.setTicker(title);
1200 builder.setContentTitle(title);
1201 builder.setContentText(body);
1202
Wei Liu546cb772016-07-21 16:19:01 -07001203 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001204 builder.setContentIntent(PendingIntent.getActivity(
1205 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001206 break;
1207 }
1208 }
1209
1210 // TODO: move to NotificationManager once we can mock it
1211 try {
1212 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001213 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001214 builder.setStyle(new Notification.BigTextStyle()
1215 .bigText(body));
1216 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001217 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001218 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001219 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001220 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001221 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001222 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001223 }
1224 }
1225
Chris Wren193ae6b2017-03-31 15:17:11 -04001226 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001227 // TODO: move to NotificationManager once we can mock it
1228 try {
1229 final String packageName = mContext.getPackageName();
1230 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001231 packageName, notificationId.getTag(), notificationId.getId(),
1232 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001233 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001234 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001235 }
1236 }
1237
1238 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001239 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001240 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001241 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001242 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001243 @Override
1244 public void onReceive(Context context, Intent intent) {
1245 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1246 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001247
1248 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001249 synchronized (mUidRulesFirstLock) {
1250 synchronized (mNetworkPoliciesSecondLock) {
1251 ensureActiveMobilePolicyAL();
1252 normalizePoliciesNL();
1253 updateNetworkEnabledNL();
1254 updateNetworkRulesNL();
1255 updateNotificationsNL();
1256 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001257 }
1258 }
1259 };
1260
1261 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001262 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1263 * if necessary.
1264 *
1265 * @param subId that has its associated NetworkPolicy updated if necessary
1266 * @return if any policies were updated
1267 */
1268 private boolean maybeUpdateMobilePolicyCycleNL(int subId) {
1269 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleNL()");
1270 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1271
1272 if (config == null) {
1273 return false;
1274 }
1275
1276 boolean policyUpdated = false;
1277 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1278
1279 // find and update the mobile NetworkPolicy for this subscriber id
1280 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1281 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1282 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1283 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1284 if (template.matches(probeIdent)) {
1285 NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1286
1287 // only update the policy if the user didn't change any of the defaults.
1288 if (!policy.inferred) {
1289 // TODO: inferred could be split, so that if a user changes their data limit or
1290 // warning, it doesn't prevent their cycle date from being updated.
1291 if (LOGD) Slog.v(TAG, "Didn't update NetworkPolicy because policy.inferred");
1292 continue;
1293 }
1294
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001295 final int currentCycleDay;
1296 if (policy.cycleRule.isMonthly()) {
1297 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1298 } else {
1299 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1300 }
1301
1302 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001303 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1304 policy.warningBytes);
1305 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1306 policy.limitBytes);
1307
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001308 if (currentCycleDay == cycleDay &&
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001309 policy.warningBytes == warningBytes &&
1310 policy.limitBytes == limitBytes) {
1311 continue;
1312 }
1313
1314 policyUpdated = true;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001315 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001316 policy.warningBytes = warningBytes;
1317 policy.limitBytes = limitBytes;
1318
1319 if (LOGD) {
1320 Slog.d(TAG, "Updated NetworkPolicy " + policy + " which matches subscriber "
1321 + NetworkIdentity.scrubSubscriberId(subscriberId)
1322 + " from CarrierConfigManager");
1323 }
1324 }
1325 }
1326
1327 return policyUpdated;
1328 }
1329
1330 /**
1331 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1332 *
1333 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1334 * to do so, it returns the fallback value.
1335 *
1336 * @param config The CarrierConfig to read the value from.
1337 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1338 * @return cycleDay to use in the mobile NetworkPolicy.
1339 */
1340 @VisibleForTesting
1341 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1342 int fallbackCycleDay) {
1343 if (config == null) {
1344 return fallbackCycleDay;
1345 }
1346 int cycleDay =
1347 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1348 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1349 return fallbackCycleDay;
1350 }
1351 // validate cycleDay value
1352 final Calendar cal = Calendar.getInstance();
1353 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1354 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1355 Slog.e(TAG, "Invalid date in "
1356 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1357 return fallbackCycleDay;
1358 }
1359 return cycleDay;
1360 }
1361
1362 /**
1363 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1364 *
1365 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1366 * to do so, it returns the fallback value.
1367 *
1368 * @param config The CarrierConfig to read the value from.
1369 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1370 * @return warningBytes to use in the mobile NetworkPolicy.
1371 */
1372 @VisibleForTesting
1373 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1374 long fallbackWarningBytes) {
1375 if (config == null) {
1376 return fallbackWarningBytes;
1377 }
1378 long warningBytes =
1379 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1380
1381 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1382 return WARNING_DISABLED;
1383 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1384 return getPlatformDefaultWarningBytes();
1385 } else if (warningBytes < 0) {
1386 Slog.e(TAG, "Invalid value in "
1387 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1388 + "non-negative value but got: " + warningBytes);
1389 return fallbackWarningBytes;
1390 }
1391
1392 return warningBytes;
1393 }
1394
1395 /**
1396 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1397 *
1398 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1399 * to do so, it returns the fallback value.
1400 *
1401 * @param config The CarrierConfig to read the value from.
1402 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1403 * @return limitBytes to use in the mobile NetworkPolicy.
1404 */
1405 @VisibleForTesting
1406 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1407 long fallbackLimitBytes) {
1408 if (config == null) {
1409 return fallbackLimitBytes;
1410 }
1411 long limitBytes =
1412 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1413
1414 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1415 return LIMIT_DISABLED;
1416 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1417 return getPlatformDefaultLimitBytes();
1418 } else if (limitBytes < 0) {
1419 Slog.e(TAG, "Invalid value in "
1420 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1421 + "non-negative value but got: " + limitBytes);
1422 return fallbackLimitBytes;
1423 }
1424 return limitBytes;
1425 }
1426
1427 /**
1428 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1429 */
1430 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1431 @Override
1432 public void onReceive(Context context, Intent intent) {
1433 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1434 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1435
1436 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1437 return;
1438 }
1439 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1440 final TelephonyManager tele = TelephonyManager.from(mContext);
1441 final String subscriberId = tele.getSubscriberId(subId);
1442
1443 maybeRefreshTrustedTime();
1444 synchronized (mUidRulesFirstLock) {
1445 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001446 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001447 if (added) return;
1448 final boolean updated = maybeUpdateMobilePolicyCycleNL(subId);
1449 if (!updated) return;
1450 // update network and notification rules, as the data cycle changed and it's
1451 // possible that we should be triggering warnings/limits now
1452 handleNetworkPoliciesUpdateAL(true);
1453 }
1454 }
1455 }
1456 };
1457
1458 /**
1459 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1460 * one has been updated.
1461 *
1462 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1463 * update.
1464 */
1465 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1466 if (shouldNormalizePolicies) {
1467 normalizePoliciesNL();
1468 }
1469 updateNetworkEnabledNL();
1470 updateNetworkRulesNL();
1471 updateNotificationsNL();
1472 writePolicyAL();
1473 }
1474
1475 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001476 * Proactively control network data connections when they exceed
1477 * {@link NetworkPolicy#limitBytes}.
1478 */
Felipe Lemef0823852016-06-08 13:43:08 -07001479 void updateNetworkEnabledNL() {
1480 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001481
1482 // TODO: reset any policy-disabled networks when any policy is removed
1483 // completely, which is currently rare case.
1484
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001485 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1486 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001487 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001488 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001489 setNetworkTemplateEnabled(policy.template, true);
1490 continue;
1491 }
1492
Jeff Sharkey53313d72017-07-13 16:47:32 -06001493 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1494 .cycleIterator(policy).next();
1495 final long start = cycle.first.toInstant().toEpochMilli();
1496 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001497 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001498
1499 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001500 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1501 && policy.lastLimitSnooze < start;
1502 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001503
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001504 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001505 }
1506 }
1507
1508 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001509 * Proactively disable networks that match the given
1510 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001511 */
1512 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001513 // TODO: reach into ConnectivityManager to proactively disable bringing
1514 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001515
1516 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1517 // If mobile data usage hits the limit or if the user resumes the data, we need to
1518 // notify telephony.
1519 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1520 final TelephonyManager tm = TelephonyManager.from(mContext);
1521
1522 final int[] subIds = sm.getActiveSubscriptionIdList();
1523 for (int subId : subIds) {
1524 final String subscriberId = tm.getSubscriberId(subId);
1525 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1526 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1527 // Template is matched when subscriber id matches.
1528 if (template.matches(probeIdent)) {
1529 tm.setPolicyDataEnabled(enabled, subId);
1530 }
1531 }
1532 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001533 }
1534
1535 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001536 * Examine all connected {@link NetworkState}, looking for
1537 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1538 * remaining quota based on usage cycle and historical stats.
1539 */
Felipe Lemef0823852016-06-08 13:43:08 -07001540 void updateNetworkRulesNL() {
1541 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542
1543 final NetworkState[] states;
1544 try {
1545 states = mConnManager.getAllNetworkState();
1546 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001547 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548 return;
1549 }
1550
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001551 // First, generate identities of all connected networks so we can
1552 // quickly compare them against all defined policies below.
1553 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001554 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001555 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001556 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001557 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001558
1559 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001560 if (baseIface != null) {
1561 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001562 }
1563
1564 // Stacked interfaces are considered to have same identity as
1565 // their parent network.
1566 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1567 for (LinkProperties stackedLink : stackedLinks) {
1568 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001569 if (stackedIface != null) {
1570 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001571 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001572 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001573 }
1574 }
1575
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001576 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001577 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001578 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001579 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001580 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001581
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001582 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001583 for (int j = connIdents.size() - 1; j >= 0; j--) {
1584 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1585 if (policy.template.matches(ident.second)) {
1586 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 }
1588 }
1589
1590 if (ifaceList.size() > 0) {
1591 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001592 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001593 }
1594 }
1595
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001596 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001597 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001598
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001599 // apply each policy that we found ifaces for; compute remaining data
1600 // based on current cycle and historical stats, and push to kernel.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001601 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1602 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1603 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001604
Jeff Sharkey53313d72017-07-13 16:47:32 -06001605 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1606 .cycleIterator(policy).next();
1607 final long start = cycle.first.toInstant().toEpochMilli();
1608 final long end = cycle.second.toInstant().toEpochMilli();
1609 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001610
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001611 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001612 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001613 }
1614
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001615 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001616 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001617 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001618 final long quotaBytes;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001619 if (!hasLimit) {
1620 // metered network, but no policy limit; we still need to
1621 // restrict apps, so push really high quota.
1622 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001623 } else if (policy.lastLimitSnooze >= start) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001624 // snoozing past quota, but we still need to restrict apps,
1625 // so push really high quota.
1626 quotaBytes = Long.MAX_VALUE;
1627 } else {
1628 // remaining "quota" bytes are based on total usage in
1629 // current cycle. kernel doesn't like 0-byte rules, so we
1630 // set 1-byte quota and disable the radio later.
1631 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1632 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001633
1634 if (ifaces.length > 1) {
1635 // TODO: switch to shared quota once NMS supports
1636 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001637 }
1638
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001639 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001640 // long quotaBytes split up into two ints to fit in message
1641 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1642 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1643 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001644 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001645 }
1646 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001647
1648 // keep track of lowest warning or limit of active policies
1649 if (hasWarning && policy.warningBytes < lowestRule) {
1650 lowestRule = policy.warningBytes;
1651 }
1652 if (hasLimit && policy.limitBytes < lowestRule) {
1653 lowestRule = policy.limitBytes;
1654 }
1655 }
1656
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001657 for (int i = connIfaces.size()-1; i >= 0; i--) {
1658 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001659 // long quotaBytes split up into two ints to fit in message
1660 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1661 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1662 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001663 newMeteredIfaces.add(iface);
1664 }
1665
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001666 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001667
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001668 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001669 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1670 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001671 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001672 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1673 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001674 }
1675 }
1676 mMeteredIfaces = newMeteredIfaces;
1677
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001678 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001679 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001680 }
1681
1682 /**
1683 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1684 * have at least a default mobile policy defined.
1685 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001686 private void ensureActiveMobilePolicyAL() {
1687 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001688 if (mSuppressDefaultPolicy) return;
1689
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001690 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001691 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001692
Jeff Sharkey32566012014-12-02 18:30:14 -08001693 final int[] subIds = sub.getActiveSubscriptionIdList();
1694 for (int subId : subIds) {
1695 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001696 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001697 }
1698 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001699
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001700 /**
1701 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1702 * have at least a default mobile policy defined.
1703 *
1704 * @param subId to build a default policy for
1705 * @param subscriberId that we check for an existing policy
1706 * @return true if a mobile network policy was added, or false one already existed.
1707 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001708 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001709 // Poke around to see if we already have a policy
1710 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001711 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001712 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1713 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1714 if (template.matches(probeIdent)) {
1715 if (LOGD) {
1716 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1717 + NetworkIdentity.scrubSubscriberId(subscriberId));
1718 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001719 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001720 }
1721 }
1722
Jeff Sharkey32566012014-12-02 18:30:14 -08001723 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1724 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001725 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001726 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001727 return true;
1728 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001729
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001730 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001731 final int dataWarningConfig = mContext.getResources().getInteger(
1732 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001733 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001734 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001735 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001736 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001737 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001738 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001739
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001740 private long getPlatformDefaultLimitBytes() {
1741 return LIMIT_DISABLED;
1742 }
1743
1744 @VisibleForTesting
1745 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
1746 PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1747
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001748 final int cycleDay = getCycleDayFromCarrierConfig(config,
1749 ZonedDateTime.now().getDayOfMonth());
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001750 final long warningBytes = getWarningBytesFromCarrierConfig(config,
1751 getPlatformDefaultWarningBytes());
1752 final long limitBytes = getLimitBytesFromCarrierConfig(config,
1753 getPlatformDefaultLimitBytes());
1754
Jeff Sharkey32566012014-12-02 18:30:14 -08001755 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001756 final RecurrenceRule cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1757 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001758 warningBytes, limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1759 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001760 }
1761
Felipe Lemef0823852016-06-08 13:43:08 -07001762 private void readPolicyAL() {
1763 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001764
1765 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001766 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001767 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001768 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001769 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001770
1771 FileInputStream fis = null;
1772 try {
1773 fis = mPolicyFile.openRead();
1774 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001775 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001776
Felipe Leme46b451f2016-08-19 08:46:17 -07001777 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1778 // to skip UIDs that were explicitly blacklisted.
1779 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1780
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001781 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001782 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001783 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001784 while ((type = in.next()) != END_DOCUMENT) {
1785 final String tag = in.getName();
1786 if (type == START_TAG) {
1787 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001788 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001789 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001790 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1791 mRestrictBackground = readBooleanAttribute(
1792 in, ATTR_RESTRICT_BACKGROUND);
1793 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001794 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001795 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001796 if (mRestrictBackground != oldValue) {
1797 // Some early services may have read the default value,
1798 // so notify them that it's changed
1799 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1800 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1801 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001802
1803 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1804 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1805 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001806 final String networkId;
1807 if (version >= VERSION_ADDED_NETWORK_ID) {
1808 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1809 } else {
1810 networkId = null;
1811 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001812 final RecurrenceRule cycleRule;
1813 if (version >= VERSION_ADDED_CYCLE) {
1814 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1815 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1816 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1817 cycleRule = new RecurrenceRule(
1818 RecurrenceRule.convertZonedDateTime(start),
1819 RecurrenceRule.convertZonedDateTime(end),
1820 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001821 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001822 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1823 final String cycleTimezone;
1824 if (version >= VERSION_ADDED_TIMEZONE) {
1825 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1826 } else {
1827 cycleTimezone = "UTC";
1828 }
1829 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001830 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001831 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1832 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001833 final long lastLimitSnooze;
1834 if (version >= VERSION_SPLIT_SNOOZE) {
1835 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1836 } else if (version >= VERSION_ADDED_SNOOZE) {
1837 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001838 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001839 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001840 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001841 final boolean metered;
1842 if (version >= VERSION_ADDED_METERED) {
1843 metered = readBooleanAttribute(in, ATTR_METERED);
1844 } else {
1845 switch (networkTemplate) {
1846 case MATCH_MOBILE_3G_LOWER:
1847 case MATCH_MOBILE_4G:
1848 case MATCH_MOBILE_ALL:
1849 metered = true;
1850 break;
1851 default:
1852 metered = false;
1853 }
1854 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001855 final long lastWarningSnooze;
1856 if (version >= VERSION_SPLIT_SNOOZE) {
1857 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1858 } else {
1859 lastWarningSnooze = SNOOZE_NEVER;
1860 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001861 final boolean inferred;
1862 if (version >= VERSION_ADDED_INFERRED) {
1863 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1864 } else {
1865 inferred = false;
1866 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001867
Jeff Sharkey32566012014-12-02 18:30:14 -08001868 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1869 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001870 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001871 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1872 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001873 lastLimitSnooze, metered, inferred));
1874 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001875
1876 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1877 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1878 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1879 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1880 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1881 RecurrenceRule.convertZonedDateTime(start),
1882 RecurrenceRule.convertZonedDateTime(end),
1883 RecurrenceRule.convertPeriod(period));
1884 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1885 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1886
1887 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1888 SubscriptionPlan.BYTES_UNKNOWN);
1889 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1890 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1891 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1892 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1893 builder.setDataLimit(limitBytes, limitBehavior);
1894 }
1895
1896 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1897 SubscriptionPlan.BYTES_UNKNOWN);
1898 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1899 SubscriptionPlan.TIME_UNKNOWN);
1900 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1901 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1902 builder.setDataUsage(usageBytes, usageTime);
1903 }
1904
1905 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1906 final SubscriptionPlan plan = builder.build();
1907 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1908 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1909
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001910 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1911 mSubscriptionPlansOwner.put(subId, ownerPackage);
1912
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001913 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001914 final int uid = readIntAttribute(in, ATTR_UID);
1915 final int policy = readIntAttribute(in, ATTR_POLICY);
1916
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001917 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001918 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001919 } else {
1920 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1921 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001922 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001923 final int appId = readIntAttribute(in, ATTR_APP_ID);
1924 final int policy = readIntAttribute(in, ATTR_POLICY);
1925
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001926 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001927 // app policy is deprecated so this is only used in pre system user split.
1928 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001929 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001930 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001931 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001933 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001934 } else if (TAG_WHITELIST.equals(tag)) {
1935 insideWhitelist = true;
1936 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1937 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001938 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001939 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1940 final int uid = readIntAttribute(in, ATTR_UID);
1941 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001942 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001943 } else if (type == END_TAG) {
1944 if (TAG_WHITELIST.equals(tag)) {
1945 insideWhitelist = false;
1946 }
1947
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001948 }
1949 }
1950
Felipe Leme46b451f2016-08-19 08:46:17 -07001951 final int size = whitelistedRestrictBackground.size();
1952 for (int i = 0; i < size; i++) {
1953 final int uid = whitelistedRestrictBackground.keyAt(i);
1954 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1955 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1956 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1957 + " because its policy is " + uidPoliciesToString(policy));
1958 continue;
1959 }
1960 if (UserHandle.isApp(uid)) {
1961 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1962 if (LOGV)
1963 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1964 setUidPolicyUncheckedUL(uid, newPolicy, false);
1965 } else {
1966 Slog.w(TAG, "unable to update policy on UID " + uid);
1967 }
1968 }
1969
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001970 } catch (FileNotFoundException e) {
1971 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001972 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001973 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001974 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001975 } finally {
1976 IoUtils.closeQuietly(fis);
1977 }
1978 }
1979
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001980 /**
1981 * Upgrade legacy background data flags, notifying listeners of one last
1982 * change to always-true.
1983 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001984 private void upgradeDefaultBackgroundDataUL() {
1985 // This method is only called when we're unable to find the network policy flag, which
1986 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001987
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001988 // Seed from the default value configured for this device.
1989 mRestrictBackground = Settings.Global.getInt(
1990 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
1991
1992 // NOTE: We used to read the legacy setting here :
1993 //
1994 // final int legacyFlagValue = Settings.Secure.getInt(
1995 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
1996 //
1997 // This is no longer necessary because we will never upgrade directly from Gingerbread
1998 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
1999 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002000 }
2001
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002002 /**
2003 * Perform upgrade step of moving any user-defined meterness overrides over
2004 * into {@link WifiConfiguration}.
2005 */
2006 private void upgradeWifiMeteredOverrideAL() {
2007 boolean modified = false;
2008 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2009 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2010 for (int i = 0; i < mNetworkPolicy.size(); ) {
2011 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2012 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2013 && !policy.inferred) {
2014 mNetworkPolicy.removeAt(i);
2015 modified = true;
2016
2017 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2018 for (WifiConfiguration config : configs) {
2019 if (Objects.equals(resolveNetworkId(config), networkId)) {
2020 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2021 config.meteredOverride = policy.metered
2022 ? WifiConfiguration.METERED_OVERRIDE_METERED
2023 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2024 wm.updateNetwork(config);
2025 }
2026 }
2027 } else {
2028 i++;
2029 }
2030 }
2031 if (modified) {
2032 writePolicyAL();
2033 }
2034 }
2035
Felipe Lemef0823852016-06-08 13:43:08 -07002036 void writePolicyAL() {
2037 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002038
2039 FileOutputStream fos = null;
2040 try {
2041 fos = mPolicyFile.startWrite();
2042
2043 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002044 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002045 out.startDocument(null, true);
2046
2047 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002048 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002049 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002050
2051 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002052 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2053 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002054 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002055 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002056
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002057 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002058 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2059 final String subscriberId = template.getSubscriberId();
2060 if (subscriberId != null) {
2061 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002062 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002063 final String networkId = template.getNetworkId();
2064 if (networkId != null) {
2065 out.attribute(null, ATTR_NETWORK_ID, networkId);
2066 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002067 writeStringAttribute(out, ATTR_CYCLE_START,
2068 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2069 writeStringAttribute(out, ATTR_CYCLE_END,
2070 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2071 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2072 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002073 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2074 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002075 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2076 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002077 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002078 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002079 out.endTag(null, TAG_NETWORK_POLICY);
2080 }
2081
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002082 // write all known subscription plans
2083 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2084 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002085 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002086 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2087 if (ArrayUtils.isEmpty(plans)) continue;
2088
2089 for (SubscriptionPlan plan : plans) {
2090 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2091 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002092 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002093 final RecurrenceRule cycleRule = plan.getCycleRule();
2094 writeStringAttribute(out, ATTR_CYCLE_START,
2095 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2096 writeStringAttribute(out, ATTR_CYCLE_END,
2097 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2098 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2099 RecurrenceRule.convertPeriod(cycleRule.period));
2100 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2101 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2102 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2103 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2104 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2105 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2106 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2107 }
2108 }
2109
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002110 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002111 for (int i = 0; i < mUidPolicy.size(); i++) {
2112 final int uid = mUidPolicy.keyAt(i);
2113 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002114
Jeff Sharkey497e4432011-06-14 17:27:29 -07002115 // skip writing empty policies
2116 if (policy == POLICY_NONE) continue;
2117
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002118 out.startTag(null, TAG_UID_POLICY);
2119 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002120 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002121 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002122 }
2123
2124 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002125
2126 // write all whitelists
2127 out.startTag(null, TAG_WHITELIST);
2128
Felipe Lemea9505cc2016-02-26 10:28:41 -08002129 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002130 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002131 for (int i = 0; i < size; i++) {
2132 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2133 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2134 writeIntAttribute(out, ATTR_UID, uid);
2135 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2136 }
2137
Felipe Lemeb85a6372016-01-14 16:16:16 -08002138 out.endTag(null, TAG_WHITELIST);
2139
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002140 out.endDocument();
2141
2142 mPolicyFile.finishWrite(fos);
2143 } catch (IOException e) {
2144 if (fos != null) {
2145 mPolicyFile.failWrite(fos);
2146 }
2147 }
2148 }
2149
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002150 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002151 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002152 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002153
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002154 if (!UserHandle.isApp(uid)) {
2155 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002156 }
Felipe Lemef0823852016-06-08 13:43:08 -07002157 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002158 final long token = Binder.clearCallingIdentity();
2159 try {
2160 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2161 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002162 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002163 }
2164 } finally {
2165 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002166 }
2167 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002168 }
2169
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002170 @Override
2171 public void addUidPolicy(int uid, int policy) {
2172 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002173
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002174 if (!UserHandle.isApp(uid)) {
2175 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2176 }
2177
Felipe Lemef0823852016-06-08 13:43:08 -07002178 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002179 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2180 policy |= oldPolicy;
2181 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002182 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002183 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002184 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002185 }
2186
2187 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002188 public void removeUidPolicy(int uid, int policy) {
2189 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2190
2191 if (!UserHandle.isApp(uid)) {
2192 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2193 }
2194
Felipe Lemef0823852016-06-08 13:43:08 -07002195 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002196 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2197 policy = oldPolicy & ~policy;
2198 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002199 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002200 }
2201 }
2202 }
2203
Felipe Lemef0823852016-06-08 13:43:08 -07002204 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2205 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002206
Felipe Leme57e3d312016-08-23 14:42:52 -07002207 final boolean notifyApp;
2208 if (!isUidValidForWhitelistRules(uid)) {
2209 notifyApp = false;
2210 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002211 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2212 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2213 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2214 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002215 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2216 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002217 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2218 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2219 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2220 if (LOGD)
2221 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2222 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2223 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002224 notifyApp = wasBlocked != isBlocked;
2225 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002226 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2227 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002228 }
2229
Felipe Lemef0823852016-06-08 13:43:08 -07002230 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002231 if (policy == POLICY_NONE) {
2232 mUidPolicy.delete(uid);
2233 } else {
2234 mUidPolicy.put(uid, policy);
2235 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002236
2237 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002238 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002239 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002240 synchronized (mNetworkPoliciesSecondLock) {
2241 writePolicyAL();
2242 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002243 }
2244 }
2245
2246 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002247 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002248 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2249
Felipe Lemef0823852016-06-08 13:43:08 -07002250 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002251 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002252 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002253 }
2254
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002255 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002256 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002257 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2258
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002259 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002260 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002261 for (int i = 0; i < mUidPolicy.size(); i++) {
2262 final int uid = mUidPolicy.keyAt(i);
2263 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002264 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2265 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002267 }
2268 }
2269 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002270 return uids;
2271 }
2272
2273 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002274 * Removes any persistable state associated with given {@link UserHandle}, persisting
2275 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002276 */
Felipe Lemef0823852016-06-08 13:43:08 -07002277 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002278
Felipe Lemef0823852016-06-08 13:43:08 -07002279 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002280 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002281
Felipe Lemea110eec2016-04-29 09:58:06 -07002282 // Remove entries from revoked default restricted background UID whitelist
2283 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2284 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2285 if (UserHandle.getUserId(uid) == userId) {
2286 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002287 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002288 }
2289 }
2290
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002291 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002292 int[] uids = new int[0];
2293 for (int i = 0; i < mUidPolicy.size(); i++) {
2294 final int uid = mUidPolicy.keyAt(i);
2295 if (UserHandle.getUserId(uid) == userId) {
2296 uids = appendInt(uids, uid);
2297 }
2298 }
2299
2300 if (uids.length > 0) {
2301 for (int uid : uids) {
2302 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002303 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002304 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002305 }
Felipe Lemef0823852016-06-08 13:43:08 -07002306 synchronized (mNetworkPoliciesSecondLock) {
2307 updateRulesForGlobalChangeAL(true);
2308 if (writePolicy && changed) {
2309 writePolicyAL();
2310 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002312 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002313 }
2314
2315 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002316 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002317 // TODO: create permission for observing network policy
2318 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002319 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002320 }
2321
2322 @Override
2323 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002324 // TODO: create permission for observing network policy
2325 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002326 mListeners.unregister(listener);
2327 }
2328
Jeff Sharkey1b861272011-05-22 00:34:52 -07002329 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002330 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002331 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2332
Felipe Leme6a05eee2016-02-19 14:43:51 -08002333 final long token = Binder.clearCallingIdentity();
2334 try {
2335 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002336 synchronized (mUidRulesFirstLock) {
2337 synchronized (mNetworkPoliciesSecondLock) {
2338 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002339 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002340 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002341 }
2342 } finally {
2343 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002344 }
2345 }
2346
Hugo Benichi446c9c92017-04-10 09:41:10 +09002347 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002348 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002349 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2350 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002351 }
2352
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002353 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002354 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002355 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002356 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002357 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2358 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2359 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002360 } catch (SecurityException e) {
2361 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002362
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002363 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2364 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2365 return new NetworkPolicy[0];
2366 }
Svet Ganov16a16892015-04-16 10:32:04 -07002367 }
2368
Felipe Lemef0823852016-06-08 13:43:08 -07002369 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002370 final int size = mNetworkPolicy.size();
2371 final NetworkPolicy[] policies = new NetworkPolicy[size];
2372 for (int i = 0; i < size; i++) {
2373 policies[i] = mNetworkPolicy.valueAt(i);
2374 }
2375 return policies;
2376 }
2377 }
2378
Felipe Lemef0823852016-06-08 13:43:08 -07002379 private void normalizePoliciesNL() {
2380 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002381 }
2382
Felipe Lemef0823852016-06-08 13:43:08 -07002383 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002384 final TelephonyManager tele = TelephonyManager.from(mContext);
2385 final String[] merged = tele.getMergedSubscriberIds();
2386
2387 mNetworkPolicy.clear();
2388 for (NetworkPolicy policy : policies) {
2389 // When two normalized templates conflict, prefer the most
2390 // restrictive policy
2391 policy.template = NetworkTemplate.normalize(policy.template, merged);
2392 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2393 if (existing == null || existing.compareTo(policy) > 0) {
2394 if (existing != null) {
2395 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2396 }
2397 mNetworkPolicy.put(policy.template, policy);
2398 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002399 }
2400 }
2401
2402 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002403 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002404 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002405
2406 final long token = Binder.clearCallingIdentity();
2407 try {
2408 performSnooze(template, TYPE_LIMIT);
2409 } finally {
2410 Binder.restoreCallingIdentity(token);
2411 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002412 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002413
Dianne Hackborn497175b2014-07-01 12:56:08 -07002414 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002415 maybeRefreshTrustedTime();
2416 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002417 synchronized (mUidRulesFirstLock) {
2418 synchronized (mNetworkPoliciesSecondLock) {
2419 // find and snooze local policy that matches
2420 final NetworkPolicy policy = mNetworkPolicy.get(template);
2421 if (policy == null) {
2422 throw new IllegalArgumentException("unable to find policy for " + template);
2423 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002424
Felipe Lemef0823852016-06-08 13:43:08 -07002425 switch (type) {
2426 case TYPE_WARNING:
2427 policy.lastWarningSnooze = currentTime;
2428 break;
2429 case TYPE_LIMIT:
2430 policy.lastLimitSnooze = currentTime;
2431 break;
2432 default:
2433 throw new IllegalArgumentException("unexpected type");
2434 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002435
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002436 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002437 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002438 }
2439 }
2440
2441 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002442 public void onTetheringChanged(String iface, boolean tethering) {
2443 // No need to enforce permission because setRestrictBackground() will do it.
2444 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002445 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002446 if (mRestrictBackground && tethering) {
2447 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2448 setRestrictBackground(false);
2449 }
2450 }
2451 }
2452
2453 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002454 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002455 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002456 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002457 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2458 final long token = Binder.clearCallingIdentity();
2459 try {
2460 maybeRefreshTrustedTime();
2461 synchronized (mUidRulesFirstLock) {
2462 if (restrictBackground == mRestrictBackground) {
2463 // Ideally, UI should never allow this scenario...
2464 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2465 return;
2466 }
2467 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002468 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002469
2470 } finally {
2471 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002472 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002473
Felipe Leme29e72ea2016-09-08 13:26:55 -07002474 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2475 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002476 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002477 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002478 }
2479 }
2480
Felipe Lemef0823852016-06-08 13:43:08 -07002481 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002482 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002483 final boolean oldRestrictBackground = mRestrictBackground;
2484 mRestrictBackground = restrictBackground;
2485 // Must whitelist foreground apps before turning data saver mode on.
2486 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2487 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002488 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002489 try {
2490 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2491 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2492 mRestrictBackground = oldRestrictBackground;
2493 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002494 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002495 return;
2496 }
2497 } catch (RemoteException e) {
2498 // ignored; service lives in system_server
2499 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002500
2501 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2502 mRestrictBackgroundChangedInBsm = true;
2503 }
Felipe Lemef0823852016-06-08 13:43:08 -07002504 synchronized (mNetworkPoliciesSecondLock) {
2505 updateNotificationsNL();
2506 writePolicyAL();
2507 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002508 }
2509
Felipe Lemeb85a6372016-01-14 16:16:16 -08002510 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002511 public int getRestrictBackgroundByCaller() {
2512 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2513 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002514
Felipe Lemef0823852016-06-08 13:43:08 -07002515 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002516 // Must clear identity because getUidPolicy() is restricted to system.
2517 final long token = Binder.clearCallingIdentity();
2518 final int policy;
2519 try {
2520 policy = getUidPolicy(uid);
2521 } finally {
2522 Binder.restoreCallingIdentity(token);
2523 }
2524 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2525 // App is blacklisted.
2526 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2527 }
Felipe Leme1b103232016-01-22 09:44:57 -08002528 if (!mRestrictBackground) {
2529 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2530 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002531 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002532 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2533 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2534 }
2535 }
2536
2537 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002538 public boolean getRestrictBackground() {
2539 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2540
Felipe Lemef0823852016-06-08 13:43:08 -07002541 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002542 return mRestrictBackground;
2543 }
2544 }
2545
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002546 @Override
2547 public void setDeviceIdleMode(boolean enabled) {
2548 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002549 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2550 try {
2551 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002552 if (mDeviceIdleMode == enabled) {
2553 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002554 }
Felipe Lemeea014392016-09-06 13:59:54 -07002555 mDeviceIdleMode = enabled;
2556 if (mSystemReady) {
2557 // Device idle change means we need to rebuild rules for all
2558 // known apps, so do a global refresh.
2559 updateRulesForRestrictPowerUL();
2560 }
2561 }
2562 if (enabled) {
2563 EventLogTags.writeDeviceIdleOnPhase("net");
2564 } else {
2565 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002566 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002567 } finally {
2568 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002569 }
2570 }
2571
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002572 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002573 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2574 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002575 final long token = Binder.clearCallingIdentity();
2576 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002577 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2578 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2579 for (WifiConfiguration config : configs) {
2580 if (Objects.equals(resolveNetworkId(config), networkId)) {
2581 config.meteredOverride = meteredOverride;
2582 wm.updateNetwork(config);
2583 }
2584 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002585 } finally {
2586 Binder.restoreCallingIdentity(token);
2587 }
2588 }
2589
Jeff Sharkey46645002011-07-27 21:11:21 -07002590 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002591 @Deprecated
2592 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2593 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2594 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2595 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002596 }
2597
Jeff Sharkey53313d72017-07-13 16:47:32 -06002598 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2599 // Verify they're not lying about package name
2600 mAppOps.checkPackage(callingUid, callingPackage);
2601
Jeff Sharkey53313d72017-07-13 16:47:32 -06002602 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002603 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002604 final long token = Binder.clearCallingIdentity();
2605 try {
2606 si = mContext.getSystemService(SubscriptionManager.class)
2607 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002608 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002609 } finally {
2610 Binder.restoreCallingIdentity(token);
2611 }
2612
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002613 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002614 if (si != null) {
2615 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2616 return;
2617 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002618 }
2619
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002620 // Second check: has the CarrierService delegated access?
2621 if (config != null) {
2622 final String overridePackage = config
2623 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2624 if (!TextUtils.isEmpty(overridePackage)
2625 && Objects.equals(overridePackage, callingPackage)) {
2626 return;
2627 }
2628 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002629
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002630 // Third check: is caller the fallback/default CarrierService?
2631 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2632 if (!TextUtils.isEmpty(defaultPackage)
2633 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002634 return;
2635 }
2636
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002637 // Final check: does the caller hold a permission?
2638 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002639 }
2640
2641 @Override
2642 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2643 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2644
Jeff Sharkey53313d72017-07-13 16:47:32 -06002645 final String fake = SystemProperties.get("fw.fake_plan");
2646 if (!TextUtils.isEmpty(fake)) {
2647 final List<SubscriptionPlan> plans = new ArrayList<>();
2648 if ("month_hard".equals(fake)) {
2649 plans.add(SubscriptionPlan.Builder
2650 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2651 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002652 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2653 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2654 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2655 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2656 .build());
2657 } else if ("month_soft".equals(fake)) {
2658 plans.add(SubscriptionPlan.Builder
2659 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2660 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2661 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2662 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002663 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2664 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2665 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2666 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2667 .build());
2668 } else if ("month_none".equals(fake)) {
2669 plans.add(SubscriptionPlan.Builder
2670 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2671 .setTitle("G-Mobile")
2672 .build());
2673 } else if ("prepaid".equals(fake)) {
2674 plans.add(SubscriptionPlan.Builder
2675 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2676 ZonedDateTime.now().plusDays(10))
2677 .setTitle("G-Mobile")
2678 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2679 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2680 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2681 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2682 .build());
2683 } else if ("prepaid_crazy".equals(fake)) {
2684 plans.add(SubscriptionPlan.Builder
2685 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2686 ZonedDateTime.now().plusDays(10))
2687 .setTitle("G-Mobile Anytime")
2688 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2689 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2690 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2691 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2692 .build());
2693 plans.add(SubscriptionPlan.Builder
2694 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2695 ZonedDateTime.now().plusDays(20))
2696 .setTitle("G-Mobile Nickel Nights")
2697 .setSummary("5¢/GB between 1-5AM")
2698 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2699 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2700 .build());
2701 plans.add(SubscriptionPlan.Builder
2702 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2703 ZonedDateTime.now().plusDays(20))
2704 .setTitle("G-Mobile Bonus 3G")
2705 .setSummary("Unlimited 3G data")
2706 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2707 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2708 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2709 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2710 .build());
2711 }
2712 return plans.toArray(new SubscriptionPlan[plans.size()]);
2713 }
2714
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002715 synchronized (mUidRulesFirstLock) {
2716 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002717 // Only give out plan details to the package that defined them,
2718 // so that we don't risk leaking plans between apps. We always
2719 // let in core system components (like the Settings app).
2720 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2721 if (Objects.equals(ownerPackage, callingPackage)
2722 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2723 return mSubscriptionPlans.get(subId);
2724 } else {
2725 Log.w(TAG, "Not returning plans because caller " + callingPackage
2726 + " doesn't match owner " + ownerPackage);
2727 return null;
2728 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002729 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002730 }
2731 }
2732
2733 @Override
2734 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2735 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2736
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002737 for (SubscriptionPlan plan : plans) {
2738 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002739 }
2740
2741 final long token = Binder.clearCallingIdentity();
2742 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002743 maybeRefreshTrustedTime();
2744 synchronized (mUidRulesFirstLock) {
2745 synchronized (mNetworkPoliciesSecondLock) {
2746 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002747 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002748 // TODO: update any implicit details from newly defined plans
2749 handleNetworkPoliciesUpdateAL(false);
2750 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002751 }
2752 } finally {
2753 Binder.restoreCallingIdentity(token);
2754 }
2755 }
2756
2757 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002758 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002759 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002760
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002761 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2762
Dianne Hackborn497175b2014-07-01 12:56:08 -07002763 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002764 for (String arg : args) {
2765 argSet.add(arg);
2766 }
2767
Felipe Lemef0823852016-06-08 13:43:08 -07002768 synchronized (mUidRulesFirstLock) {
2769 synchronized (mNetworkPoliciesSecondLock) {
2770 if (argSet.contains("--unsnooze")) {
2771 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2772 mNetworkPolicy.valueAt(i).clearSnooze();
2773 }
2774
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002775 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002776
2777 fout.println("Cleared snooze timestamps");
2778 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002779 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002780
Felipe Lemef0823852016-06-08 13:43:08 -07002781 fout.print("System ready: "); fout.println(mSystemReady);
2782 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2783 fout.print("Restrict power: "); fout.println(mRestrictPower);
2784 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
2785 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002786 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002787 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2788 fout.println(mNetworkPolicy.valueAt(i).toString());
2789 }
2790 fout.decreaseIndent();
2791
2792 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2793
2794 fout.println("Policy for UIDs:");
2795 fout.increaseIndent();
2796 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002797 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002798 final int uid = mUidPolicy.keyAt(i);
2799 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002800 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002801 fout.print(uid);
2802 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002803 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002804 fout.println();
2805 }
2806 fout.decreaseIndent();
2807
2808 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2809 if (size > 0) {
2810 fout.println("Power save whitelist (except idle) app ids:");
2811 fout.increaseIndent();
2812 for (int i = 0; i < size; i++) {
2813 fout.print("UID=");
2814 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2815 fout.print(": ");
2816 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2817 fout.println();
2818 }
2819 fout.decreaseIndent();
2820 }
2821
2822 size = mPowerSaveWhitelistAppIds.size();
2823 if (size > 0) {
2824 fout.println("Power save whitelist app ids:");
2825 fout.increaseIndent();
2826 for (int i = 0; i < size; i++) {
2827 fout.print("UID=");
2828 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2829 fout.print(": ");
2830 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2831 fout.println();
2832 }
2833 fout.decreaseIndent();
2834 }
2835
Felipe Lemef0823852016-06-08 13:43:08 -07002836 size = mDefaultRestrictBackgroundWhitelistUids.size();
2837 if (size > 0) {
2838 fout.println("Default restrict background whitelist uids:");
2839 fout.increaseIndent();
2840 for (int i = 0; i < size; i++) {
2841 fout.print("UID=");
2842 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2843 fout.println();
2844 }
2845 fout.decreaseIndent();
2846 }
2847
2848 size = mRestrictBackgroundWhitelistRevokedUids.size();
2849 if (size > 0) {
2850 fout.println("Default restrict background whitelist uids revoked by users:");
2851 fout.increaseIndent();
2852 for (int i = 0; i < size; i++) {
2853 fout.print("UID=");
2854 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2855 fout.println();
2856 }
2857 fout.decreaseIndent();
2858 }
2859
2860 final SparseBooleanArray knownUids = new SparseBooleanArray();
2861 collectKeys(mUidState, knownUids);
2862 collectKeys(mUidRules, knownUids);
2863
2864 fout.println("Status for all known UIDs:");
2865 fout.increaseIndent();
2866 size = knownUids.size();
2867 for (int i = 0; i < size; i++) {
2868 final int uid = knownUids.keyAt(i);
2869 fout.print("UID=");
2870 fout.print(uid);
2871
2872 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2873 fout.print(" state=");
2874 fout.print(state);
2875 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2876 fout.print(" (fg)");
2877 } else {
2878 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2879 ? " (fg svc)" : " (bg)");
2880 }
2881
2882 final int uidRules = mUidRules.get(uid, RULE_NONE);
2883 fout.print(" rules=");
2884 fout.print(uidRulesToString(uidRules));
2885 fout.println();
2886 }
2887 fout.decreaseIndent();
2888
2889 fout.println("Status for just UIDs with rules:");
2890 fout.increaseIndent();
2891 size = mUidRules.size();
2892 for (int i = 0; i < size; i++) {
2893 final int uid = mUidRules.keyAt(i);
2894 fout.print("UID=");
2895 fout.print(uid);
2896 final int uidRules = mUidRules.get(uid, RULE_NONE);
2897 fout.print(" rules=");
2898 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002899 fout.println();
2900 }
2901 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002902
2903 fout.println("Observed uid state changes:");
2904 fout.increaseIndent();
2905 mObservedHistory.dumpUL(fout);
2906 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002907 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002908 }
2909 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002910
2911 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002912 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07002913 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08002914 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07002915 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08002916 }
2917
2918 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002919 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07002920 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2921
Felipe Lemef0823852016-06-08 13:43:08 -07002922 synchronized (mUidRulesFirstLock) {
2923 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002924 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002925 }
2926
Felipe Lemef0823852016-06-08 13:43:08 -07002927 private boolean isUidForegroundUL(int uid) {
2928 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07002929 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
2930 }
2931
Felipe Lemef0823852016-06-08 13:43:08 -07002932 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07002933 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002934 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07002935 }
2936
Felipe Lemef0823852016-06-08 13:43:08 -07002937 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07002938 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2939 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
2940 }
2941
Felipe Lemef0823852016-06-08 13:43:08 -07002942 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07002943 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07002944 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07002945 }
2946
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002947 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002948 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07002949 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
2950 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002951 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00002952 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07002953 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
2954 try {
2955 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2956 if (oldUidState != uidState) {
2957 // state changed, push updated rules
2958 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00002959 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
2960 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
2961 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
2962 if (isUidIdle(uid)) {
2963 updateRuleForAppIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002964 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002965 if (mDeviceIdleMode) {
2966 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002967 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002968 if (mRestrictPower) {
2969 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07002970 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002971 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07002972 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002973 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002974 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002975 } finally {
2976 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002977 }
2978 }
2979
Felipe Lemef0823852016-06-08 13:43:08 -07002980 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002981 final int index = mUidState.indexOfKey(uid);
2982 if (index >= 0) {
2983 final int oldUidState = mUidState.valueAt(index);
2984 mUidState.removeAt(index);
2985 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07002986 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00002987 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002988 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07002989 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07002990 }
Felipe Leme011b98f2016-02-10 17:28:31 -08002991 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07002992 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08002993 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00002994 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07002995 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07002996 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002997 }
2998 }
2999
Felipe Lemef28983d2016-03-25 12:18:23 -07003000 // adjust stats accounting based on foreground status
3001 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003002 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3003 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3004 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3005 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003006 try {
3007 mNetworkStats.setUidForeground(uid, uidForeground);
3008 } catch (RemoteException e) {
3009 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003010 } finally {
3011 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003012 }
3013 }
3014
Sudheer Shankac9d94072017-02-22 22:13:55 +00003015 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3016 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003017 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003018 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003019 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003020 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003021 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003022 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003023 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003024 }
3025
Felipe Lemef0823852016-06-08 13:43:08 -07003026 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003027 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3028 try {
3029 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3030 mUidFirewallPowerSaveRules);
3031 } finally {
3032 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3033 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003034 }
3035
Felipe Lemef0823852016-06-08 13:43:08 -07003036 void updateRuleForRestrictPowerUL(int uid) {
3037 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003038 }
3039
Felipe Lemef0823852016-06-08 13:43:08 -07003040 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003041 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3042 try {
3043 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3044 mUidFirewallDozableRules);
3045 } finally {
3046 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3047 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003048 }
3049
Felipe Lemef0823852016-06-08 13:43:08 -07003050 void updateRuleForDeviceIdleUL(int uid) {
3051 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003052 }
3053
Felipe Lemef28983d2016-03-25 12:18:23 -07003054 // NOTE: since both fw_dozable and fw_powersave uses the same map
3055 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003056 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003057 SparseIntArray rules) {
3058 if (enabled) {
3059 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003060 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003061 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003062 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003063 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003064 for (int ui = users.size() - 1; ui >= 0; ui--) {
3065 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003066 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3067 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3068 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3069 updateRulesForWhitelistedAppIds(uidRules,
3070 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003071 }
3072 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003073 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003074 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003075 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3076 }
3077 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003078 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3079 } else {
3080 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003081 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003082 }
3083
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003084 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3085 final SparseBooleanArray whitelistedAppIds, int userId) {
3086 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3087 if (whitelistedAppIds.valueAt(i)) {
3088 final int appId = whitelistedAppIds.keyAt(i);
3089 final int uid = UserHandle.getUid(userId, appId);
3090 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3091 }
3092 }
3093 }
3094
3095 /**
3096 * @param deviceIdleMode if true then we don't consider
3097 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3098 * whitelisted.
3099 */
3100 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003101 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003102 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3103 || mPowerSaveWhitelistAppIds.get(appId);
3104 if (!deviceIdleMode) {
3105 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3106 }
3107 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003108 }
3109
Felipe Lemef28983d2016-03-25 12:18:23 -07003110 // NOTE: since both fw_dozable and fw_powersave uses the same map
3111 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003112 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003113 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003114 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3115 chain == FIREWALL_CHAIN_DOZABLE);
3116 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003117 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003118 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003119 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003120 }
3121 }
3122 }
3123
Felipe Lemef0823852016-06-08 13:43:08 -07003124 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003125 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3126 try {
3127 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3128 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003129
Felipe Leme873a83a2016-09-07 11:34:10 -07003130 // Fully update the app idle firewall chain.
3131 final List<UserInfo> users = mUserManager.getUsers();
3132 for (int ui = users.size() - 1; ui >= 0; ui--) {
3133 UserInfo user = users.get(ui);
3134 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3135 for (int uid : idleUids) {
3136 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3137 // quick check: if this uid doesn't have INTERNET permission, it
3138 // doesn't have network access anyway, so it is a waste to mess
3139 // with it here.
3140 if (hasInternetPermissions(uid)) {
3141 uidRules.put(uid, FIREWALL_RULE_DENY);
3142 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003143 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003144 }
3145 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003146
Felipe Lemebc853dd2016-09-08 13:26:55 -07003147 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003148 } finally {
3149 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3150 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003151 }
3152
Felipe Lemef0823852016-06-08 13:43:08 -07003153 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003154 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003155
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003156 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3157 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3158 }
3159 try {
3160 int appId = UserHandle.getAppId(uid);
3161 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3162 && !isUidForegroundOnRestrictPowerUL(uid)) {
3163 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3164 } else {
3165 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3166 }
3167 } finally {
3168 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003169 }
3170 }
3171
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003172 /**
3173 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3174 * changed.
3175 */
Felipe Lemef0823852016-06-08 13:43:08 -07003176 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003177 boolean paroled = mUsageStats.isAppIdleParoleOn();
3178 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003179 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003180
3181 int ruleCount = mUidFirewallStandbyRules.size();
3182 for (int i = 0; i < ruleCount; i++) {
3183 int uid = mUidFirewallStandbyRules.keyAt(i);
3184 int oldRules = mUidRules.get(uid);
3185 if (enableChain) {
3186 // Chain wasn't enabled before and the other power-related
3187 // chains are whitelists, so we can clear the
3188 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3189 // the effective rules result in blocking network access.
3190 oldRules &= MASK_METERED_NETWORKS;
3191 } else {
3192 // Skip if it had no restrictions to begin with
3193 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3194 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003195 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3196 if (newUidRules == RULE_NONE) {
3197 mUidRules.delete(uid);
3198 } else {
3199 mUidRules.put(uid, newUidRules);
3200 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003201 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003202 }
3203
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003204 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003205 * Update rules that might be changed by {@link #mRestrictBackground},
3206 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003207 */
Felipe Lemef0823852016-06-08 13:43:08 -07003208 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003209 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3210 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3211 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3212 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003213 try {
Felipe Leme09700462016-09-08 09:33:48 -07003214 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003215 updateRulesForRestrictPowerUL();
3216 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003217
Felipe Leme873a83a2016-09-07 11:34:10 -07003218 // If the set of restricted networks may have changed, re-evaluate those.
3219 if (restrictedNetworksChanged) {
3220 normalizePoliciesNL();
3221 updateNetworkRulesNL();
3222 }
3223 } finally {
3224 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003225 }
3226 }
3227
Felipe Leme09700462016-09-08 09:33:48 -07003228 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003229 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003230 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3231 try {
3232 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003233 updateRulesForPowerSaveUL();
3234 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3235 } finally {
3236 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3237 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003238 }
3239
Felipe Lemef0823852016-06-08 13:43:08 -07003240 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003241 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3242 try {
3243 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3244 } finally {
3245 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3246 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003247 }
3248
3249 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3250 private static final int TYPE_RESTRICT_POWER = 2;
3251 @Retention(RetentionPolicy.SOURCE)
3252 @IntDef(flag = false, value = {
3253 TYPE_RESTRICT_BACKGROUND,
3254 TYPE_RESTRICT_POWER,
3255 })
3256 public @interface RestrictType {
3257 }
3258
3259 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003260 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003261 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3262 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3263 }
3264 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003265 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003266
3267 final PackageManager pm = mContext.getPackageManager();
3268 final List<UserInfo> users;
3269 final List<ApplicationInfo> apps;
3270
3271 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3272 try {
3273 users = mUserManager.getUsers();
3274 } finally {
3275 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3276 }
3277 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3278 try {
3279 apps = pm.getInstalledApplications(
3280 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3281 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3282 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3283 } finally {
3284 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3285 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003286
Felipe Leme873a83a2016-09-07 11:34:10 -07003287 final int usersSize = users.size();
3288 final int appsSize = apps.size();
3289 for (int i = 0; i < usersSize; i++) {
3290 final UserInfo user = users.get(i);
3291 for (int j = 0; j < appsSize; j++) {
3292 final ApplicationInfo app = apps.get(j);
3293 final int uid = UserHandle.getUid(user.id, app.uid);
3294 switch (type) {
3295 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003296 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003297 break;
3298 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003299 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003300 break;
3301 default:
3302 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3303 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003304 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003305 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003306 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003307 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003308 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003309 }
3310
Felipe Lemef0823852016-06-08 13:43:08 -07003311 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003312 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003313 for (int i = 0; i < users.size(); i++) {
3314 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003315 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003316 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003317 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003318 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003319 updateRuleForAppIdleUL(uid);
3320 updateRuleForDeviceIdleUL(uid);
3321 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003322 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003323 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003324 }
3325 }
3326 }
3327
Felipe Leme70c57c22016-03-29 10:45:13 -07003328 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3329 // methods below could be merged into a isUidValidForRules() method.
3330 private boolean isUidValidForBlacklistRules(int uid) {
3331 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003332 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003333 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003334 return true;
3335 }
3336
3337 return false;
3338 }
3339
Felipe Leme70c57c22016-03-29 10:45:13 -07003340 private boolean isUidValidForWhitelistRules(int uid) {
3341 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3342 }
3343
Amith Yamasani15e472352015-04-24 19:06:07 -07003344 private boolean isUidIdle(int uid) {
3345 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3346 final int userId = UserHandle.getUserId(uid);
3347
songjinshi0655edd2016-05-18 19:55:32 +08003348 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003349 for (String packageName : packages) {
3350 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3351 return false;
3352 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003353 }
3354 }
3355 return true;
3356 }
3357
3358 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003359 * Checks if an uid has INTERNET permissions.
3360 * <p>
3361 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003362 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003363 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003364 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003365 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003366 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003367 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003368 }
3369 } catch (RemoteException e) {
3370 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003371 return true;
3372 }
3373
3374 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003375 * Clears all state - internal and external - associated with an UID.
3376 */
3377 private void onUidDeletedUL(int uid) {
3378 // First cleanup in-memory state synchronously...
3379 mUidRules.delete(uid);
3380 mUidPolicy.delete(uid);
3381 mUidFirewallStandbyRules.delete(uid);
3382 mUidFirewallDozableRules.delete(uid);
3383 mUidFirewallPowerSaveRules.delete(uid);
3384 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3385 mPowerSaveWhitelistAppIds.delete(uid);
3386 mPowerSaveTempWhitelistAppIds.delete(uid);
3387
3388 // ...then update iptables asynchronously.
3389 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3390 }
3391
3392 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003393 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003394 *
Felipe Leme781ba142016-05-09 16:24:48 -07003395 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003396 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003397 * <li>Doze mode
3398 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003399 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003400 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003401 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003402 *
3403 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003404 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003405 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003406 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003407 updateRuleForDeviceIdleUL(uid);
3408 updateRuleForAppIdleUL(uid);
3409 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003410
3411 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003412 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003413
3414 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003415 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003416 }
3417
Felipe Leme70c57c22016-03-29 10:45:13 -07003418 /**
3419 * Applies network rules to bandwidth controllers based on process state and user-defined
3420 * restrictions (blacklist / whitelist).
3421 *
3422 * <p>
3423 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3424 * networks:
3425 * <ul>
3426 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3427 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3428 * also blacklisted.
3429 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3430 * no UIDs other those whitelisted will have access.
3431 * <ul>
3432 *
3433 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3434 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3435 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3436 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003437 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003438 * {@link INetworkManagementService}, but this method should also be called in events (like
3439 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3440 * following rules should also be applied:
3441 *
3442 * <ul>
3443 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3444 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3445 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3446 * {@code bw_penalty_box}.
3447 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3448 * </ul>
3449 *
3450 * <p>For optimization, the rules are only applied on user apps that have internet access
3451 * permission, since there is no need to change the {@code iptables} rule if the app does not
3452 * have permission to use the internet.
3453 *
3454 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003455 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003456 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003457 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003458 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3459 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3460 "updateRulesForDataUsageRestrictionsUL: " + uid);
3461 }
3462 try {
3463 updateRulesForDataUsageRestrictionsULInner(uid);
3464 } finally {
3465 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3466 }
3467 }
3468
3469 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003470 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003471 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003472 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003473 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003474
Dianne Hackborn497175b2014-07-01 12:56:08 -07003475 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003476 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003477 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003478
Felipe Leme781ba142016-05-09 16:24:48 -07003479 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003480 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003481 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3482 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003483
Felipe Leme70c57c22016-03-29 10:45:13 -07003484 // First step: define the new rule based on user restrictions and foreground state.
3485 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003486 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3487 newRule = RULE_TEMPORARY_ALLOW_METERED;
3488 } else if (isWhitelisted) {
3489 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003490 }
3491 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003492 if (isBlacklisted) {
3493 newRule = RULE_REJECT_METERED;
3494 } else if (mRestrictBackground && isWhitelisted) {
3495 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003496 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003497 }
Felipe Leme781ba142016-05-09 16:24:48 -07003498 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003499
Felipe Lemef28983d2016-03-25 12:18:23 -07003500 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003501 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003502 + ": isForeground=" +isForeground
3503 + ", isBlacklisted=" + isBlacklisted
3504 + ", isWhitelisted=" + isWhitelisted
3505 + ", oldRule=" + uidRulesToString(oldRule)
3506 + ", newRule=" + uidRulesToString(newRule)
3507 + ", newUidRules=" + uidRulesToString(newUidRules)
3508 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003509 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003510
Felipe Leme46c4fc32016-05-04 09:21:43 -07003511 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003512 mUidRules.delete(uid);
3513 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003514 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003515 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003516
Felipe Leme70c57c22016-03-29 10:45:13 -07003517 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003518 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003519 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003520 // Temporarily whitelist foreground app, removing from blacklist if necessary
3521 // (since bw_penalty_box prevails over bw_happy_box).
3522
3523 setMeteredNetworkWhitelist(uid, true);
3524 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3525 // but ideally it should be just:
3526 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003527 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003528 setMeteredNetworkBlacklist(uid, false);
3529 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003530 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003531 // Remove temporary whitelist from app that is not on foreground anymore.
3532
3533 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3534 // but ideally they should be just:
3535 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3536 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003537 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003538 setMeteredNetworkWhitelist(uid, false);
3539 }
Felipe Leme781ba142016-05-09 16:24:48 -07003540 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003541 setMeteredNetworkBlacklist(uid, true);
3542 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003543 } else if (hasRule(newRule, RULE_REJECT_METERED)
3544 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003545 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003546 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003547 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003548 // Since blacklist prevails over whitelist, we need to handle the special case
3549 // where app is whitelisted and blacklisted at the same time (although such
3550 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003551 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003552 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003553 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3554 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003555 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003556 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003557 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003558 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003559 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3560 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003561 + ", whitelisted=" + isWhitelisted
3562 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003563 + ", newRule=" + uidRulesToString(newUidRules)
3564 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003565 }
Felipe Leme781ba142016-05-09 16:24:48 -07003566
Sudheer Shankac9d94072017-02-22 22:13:55 +00003567 // Dispatch changed rule to existing listeners.
3568 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003569 }
3570 }
3571
3572 /**
3573 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3574 * listeners in case of change.
3575 * <p>
3576 * There are 3 power-related rules that affects whether an app has background access on
3577 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3578 * restriction, it's added to the equivalent firewall chain:
3579 * <ul>
3580 * <li>App is idle: {@code fw_standby} firewall chain.
3581 * <li>Device is idle: {@code fw_dozable} firewall chain.
3582 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3583 * </ul>
3584 * <p>
3585 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3586 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3587 * <p>
3588 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3589 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003590 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003591 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3592
Sudheer Shankac9d94072017-02-22 22:13:55 +00003593 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003594
Sudheer Shankac9d94072017-02-22 22:13:55 +00003595 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003596 mUidRules.delete(uid);
3597 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003598 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003599 }
3600 }
3601
3602 /**
3603 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3604 *
3605 * @param uid the uid of the app to update rules for
3606 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3607 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3608 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003609 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003610 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003611 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003612 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3613 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3614 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3615 + (paroled ? "P" : "-"));
3616 }
3617 try {
3618 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3619 } finally {
3620 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3621 }
3622 }
3623
3624 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003625 if (!isUidValidForBlacklistRules(uid)) {
3626 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003627 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003628 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003629
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003630 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003631 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003632 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003633
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003634 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003635 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3636 int newRule = RULE_NONE;
3637
3638 // First step: define the new rule based on user restrictions and foreground state.
3639
3640 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3641 // by considering the foreground and non-foreground states.
3642 if (isForeground) {
3643 if (restrictMode) {
3644 newRule = RULE_ALLOW_ALL;
3645 }
3646 } else if (restrictMode) {
3647 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3648 }
3649
3650 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3651
3652 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003653 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003654 + ", isIdle: " + isIdle
3655 + ", mRestrictPower: " + mRestrictPower
3656 + ", mDeviceIdleMode: " + mDeviceIdleMode
3657 + ", isForeground=" + isForeground
3658 + ", isWhitelisted=" + isWhitelisted
3659 + ", oldRule=" + uidRulesToString(oldRule)
3660 + ", newRule=" + uidRulesToString(newRule)
3661 + ", newUidRules=" + uidRulesToString(newUidRules)
3662 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3663 }
3664
Felipe Leme781ba142016-05-09 16:24:48 -07003665 // Second step: notify listeners if state changed.
3666 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003667 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003668 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003669 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003670 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3671 } else {
3672 // All scenarios should have been covered above
3673 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3674 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003675 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003676 + ", newRule=" + uidRulesToString(newUidRules)
3677 + ", oldRule=" + uidRulesToString(oldUidRules));
3678 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003679 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003680 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003681
Sudheer Shankac9d94072017-02-22 22:13:55 +00003682 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003683 }
3684
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003685 private class AppIdleStateChangeListener
3686 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3687
3688 @Override
3689 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3690 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003691 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3692 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003693 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003694 synchronized (mUidRulesFirstLock) {
3695 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003696 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003697 }
3698 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003699 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003700 }
3701
3702 @Override
3703 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003704 synchronized (mUidRulesFirstLock) {
3705 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003706 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003707 }
3708 }
3709
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003710 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3711 if (listener != null) {
3712 try {
3713 listener.onUidRulesChanged(uid, uidRules);
3714 } catch (RemoteException ignored) {
3715 }
3716 }
3717 }
3718
3719 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3720 String[] meteredIfaces) {
3721 if (listener != null) {
3722 try {
3723 listener.onMeteredIfacesChanged(meteredIfaces);
3724 } catch (RemoteException ignored) {
3725 }
3726 }
3727 }
3728
3729 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3730 boolean restrictBackground) {
3731 if (listener != null) {
3732 try {
3733 listener.onRestrictBackgroundChanged(restrictBackground);
3734 } catch (RemoteException ignored) {
3735 }
3736 }
3737 }
3738
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003739 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3740 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003741 if (listener != null) {
3742 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003743 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003744 } catch (RemoteException ignored) {
3745 }
3746 }
3747 }
3748
Makoto Onuki8e777332017-03-28 11:25:47 -07003749 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003750 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003751 public boolean handleMessage(Message msg) {
3752 switch (msg.what) {
3753 case MSG_RULES_CHANGED: {
3754 final int uid = msg.arg1;
3755 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003756 final int length = mListeners.beginBroadcast();
3757 for (int i = 0; i < length; i++) {
3758 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3759 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003760 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003761 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003762 return true;
3763 }
3764 case MSG_METERED_IFACES_CHANGED: {
3765 final String[] meteredIfaces = (String[]) msg.obj;
3766 final int length = mListeners.beginBroadcast();
3767 for (int i = 0; i < length; i++) {
3768 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003769 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003770 }
3771 mListeners.finishBroadcast();
3772 return true;
3773 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003774 case MSG_LIMIT_REACHED: {
3775 final String iface = (String) msg.obj;
3776
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003777 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003778 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003779 if (mMeteredIfaces.contains(iface)) {
3780 try {
3781 // force stats update to make sure we have
3782 // numbers that caused alert to trigger.
3783 mNetworkStats.forceUpdate();
3784 } catch (RemoteException e) {
3785 // ignored; service lives in system_server
3786 }
3787
Felipe Lemef0823852016-06-08 13:43:08 -07003788 updateNetworkEnabledNL();
3789 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003790 }
3791 }
3792 return true;
3793 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003794 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3795 final boolean restrictBackground = msg.arg1 != 0;
3796 final int length = mListeners.beginBroadcast();
3797 for (int i = 0; i < length; i++) {
3798 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003799 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003800 }
3801 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003802 final Intent intent =
3803 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3804 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3805 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3806 return true;
3807 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003808 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003809 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003810 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003811 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003812 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003813 final int length = mListeners.beginBroadcast();
3814 for (int i = 0; i < length; i++) {
3815 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003816 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003817 }
3818 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003819 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3820 if (notifyApp.booleanValue()) {
3821 broadcastRestrictBackgroundChanged(uid, notifyApp);
3822 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003823 return true;
3824 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003825 case MSG_ADVISE_PERSIST_THRESHOLD: {
3826 final long lowestRule = (Long) msg.obj;
3827 try {
3828 // make sure stats are recorded frequently enough; we aim
3829 // for 2MB threshold for 2GB/month rules.
3830 final long persistThreshold = lowestRule / 1000;
3831 mNetworkStats.advisePersistThreshold(persistThreshold);
3832 } catch (RemoteException e) {
3833 // ignored; service lives in system_server
3834 }
3835 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003836 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003837 case MSG_UPDATE_INTERFACE_QUOTA: {
3838 removeInterfaceQuota((String) msg.obj);
3839 // int params need to be stitched back into a long
3840 setInterfaceQuota((String) msg.obj,
3841 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3842 return true;
3843 }
3844 case MSG_REMOVE_INTERFACE_QUOTA: {
3845 removeInterfaceQuota((String) msg.obj);
3846 return true;
3847 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003848 case MSG_SET_FIREWALL_RULES: {
3849 final int chain = msg.arg1;
3850 final int toggle = msg.arg2;
3851 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3852 if (uidRules != null) {
3853 setUidFirewallRules(chain, uidRules);
3854 }
3855 if (toggle != CHAIN_TOGGLE_NONE) {
3856 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3857 }
3858 return true;
3859 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003860 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3861 resetUidFirewallRules(msg.arg1);
3862 return true;
3863 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003864 default: {
3865 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003866 }
3867 }
3868 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003869 };
3870
3871 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3872 @Override
3873 public boolean handleMessage(Message msg) {
3874 switch (msg.what) {
3875 case UID_MSG_STATE_CHANGED: {
3876 final int uid = msg.arg1;
3877 final int procState = msg.arg2;
3878 final long procStateSeq = (Long) msg.obj;
3879
3880 handleUidChanged(uid, procState, procStateSeq);
3881 return true;
3882 }
3883 case UID_MSG_GONE: {
3884 final int uid = msg.arg1;
3885 handleUidGone(uid);
3886 return true;
3887 }
3888 default: {
3889 return false;
3890 }
3891 }
3892 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003893
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003894 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003895
Makoto Onuki8e777332017-03-28 11:25:47 -07003896 void handleUidChanged(int uid, int procState, long procStateSeq) {
3897 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3898 try {
3899 synchronized (mUidRulesFirstLock) {
3900 // We received a uid state change callback, add it to the history so that it
3901 // will be useful for debugging.
3902 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3903 // Now update the network policy rules as per the updated uid state.
3904 updateUidStateUL(uid, procState);
3905 // Updating the network rules is done, so notify AMS about this.
3906 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3907 }
3908 } finally {
3909 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3910 }
3911 }
3912
3913 void handleUidGone(int uid) {
3914 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
3915 try {
3916 synchronized (mUidRulesFirstLock) {
3917 removeUidStateUL(uid);
3918 }
3919 } finally {
3920 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3921 }
3922 }
3923
Felipe Leme57e3d312016-08-23 14:42:52 -07003924 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
3925 final PackageManager pm = mContext.getPackageManager();
3926 final String[] packages = pm.getPackagesForUid(uid);
3927 if (packages != null) {
3928 final int userId = UserHandle.getUserId(uid);
3929 for (String packageName : packages) {
3930 final Intent intent =
3931 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3932 intent.setPackage(packageName);
3933 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3934 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
3935 }
3936 }
3937 }
3938
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003939 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003940 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003941 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003942 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003943 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003944 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003945 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003946 }
3947 }
3948
3949 private void removeInterfaceQuota(String iface) {
3950 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003951 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003952 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003953 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003954 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003955 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07003956 }
3957 }
3958
Felipe Leme70c57c22016-03-29 10:45:13 -07003959 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
3960 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003961 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07003962 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003963 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003964 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
3965 } catch (RemoteException e) {
3966 // ignored; service lives in system_server
3967 }
3968 }
3969
3970 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
3971 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
3972 try {
3973 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
3974 } catch (IllegalStateException e) {
3975 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003976 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07003977 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003978 }
3979 }
3980
Felipe Lemebc853dd2016-09-08 13:26:55 -07003981 private static final int CHAIN_TOGGLE_NONE = 0;
3982 private static final int CHAIN_TOGGLE_ENABLE = 1;
3983 private static final int CHAIN_TOGGLE_DISABLE = 2;
3984 @Retention(RetentionPolicy.SOURCE)
3985 @IntDef(flag = false, value = {
3986 CHAIN_TOGGLE_NONE,
3987 CHAIN_TOGGLE_ENABLE,
3988 CHAIN_TOGGLE_DISABLE
3989 })
3990 public @interface ChainToggleType {
3991 }
3992
3993 /**
3994 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
3995 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
3996 *
3997 * @param chain firewall chain.
3998 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
3999 * @param toggle whether the chain should be enabled, disabled, or not changed.
4000 */
4001 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4002 @ChainToggleType int toggle) {
4003 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4004 }
4005
Amith Yamasani15e472352015-04-24 19:06:07 -07004006 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004007 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4008 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4009 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004010 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004011 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004012 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004013 int size = uidRules.size();
4014 int[] uids = new int[size];
4015 int[] rules = new int[size];
4016 for(int index = size - 1; index >= 0; --index) {
4017 uids[index] = uidRules.keyAt(index);
4018 rules[index] = uidRules.valueAt(index);
4019 }
4020 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004021 } catch (IllegalStateException e) {
4022 Log.wtf(TAG, "problem setting firewall uid rules", e);
4023 } catch (RemoteException e) {
4024 // ignored; service lives in system_server
4025 }
4026 }
4027
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004028 /**
4029 * Add or remove a uid to the firewall blacklist for all network ifaces.
4030 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004031 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004032 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4033 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4034 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004035 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004036 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004037 if (chain == FIREWALL_CHAIN_DOZABLE) {
4038 mUidFirewallDozableRules.put(uid, rule);
4039 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4040 mUidFirewallStandbyRules.put(uid, rule);
4041 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4042 mUidFirewallPowerSaveRules.put(uid, rule);
4043 }
4044
4045 try {
4046 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4047 } catch (IllegalStateException e) {
4048 Log.wtf(TAG, "problem setting firewall uid rules", e);
4049 } catch (RemoteException e) {
4050 // ignored; service lives in system_server
4051 }
4052 } finally {
4053 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004054 }
4055 }
4056
4057 /**
4058 * Add or remove a uid to the firewall blacklist for all network ifaces.
4059 */
Felipe Lemef0823852016-06-08 13:43:08 -07004060 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004061 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4062 mFirewallChainStates.get(chain) == enable) {
4063 // All is the same, nothing to do.
4064 return;
4065 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004066 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004067 try {
4068 mNetworkManager.setFirewallChainEnabled(chain, enable);
4069 } catch (IllegalStateException e) {
4070 Log.wtf(TAG, "problem enable firewall chain", e);
4071 } catch (RemoteException e) {
4072 // ignored; service lives in system_server
4073 }
4074 }
4075
Felipe Leme03e95e22016-09-09 09:25:31 -07004076 /**
4077 * Resets all firewall rules associated with an UID.
4078 */
4079 private void resetUidFirewallRules(int uid) {
4080 try {
4081 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4082 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4083 mNetworkManager
4084 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4085 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4086 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4087 } catch (IllegalStateException e) {
4088 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4089 } catch (RemoteException e) {
4090 // ignored; service lives in system_server
4091 }
4092 }
4093
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004094 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4095 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004096 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004097 } catch (RuntimeException e) {
4098 Slog.w(TAG, "problem reading network stats: " + e);
4099 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004100 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004101 // ignored; service lives in system_server
4102 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004103 }
4104 }
4105
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004106 private boolean isBandwidthControlEnabled() {
4107 final long token = Binder.clearCallingIdentity();
4108 try {
4109 return mNetworkManager.isBandwidthControlEnabled();
4110 } catch (RemoteException e) {
4111 // ignored; service lives in system_server
4112 return false;
4113 } finally {
4114 Binder.restoreCallingIdentity(token);
4115 }
4116 }
4117
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004118 /**
4119 * Try refreshing {@link #mTime} when stale.
4120 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004121 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004122 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004123 mTime.forceRefresh();
4124 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004125 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004126
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004127 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004128 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4129 }
4130
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004131 private static Intent buildAllowBackgroundDataIntent() {
4132 return new Intent(ACTION_ALLOW_BACKGROUND);
4133 }
4134
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004135 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4136 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4137 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4138 return intent;
4139 }
4140
Wei Liu546cb772016-07-21 16:19:01 -07004141 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004142 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004143 intent.setComponent(ComponentName.unflattenFromString(
4144 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004145 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4146 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4147 return intent;
4148 }
4149
Wei Liu546cb772016-07-21 16:19:01 -07004150 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004151 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004152 intent.setComponent(ComponentName.unflattenFromString(
4153 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004154 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4155 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4156 return intent;
4157 }
4158
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004159 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004160 public void addIdleHandler(IdleHandler handler) {
4161 mHandler.getLooper().getQueue().addIdleHandler(handler);
4162 }
4163
jackqdyulei29c82ab2017-03-10 14:09:16 -08004164 @VisibleForTesting
4165 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4166 mRestrictBackgroundPowerState = result;
4167
4168 boolean restrictBackground = result.batterySaverEnabled;
4169 boolean shouldInvokeRestrictBackground;
4170 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4171 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4172
4173 if (result.globalBatterySaverEnabled) {
4174 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4175 // turn it on.
4176 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4177 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4178 localRestrictBgChangedInBsm = false;
4179 } else {
4180 // Try to restore the restrictBackground if it doesn't change in bsm
4181 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4182 restrictBackground = mRestrictBackgroundBeforeBsm;
4183 }
4184
4185 if (shouldInvokeRestrictBackground) {
4186 setRestrictBackground(restrictBackground);
4187 }
4188
4189 // Change it at last so setRestrictBackground() won't affect this variable
4190 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4191 }
4192
Jeff Sharkey1b861272011-05-22 00:34:52 -07004193 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4194 final int size = source.size();
4195 for (int i = 0; i < size; i++) {
4196 target.put(source.keyAt(i), true);
4197 }
4198 }
4199
Stuart Scottf1fb3972015-04-02 18:00:02 -07004200 @Override
4201 public void factoryReset(String subscriber) {
4202 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4203
Stuart Scotte3e314d2015-04-20 14:07:45 -07004204 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4205 return;
4206 }
4207
Stuart Scottf1fb3972015-04-02 18:00:02 -07004208 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004209 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004210 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4211 for (NetworkPolicy policy : policies) {
4212 if (policy.template.equals(template)) {
4213 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4214 policy.inferred = false;
4215 policy.clearSnooze();
4216 }
4217 }
4218 setNetworkPolicies(policies);
4219
4220 // Turn restrict background data off
4221 setRestrictBackground(false);
4222
Stuart Scotte3e314d2015-04-20 14:07:45 -07004223 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4224 // Remove app's "restrict background data" flag
4225 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4226 setUidPolicy(uid, POLICY_NONE);
4227 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004228 }
4229 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004230
Felipe Lemed17fda42016-04-29 11:12:45 -07004231 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4232
4233 @Override
4234 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004235 synchronized (mUidRulesFirstLock) {
4236 boolean changed = removeUserStateUL(userId, false);
4237 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004238 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004239 synchronized (mNetworkPoliciesSecondLock) {
4240 writePolicyAL();
4241 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004242 }
4243 }
4244 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004245
4246 /**
4247 * @return true if the given uid is restricted from doing networking on metered networks.
4248 */
4249 @Override
4250 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4251 final int uidRules;
4252 final boolean isBackgroundRestricted;
4253 synchronized (mUidRulesFirstLock) {
4254 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4255 isBackgroundRestricted = mRestrictBackground;
4256 }
4257 return isBackgroundRestricted
4258 && !hasRule(uidRules, RULE_ALLOW_METERED)
4259 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4260 }
4261
4262 /**
4263 * @return true if networking is blocked on the given interface for the given uid according
4264 * to current networking policies.
4265 */
4266 @Override
4267 public boolean isUidNetworkingBlocked(int uid, String ifname) {
4268 final int uidRules;
4269 final boolean isBackgroundRestricted;
4270 final boolean isNetworkMetered;
4271 synchronized (mUidRulesFirstLock) {
4272 uidRules = mUidRules.get(uid, RULE_NONE);
4273 isBackgroundRestricted = mRestrictBackground;
4274 synchronized (mNetworkPoliciesSecondLock) {
4275 isNetworkMetered = mMeteredIfaces.contains(ifname);
4276 }
4277 }
4278 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4279 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4280 return true;
4281 }
4282 if (!isNetworkMetered) {
4283 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4284 return false;
4285 }
4286 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4287 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4288 return true;
4289 }
4290 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4291 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4292 return false;
4293 }
4294 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4295 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4296 return false;
4297 }
4298 if (isBackgroundRestricted) {
4299 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4300 return true;
4301 }
4302 if (LOGV) logUidStatus(uid, "allowed by default");
4303 return false;
4304 }
4305 }
4306
4307 private static boolean hasRule(int uidRules, int rule) {
4308 return (uidRules & rule) != 0;
4309 }
4310
4311 private static void logUidStatus(int uid, String descr) {
4312 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004313 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004314
4315 /**
4316 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4317 * (uid, procStateSeq) pairs.
4318 */
4319 @VisibleForTesting
4320 public static final class ProcStateSeqHistory {
4321 private static final int INVALID_UID = -1;
4322
4323 /**
4324 * Denotes maximum number of items this history can hold.
4325 */
4326 private final int mMaxCapacity;
4327 /**
4328 * Used for storing the uid information.
4329 */
4330 private final int[] mUids;
4331 /**
4332 * Used for storing the sequence numbers associated with {@link #mUids}.
4333 */
4334 private final long[] mProcStateSeqs;
4335 /**
4336 * Points to the next available slot for writing (uid, procStateSeq) pair.
4337 */
4338 private int mHistoryNext;
4339
4340 public ProcStateSeqHistory(int maxCapacity) {
4341 mMaxCapacity = maxCapacity;
4342 mUids = new int[mMaxCapacity];
4343 Arrays.fill(mUids, INVALID_UID);
4344 mProcStateSeqs = new long[mMaxCapacity];
4345 }
4346
4347 @GuardedBy("mUidRulesFirstLock")
4348 public void addProcStateSeqUL(int uid, long procStateSeq) {
4349 mUids[mHistoryNext] = uid;
4350 mProcStateSeqs[mHistoryNext] = procStateSeq;
4351 mHistoryNext = increaseNext(mHistoryNext, 1);
4352 }
4353
4354 @GuardedBy("mUidRulesFirstLock")
4355 public void dumpUL(IndentingPrintWriter fout) {
4356 if (mUids[0] == INVALID_UID) {
4357 fout.println("NONE");
4358 return;
4359 }
4360 int index = mHistoryNext;
4361 do {
4362 index = increaseNext(index, -1);
4363 if (mUids[index] == INVALID_UID) {
4364 break;
4365 }
4366 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4367 } while (index != mHistoryNext);
4368 }
4369
4370 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004371 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004372 }
4373
4374 private int increaseNext(int next, int increment) {
4375 next += increment;
4376 if (next >= mMaxCapacity) {
4377 next = 0;
4378 } else if (next < 0) {
4379 next = mMaxCapacity - 1;
4380 }
4381 return next;
4382 }
4383 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004384
4385 private class NotificationId {
4386 private final String mTag;
4387 private final int mId;
4388
4389 NotificationId(NetworkPolicy policy, int type) {
4390 mTag = buildNotificationTag(policy, type);
4391 mId = type;
4392 }
4393
4394 @Override
4395 public boolean equals(Object o) {
4396 if (this == o) return true;
4397 if (!(o instanceof NotificationId)) return false;
4398 NotificationId that = (NotificationId) o;
4399 return Objects.equals(mTag, that.mTag);
4400 }
4401
4402 @Override
4403 public int hashCode() {
4404 return Objects.hash(mTag);
4405 }
4406
4407 /**
4408 * Build unique tag that identifies an active {@link NetworkPolicy}
4409 * notification of a specific type, like {@link #TYPE_LIMIT}.
4410 */
4411 private String buildNotificationTag(NetworkPolicy policy, int type) {
4412 return TAG + ":" + policy.template.hashCode() + ":" + type;
4413 }
4414
4415 public String getTag() {
4416 return mTag;
4417 }
4418
4419 public int getId() {
4420 return mId;
4421 }
4422 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004423}