blob: f88a074ad132fa5a7de3e4421cf2a4bb07cfcc71 [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 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001268 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1269 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001270
1271 boolean policyUpdated = false;
1272 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1273
1274 // find and update the mobile NetworkPolicy for this subscriber id
1275 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1276 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1277 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1278 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1279 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001280 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1281 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001282 }
1283 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001284 return policyUpdated;
1285 }
1286
1287 /**
1288 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1289 *
1290 * It attempts to get an appropriate cycle day from the passed in CarrierConfig. If it's unable
1291 * to do so, it returns the fallback value.
1292 *
1293 * @param config The CarrierConfig to read the value from.
1294 * @param fallbackCycleDay to return if the CarrierConfig can't be read.
1295 * @return cycleDay to use in the mobile NetworkPolicy.
1296 */
1297 @VisibleForTesting
1298 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1299 int fallbackCycleDay) {
1300 if (config == null) {
1301 return fallbackCycleDay;
1302 }
1303 int cycleDay =
1304 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1305 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1306 return fallbackCycleDay;
1307 }
1308 // validate cycleDay value
1309 final Calendar cal = Calendar.getInstance();
1310 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1311 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1312 Slog.e(TAG, "Invalid date in "
1313 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1314 return fallbackCycleDay;
1315 }
1316 return cycleDay;
1317 }
1318
1319 /**
1320 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1321 *
1322 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1323 * to do so, it returns the fallback value.
1324 *
1325 * @param config The CarrierConfig to read the value from.
1326 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1327 * @return warningBytes to use in the mobile NetworkPolicy.
1328 */
1329 @VisibleForTesting
1330 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1331 long fallbackWarningBytes) {
1332 if (config == null) {
1333 return fallbackWarningBytes;
1334 }
1335 long warningBytes =
1336 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1337
1338 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1339 return WARNING_DISABLED;
1340 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1341 return getPlatformDefaultWarningBytes();
1342 } else if (warningBytes < 0) {
1343 Slog.e(TAG, "Invalid value in "
1344 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1345 + "non-negative value but got: " + warningBytes);
1346 return fallbackWarningBytes;
1347 }
1348
1349 return warningBytes;
1350 }
1351
1352 /**
1353 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1354 *
1355 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1356 * to do so, it returns the fallback value.
1357 *
1358 * @param config The CarrierConfig to read the value from.
1359 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1360 * @return limitBytes to use in the mobile NetworkPolicy.
1361 */
1362 @VisibleForTesting
1363 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1364 long fallbackLimitBytes) {
1365 if (config == null) {
1366 return fallbackLimitBytes;
1367 }
1368 long limitBytes =
1369 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1370
1371 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1372 return LIMIT_DISABLED;
1373 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1374 return getPlatformDefaultLimitBytes();
1375 } else if (limitBytes < 0) {
1376 Slog.e(TAG, "Invalid value in "
1377 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1378 + "non-negative value but got: " + limitBytes);
1379 return fallbackLimitBytes;
1380 }
1381 return limitBytes;
1382 }
1383
1384 /**
1385 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1386 */
1387 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1388 @Override
1389 public void onReceive(Context context, Intent intent) {
1390 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1391 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1392
1393 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1394 return;
1395 }
1396 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1397 final TelephonyManager tele = TelephonyManager.from(mContext);
1398 final String subscriberId = tele.getSubscriberId(subId);
1399
1400 maybeRefreshTrustedTime();
1401 synchronized (mUidRulesFirstLock) {
1402 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001403 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001404 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001405 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001406 if (!updated) return;
1407 // update network and notification rules, as the data cycle changed and it's
1408 // possible that we should be triggering warnings/limits now
1409 handleNetworkPoliciesUpdateAL(true);
1410 }
1411 }
1412 }
1413 };
1414
1415 /**
1416 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1417 * one has been updated.
1418 *
1419 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1420 * update.
1421 */
1422 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1423 if (shouldNormalizePolicies) {
1424 normalizePoliciesNL();
1425 }
1426 updateNetworkEnabledNL();
1427 updateNetworkRulesNL();
1428 updateNotificationsNL();
1429 writePolicyAL();
1430 }
1431
1432 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001433 * Proactively control network data connections when they exceed
1434 * {@link NetworkPolicy#limitBytes}.
1435 */
Felipe Lemef0823852016-06-08 13:43:08 -07001436 void updateNetworkEnabledNL() {
1437 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001438
1439 // TODO: reset any policy-disabled networks when any policy is removed
1440 // completely, which is currently rare case.
1441
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001442 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1443 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001444 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001445 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001446 setNetworkTemplateEnabled(policy.template, true);
1447 continue;
1448 }
1449
Jeff Sharkey53313d72017-07-13 16:47:32 -06001450 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1451 .cycleIterator(policy).next();
1452 final long start = cycle.first.toInstant().toEpochMilli();
1453 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001454 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001455
1456 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001457 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1458 && policy.lastLimitSnooze < start;
1459 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001460
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001461 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001462 }
1463 }
1464
1465 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001466 * Proactively disable networks that match the given
1467 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001468 */
1469 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001470 // TODO: reach into ConnectivityManager to proactively disable bringing
1471 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001472
1473 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1474 // If mobile data usage hits the limit or if the user resumes the data, we need to
1475 // notify telephony.
1476 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1477 final TelephonyManager tm = TelephonyManager.from(mContext);
1478
1479 final int[] subIds = sm.getActiveSubscriptionIdList();
1480 for (int subId : subIds) {
1481 final String subscriberId = tm.getSubscriberId(subId);
1482 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
1483 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
1484 // Template is matched when subscriber id matches.
1485 if (template.matches(probeIdent)) {
1486 tm.setPolicyDataEnabled(enabled, subId);
1487 }
1488 }
1489 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001490 }
1491
1492 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001493 * Examine all connected {@link NetworkState}, looking for
1494 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1495 * remaining quota based on usage cycle and historical stats.
1496 */
Felipe Lemef0823852016-06-08 13:43:08 -07001497 void updateNetworkRulesNL() {
1498 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001499
1500 final NetworkState[] states;
1501 try {
1502 states = mConnManager.getAllNetworkState();
1503 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001504 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001505 return;
1506 }
1507
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001508 // First, generate identities of all connected networks so we can
1509 // quickly compare them against all defined policies below.
1510 final ArrayList<Pair<String, NetworkIdentity>> connIdents = new ArrayList<>(states.length);
Dianne Hackborn497175b2014-07-01 12:56:08 -07001511 final ArraySet<String> connIfaces = new ArraySet<String>(states.length);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001512 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001513 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001514 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state);
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001515
1516 final String baseIface = state.linkProperties.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001517 if (baseIface != null) {
1518 connIdents.add(Pair.create(baseIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001519 }
1520
1521 // Stacked interfaces are considered to have same identity as
1522 // their parent network.
1523 final List<LinkProperties> stackedLinks = state.linkProperties.getStackedLinks();
1524 for (LinkProperties stackedLink : stackedLinks) {
1525 final String stackedIface = stackedLink.getInterfaceName();
Jeff Sharkey9da2f1e2014-08-14 12:55:00 -07001526 if (stackedIface != null) {
1527 connIdents.add(Pair.create(stackedIface, ident));
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001528 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001529 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001530 }
1531 }
1532
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001533 // Apply policies against all connected interfaces found above
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001534 mNetworkRules.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001535 final ArrayList<String> ifaceList = Lists.newArrayList();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001536 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001537 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001538
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001539 ifaceList.clear();
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001540 for (int j = connIdents.size() - 1; j >= 0; j--) {
1541 final Pair<String, NetworkIdentity> ident = connIdents.get(j);
1542 if (policy.template.matches(ident.second)) {
1543 ifaceList.add(ident.first);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001544 }
1545 }
1546
1547 if (ifaceList.size() > 0) {
1548 final String[] ifaces = ifaceList.toArray(new String[ifaceList.size()]);
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001549 mNetworkRules.put(policy, ifaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001550 }
1551 }
1552
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001553 long lowestRule = Long.MAX_VALUE;
Dianne Hackborn497175b2014-07-01 12:56:08 -07001554 final ArraySet<String> newMeteredIfaces = new ArraySet<String>(states.length);
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001555
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001556 // apply each policy that we found ifaces for; compute remaining data
1557 // based on current cycle and historical stats, and push to kernel.
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001558 for (int i = mNetworkRules.size()-1; i >= 0; i--) {
1559 final NetworkPolicy policy = mNetworkRules.keyAt(i);
1560 final String[] ifaces = mNetworkRules.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001561
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001562 if (LOGD) {
Felipe Leme03e689d2016-03-02 16:17:38 -08001563 Slog.d(TAG, "applying policy " + policy + " to ifaces " + Arrays.toString(ifaces));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001564 }
1565
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001566 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001567 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001568 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001569 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001570 if (hasLimit && policy.hasCycle()) {
1571 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1572 .cycleIterator(policy).next();
1573 final long start = cycle.first.toInstant().toEpochMilli();
1574 final long end = cycle.second.toInstant().toEpochMilli();
1575 final long totalBytes = getTotalBytes(policy.template, start, end);
1576
1577 if (policy.lastLimitSnooze >= start) {
1578 // snoozing past quota, but we still need to restrict apps,
1579 // so push really high quota.
1580 quotaBytes = Long.MAX_VALUE;
1581 } else {
1582 // remaining "quota" bytes are based on total usage in
1583 // current cycle. kernel doesn't like 0-byte rules, so we
1584 // set 1-byte quota and disable the radio later.
1585 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1586 }
1587 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001588 // metered network, but no policy limit; we still need to
1589 // restrict apps, so push really high quota.
1590 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001591 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001592
1593 if (ifaces.length > 1) {
1594 // TODO: switch to shared quota once NMS supports
1595 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001596 }
1597
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001598 for (String iface : ifaces) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001599 // long quotaBytes split up into two ints to fit in message
1600 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1601 (int) (quotaBytes >> 32), (int) (quotaBytes & 0xFFFFFFFF), iface)
1602 .sendToTarget();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001603 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001604 }
1605 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001606
1607 // keep track of lowest warning or limit of active policies
1608 if (hasWarning && policy.warningBytes < lowestRule) {
1609 lowestRule = policy.warningBytes;
1610 }
1611 if (hasLimit && policy.limitBytes < lowestRule) {
1612 lowestRule = policy.limitBytes;
1613 }
1614 }
1615
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001616 for (int i = connIfaces.size()-1; i >= 0; i--) {
1617 String iface = connIfaces.valueAt(i);
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001618 // long quotaBytes split up into two ints to fit in message
1619 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA,
1620 (int) (Long.MAX_VALUE >> 32), (int) (Long.MAX_VALUE & 0xFFFFFFFF), iface)
1621 .sendToTarget();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001622 newMeteredIfaces.add(iface);
1623 }
1624
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07001625 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001626
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001627 // remove quota on any trailing interfaces
Dianne Hackborn497175b2014-07-01 12:56:08 -07001628 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1629 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001630 if (!newMeteredIfaces.contains(iface)) {
Amith Yamasani3646cbd2016-04-13 14:04:53 -07001631 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface)
1632 .sendToTarget();
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001633 }
1634 }
1635 mMeteredIfaces = newMeteredIfaces;
1636
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001637 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001638 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001639 }
1640
1641 /**
1642 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1643 * have at least a default mobile policy defined.
1644 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001645 private void ensureActiveMobilePolicyAL() {
1646 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001647 if (mSuppressDefaultPolicy) return;
1648
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001649 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001650 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001651
Jeff Sharkey32566012014-12-02 18:30:14 -08001652 final int[] subIds = sub.getActiveSubscriptionIdList();
1653 for (int subId : subIds) {
1654 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001655 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001656 }
1657 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001658
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001659 /**
1660 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1661 * have at least a default mobile policy defined.
1662 *
1663 * @param subId to build a default policy for
1664 * @param subscriberId that we check for an existing policy
1665 * @return true if a mobile network policy was added, or false one already existed.
1666 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001667 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001668 // Poke around to see if we already have a policy
1669 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Jack Yu66a6be32016-03-30 11:14:39 -07001670 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001671 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1672 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1673 if (template.matches(probeIdent)) {
1674 if (LOGD) {
1675 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1676 + NetworkIdentity.scrubSubscriberId(subscriberId));
1677 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001678 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001679 }
1680 }
1681
Jeff Sharkey32566012014-12-02 18:30:14 -08001682 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1683 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001684 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001685 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001686 return true;
1687 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001688
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001689 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001690 final int dataWarningConfig = mContext.getResources().getInteger(
1691 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001692 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001693 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001694 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001695 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001696 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001697 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001698
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001699 private long getPlatformDefaultLimitBytes() {
1700 return LIMIT_DISABLED;
1701 }
1702
1703 @VisibleForTesting
1704 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001705 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001706 final RecurrenceRule cycleRule = NetworkPolicy
1707 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001708 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001709 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1710 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1711 synchronized (mUidRulesFirstLock) {
1712 synchronized (mNetworkPoliciesSecondLock) {
1713 updateDefaultMobilePolicyAL(subId, policy);
1714 }
1715 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001716 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001717 }
1718
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001719 /**
1720 * Update the given {@link NetworkPolicy} based on any carrier-provided
1721 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1722 * Leaves policy untouched if the user has modified it.
1723 *
1724 * @return if the policy was modified
1725 */
1726 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1727 if (!policy.inferred) {
1728 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1729 return false;
1730 }
1731
1732 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1733 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1734 policy.lastLimitSnooze, policy.metered, policy.inferred);
1735
1736 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1737 if (!ArrayUtils.isEmpty(plans)) {
1738 final SubscriptionPlan plan = plans[0];
1739 policy.cycleRule = plan.getCycleRule();
1740 final long planLimitBytes = plan.getDataLimitBytes();
1741 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1742 policy.warningBytes = getPlatformDefaultWarningBytes();
1743 policy.limitBytes = getPlatformDefaultLimitBytes();
1744 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1745 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1746 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1747 } else {
1748 policy.warningBytes = (planLimitBytes * 9) / 10;
1749 switch (plan.getDataLimitBehavior()) {
1750 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1751 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1752 policy.limitBytes = planLimitBytes;
1753 break;
1754 default:
1755 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1756 break;
1757 }
1758 }
1759 } else {
1760 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1761 final int currentCycleDay;
1762 if (policy.cycleRule.isMonthly()) {
1763 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1764 } else {
1765 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1766 }
1767 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1768 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1769 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1770 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1771 }
1772
1773 if (policy.equals(original)) {
1774 return false;
1775 } else {
1776 Slog.d(TAG, "Updated " + original + " to " + policy);
1777 return true;
1778 }
1779 }
1780
Felipe Lemef0823852016-06-08 13:43:08 -07001781 private void readPolicyAL() {
1782 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001783
1784 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001785 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001786 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001787 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001788 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001789
1790 FileInputStream fis = null;
1791 try {
1792 fis = mPolicyFile.openRead();
1793 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001794 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001795
Felipe Leme46b451f2016-08-19 08:46:17 -07001796 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1797 // to skip UIDs that were explicitly blacklisted.
1798 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1799
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001800 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001801 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001802 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001803 while ((type = in.next()) != END_DOCUMENT) {
1804 final String tag = in.getName();
1805 if (type == START_TAG) {
1806 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001807 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001808 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001809 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1810 mRestrictBackground = readBooleanAttribute(
1811 in, ATTR_RESTRICT_BACKGROUND);
1812 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001813 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001814 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001815 if (mRestrictBackground != oldValue) {
1816 // Some early services may have read the default value,
1817 // so notify them that it's changed
1818 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1819 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1820 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001821
1822 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1823 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1824 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001825 final String networkId;
1826 if (version >= VERSION_ADDED_NETWORK_ID) {
1827 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1828 } else {
1829 networkId = null;
1830 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001831 final RecurrenceRule cycleRule;
1832 if (version >= VERSION_ADDED_CYCLE) {
1833 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1834 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1835 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1836 cycleRule = new RecurrenceRule(
1837 RecurrenceRule.convertZonedDateTime(start),
1838 RecurrenceRule.convertZonedDateTime(end),
1839 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001840 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001841 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1842 final String cycleTimezone;
1843 if (version >= VERSION_ADDED_TIMEZONE) {
1844 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1845 } else {
1846 cycleTimezone = "UTC";
1847 }
1848 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001849 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001850 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1851 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001852 final long lastLimitSnooze;
1853 if (version >= VERSION_SPLIT_SNOOZE) {
1854 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1855 } else if (version >= VERSION_ADDED_SNOOZE) {
1856 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001857 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001858 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001859 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001860 final boolean metered;
1861 if (version >= VERSION_ADDED_METERED) {
1862 metered = readBooleanAttribute(in, ATTR_METERED);
1863 } else {
1864 switch (networkTemplate) {
1865 case MATCH_MOBILE_3G_LOWER:
1866 case MATCH_MOBILE_4G:
1867 case MATCH_MOBILE_ALL:
1868 metered = true;
1869 break;
1870 default:
1871 metered = false;
1872 }
1873 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001874 final long lastWarningSnooze;
1875 if (version >= VERSION_SPLIT_SNOOZE) {
1876 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1877 } else {
1878 lastWarningSnooze = SNOOZE_NEVER;
1879 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001880 final boolean inferred;
1881 if (version >= VERSION_ADDED_INFERRED) {
1882 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1883 } else {
1884 inferred = false;
1885 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001886
Jeff Sharkey32566012014-12-02 18:30:14 -08001887 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1888 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001889 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001890 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1891 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001892 lastLimitSnooze, metered, inferred));
1893 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001894
1895 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1896 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1897 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1898 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1899 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1900 RecurrenceRule.convertZonedDateTime(start),
1901 RecurrenceRule.convertZonedDateTime(end),
1902 RecurrenceRule.convertPeriod(period));
1903 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1904 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1905
1906 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1907 SubscriptionPlan.BYTES_UNKNOWN);
1908 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1909 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1910 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1911 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1912 builder.setDataLimit(limitBytes, limitBehavior);
1913 }
1914
1915 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1916 SubscriptionPlan.BYTES_UNKNOWN);
1917 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1918 SubscriptionPlan.TIME_UNKNOWN);
1919 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1920 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1921 builder.setDataUsage(usageBytes, usageTime);
1922 }
1923
1924 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1925 final SubscriptionPlan plan = builder.build();
1926 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1927 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1928
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001929 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1930 mSubscriptionPlansOwner.put(subId, ownerPackage);
1931
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001932 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001933 final int uid = readIntAttribute(in, ATTR_UID);
1934 final int policy = readIntAttribute(in, ATTR_POLICY);
1935
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001936 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001937 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001938 } else {
1939 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1940 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001941 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001942 final int appId = readIntAttribute(in, ATTR_APP_ID);
1943 final int policy = readIntAttribute(in, ATTR_POLICY);
1944
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001945 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001946 // app policy is deprecated so this is only used in pre system user split.
1947 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001948 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001949 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001950 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001951 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001952 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001953 } else if (TAG_WHITELIST.equals(tag)) {
1954 insideWhitelist = true;
1955 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1956 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001957 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001958 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1959 final int uid = readIntAttribute(in, ATTR_UID);
1960 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001962 } else if (type == END_TAG) {
1963 if (TAG_WHITELIST.equals(tag)) {
1964 insideWhitelist = false;
1965 }
1966
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001967 }
1968 }
1969
Felipe Leme46b451f2016-08-19 08:46:17 -07001970 final int size = whitelistedRestrictBackground.size();
1971 for (int i = 0; i < size; i++) {
1972 final int uid = whitelistedRestrictBackground.keyAt(i);
1973 final int policy = mUidPolicy.get(uid, POLICY_NONE);
1974 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
1975 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
1976 + " because its policy is " + uidPoliciesToString(policy));
1977 continue;
1978 }
1979 if (UserHandle.isApp(uid)) {
1980 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
1981 if (LOGV)
1982 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
1983 setUidPolicyUncheckedUL(uid, newPolicy, false);
1984 } else {
1985 Slog.w(TAG, "unable to update policy on UID " + uid);
1986 }
1987 }
1988
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001989 } catch (FileNotFoundException e) {
1990 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01001991 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001992 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001993 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001994 } finally {
1995 IoUtils.closeQuietly(fis);
1996 }
1997 }
1998
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001999 /**
2000 * Upgrade legacy background data flags, notifying listeners of one last
2001 * change to always-true.
2002 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002003 private void upgradeDefaultBackgroundDataUL() {
2004 // This method is only called when we're unable to find the network policy flag, which
2005 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002006
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002007 // Seed from the default value configured for this device.
2008 mRestrictBackground = Settings.Global.getInt(
2009 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2010
2011 // NOTE: We used to read the legacy setting here :
2012 //
2013 // final int legacyFlagValue = Settings.Secure.getInt(
2014 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2015 //
2016 // This is no longer necessary because we will never upgrade directly from Gingerbread
2017 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2018 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002019 }
2020
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002021 /**
2022 * Perform upgrade step of moving any user-defined meterness overrides over
2023 * into {@link WifiConfiguration}.
2024 */
2025 private void upgradeWifiMeteredOverrideAL() {
2026 boolean modified = false;
2027 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2028 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2029 for (int i = 0; i < mNetworkPolicy.size(); ) {
2030 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2031 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2032 && !policy.inferred) {
2033 mNetworkPolicy.removeAt(i);
2034 modified = true;
2035
2036 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2037 for (WifiConfiguration config : configs) {
2038 if (Objects.equals(resolveNetworkId(config), networkId)) {
2039 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2040 config.meteredOverride = policy.metered
2041 ? WifiConfiguration.METERED_OVERRIDE_METERED
2042 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2043 wm.updateNetwork(config);
2044 }
2045 }
2046 } else {
2047 i++;
2048 }
2049 }
2050 if (modified) {
2051 writePolicyAL();
2052 }
2053 }
2054
Felipe Lemef0823852016-06-08 13:43:08 -07002055 void writePolicyAL() {
2056 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002057
2058 FileOutputStream fos = null;
2059 try {
2060 fos = mPolicyFile.startWrite();
2061
2062 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002063 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002064 out.startDocument(null, true);
2065
2066 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002067 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002068 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002069
2070 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002071 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2072 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002073 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002074 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002075
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002076 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002077 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2078 final String subscriberId = template.getSubscriberId();
2079 if (subscriberId != null) {
2080 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002081 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002082 final String networkId = template.getNetworkId();
2083 if (networkId != null) {
2084 out.attribute(null, ATTR_NETWORK_ID, networkId);
2085 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002086 writeStringAttribute(out, ATTR_CYCLE_START,
2087 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2088 writeStringAttribute(out, ATTR_CYCLE_END,
2089 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2090 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2091 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002092 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2093 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002094 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2095 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002096 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002097 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002098 out.endTag(null, TAG_NETWORK_POLICY);
2099 }
2100
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002101 // write all known subscription plans
2102 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2103 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002104 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002105 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2106 if (ArrayUtils.isEmpty(plans)) continue;
2107
2108 for (SubscriptionPlan plan : plans) {
2109 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2110 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002111 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002112 final RecurrenceRule cycleRule = plan.getCycleRule();
2113 writeStringAttribute(out, ATTR_CYCLE_START,
2114 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2115 writeStringAttribute(out, ATTR_CYCLE_END,
2116 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2117 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2118 RecurrenceRule.convertPeriod(cycleRule.period));
2119 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2120 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2121 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2122 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2123 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2124 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2125 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2126 }
2127 }
2128
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002129 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002130 for (int i = 0; i < mUidPolicy.size(); i++) {
2131 final int uid = mUidPolicy.keyAt(i);
2132 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002133
Jeff Sharkey497e4432011-06-14 17:27:29 -07002134 // skip writing empty policies
2135 if (policy == POLICY_NONE) continue;
2136
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002137 out.startTag(null, TAG_UID_POLICY);
2138 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002139 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002140 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002141 }
2142
2143 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002144
2145 // write all whitelists
2146 out.startTag(null, TAG_WHITELIST);
2147
Felipe Lemea9505cc2016-02-26 10:28:41 -08002148 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002149 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002150 for (int i = 0; i < size; i++) {
2151 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2152 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2153 writeIntAttribute(out, ATTR_UID, uid);
2154 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2155 }
2156
Felipe Lemeb85a6372016-01-14 16:16:16 -08002157 out.endTag(null, TAG_WHITELIST);
2158
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002159 out.endDocument();
2160
2161 mPolicyFile.finishWrite(fos);
2162 } catch (IOException e) {
2163 if (fos != null) {
2164 mPolicyFile.failWrite(fos);
2165 }
2166 }
2167 }
2168
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002169 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002170 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002171 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002172
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002173 if (!UserHandle.isApp(uid)) {
2174 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002175 }
Felipe Lemef0823852016-06-08 13:43:08 -07002176 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002177 final long token = Binder.clearCallingIdentity();
2178 try {
2179 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2180 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002181 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002182 }
2183 } finally {
2184 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002185 }
2186 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002187 }
2188
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002189 @Override
2190 public void addUidPolicy(int uid, int policy) {
2191 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002192
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002193 if (!UserHandle.isApp(uid)) {
2194 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2195 }
2196
Felipe Lemef0823852016-06-08 13:43:08 -07002197 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002198 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2199 policy |= oldPolicy;
2200 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002201 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002202 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002203 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002204 }
2205
2206 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002207 public void removeUidPolicy(int uid, int policy) {
2208 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2209
2210 if (!UserHandle.isApp(uid)) {
2211 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2212 }
2213
Felipe Lemef0823852016-06-08 13:43:08 -07002214 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002215 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2216 policy = oldPolicy & ~policy;
2217 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002218 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002219 }
2220 }
2221 }
2222
Felipe Lemef0823852016-06-08 13:43:08 -07002223 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2224 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002225
Felipe Leme57e3d312016-08-23 14:42:52 -07002226 final boolean notifyApp;
2227 if (!isUidValidForWhitelistRules(uid)) {
2228 notifyApp = false;
2229 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002230 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2231 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2232 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2233 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002234 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2235 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002236 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2237 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2238 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2239 if (LOGD)
2240 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2241 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2242 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002243 notifyApp = wasBlocked != isBlocked;
2244 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002245 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2246 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002247 }
2248
Felipe Lemef0823852016-06-08 13:43:08 -07002249 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002250 if (policy == POLICY_NONE) {
2251 mUidPolicy.delete(uid);
2252 } else {
2253 mUidPolicy.put(uid, policy);
2254 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002255
2256 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002257 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002258 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002259 synchronized (mNetworkPoliciesSecondLock) {
2260 writePolicyAL();
2261 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002262 }
2263 }
2264
2265 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002266 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002267 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2268
Felipe Lemef0823852016-06-08 13:43:08 -07002269 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002270 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002271 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002272 }
2273
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002274 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002275 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002276 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2277
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002278 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002279 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002280 for (int i = 0; i < mUidPolicy.size(); i++) {
2281 final int uid = mUidPolicy.keyAt(i);
2282 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002283 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2284 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002285 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002286 }
2287 }
2288 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002289 return uids;
2290 }
2291
2292 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002293 * Removes any persistable state associated with given {@link UserHandle}, persisting
2294 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002295 */
Felipe Lemef0823852016-06-08 13:43:08 -07002296 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002297
Felipe Lemef0823852016-06-08 13:43:08 -07002298 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002299 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002300
Felipe Lemea110eec2016-04-29 09:58:06 -07002301 // Remove entries from revoked default restricted background UID whitelist
2302 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2303 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2304 if (UserHandle.getUserId(uid) == userId) {
2305 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002306 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002307 }
2308 }
2309
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002310 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002311 int[] uids = new int[0];
2312 for (int i = 0; i < mUidPolicy.size(); i++) {
2313 final int uid = mUidPolicy.keyAt(i);
2314 if (UserHandle.getUserId(uid) == userId) {
2315 uids = appendInt(uids, uid);
2316 }
2317 }
2318
2319 if (uids.length > 0) {
2320 for (int uid : uids) {
2321 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002322 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002323 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002324 }
Felipe Lemef0823852016-06-08 13:43:08 -07002325 synchronized (mNetworkPoliciesSecondLock) {
2326 updateRulesForGlobalChangeAL(true);
2327 if (writePolicy && changed) {
2328 writePolicyAL();
2329 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002330 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002331 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002332 }
2333
2334 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002335 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002336 // TODO: create permission for observing network policy
2337 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002338 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002339 }
2340
2341 @Override
2342 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002343 // TODO: create permission for observing network policy
2344 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002345 mListeners.unregister(listener);
2346 }
2347
Jeff Sharkey1b861272011-05-22 00:34:52 -07002348 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002349 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002350 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2351
Felipe Leme6a05eee2016-02-19 14:43:51 -08002352 final long token = Binder.clearCallingIdentity();
2353 try {
2354 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002355 synchronized (mUidRulesFirstLock) {
2356 synchronized (mNetworkPoliciesSecondLock) {
2357 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002358 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002359 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002360 }
2361 } finally {
2362 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002363 }
2364 }
2365
Hugo Benichi446c9c92017-04-10 09:41:10 +09002366 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002367 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002368 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2369 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002370 }
2371
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002372 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002373 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002374 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002375 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002376 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2377 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2378 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002379 } catch (SecurityException e) {
2380 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002381
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002382 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2383 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2384 return new NetworkPolicy[0];
2385 }
Svet Ganov16a16892015-04-16 10:32:04 -07002386 }
2387
Felipe Lemef0823852016-06-08 13:43:08 -07002388 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002389 final int size = mNetworkPolicy.size();
2390 final NetworkPolicy[] policies = new NetworkPolicy[size];
2391 for (int i = 0; i < size; i++) {
2392 policies[i] = mNetworkPolicy.valueAt(i);
2393 }
2394 return policies;
2395 }
2396 }
2397
Felipe Lemef0823852016-06-08 13:43:08 -07002398 private void normalizePoliciesNL() {
2399 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002400 }
2401
Felipe Lemef0823852016-06-08 13:43:08 -07002402 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002403 final TelephonyManager tele = TelephonyManager.from(mContext);
2404 final String[] merged = tele.getMergedSubscriberIds();
2405
2406 mNetworkPolicy.clear();
2407 for (NetworkPolicy policy : policies) {
2408 // When two normalized templates conflict, prefer the most
2409 // restrictive policy
2410 policy.template = NetworkTemplate.normalize(policy.template, merged);
2411 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2412 if (existing == null || existing.compareTo(policy) > 0) {
2413 if (existing != null) {
2414 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2415 }
2416 mNetworkPolicy.put(policy.template, policy);
2417 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002418 }
2419 }
2420
2421 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002422 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002423 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002424
2425 final long token = Binder.clearCallingIdentity();
2426 try {
2427 performSnooze(template, TYPE_LIMIT);
2428 } finally {
2429 Binder.restoreCallingIdentity(token);
2430 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002431 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002432
Dianne Hackborn497175b2014-07-01 12:56:08 -07002433 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002434 maybeRefreshTrustedTime();
2435 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002436 synchronized (mUidRulesFirstLock) {
2437 synchronized (mNetworkPoliciesSecondLock) {
2438 // find and snooze local policy that matches
2439 final NetworkPolicy policy = mNetworkPolicy.get(template);
2440 if (policy == null) {
2441 throw new IllegalArgumentException("unable to find policy for " + template);
2442 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002443
Felipe Lemef0823852016-06-08 13:43:08 -07002444 switch (type) {
2445 case TYPE_WARNING:
2446 policy.lastWarningSnooze = currentTime;
2447 break;
2448 case TYPE_LIMIT:
2449 policy.lastLimitSnooze = currentTime;
2450 break;
2451 default:
2452 throw new IllegalArgumentException("unexpected type");
2453 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002454
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002455 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002456 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002457 }
2458 }
2459
2460 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002461 public void onTetheringChanged(String iface, boolean tethering) {
2462 // No need to enforce permission because setRestrictBackground() will do it.
2463 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002464 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002465 if (mRestrictBackground && tethering) {
2466 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2467 setRestrictBackground(false);
2468 }
2469 }
2470 }
2471
2472 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002473 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002474 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002475 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002476 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2477 final long token = Binder.clearCallingIdentity();
2478 try {
2479 maybeRefreshTrustedTime();
2480 synchronized (mUidRulesFirstLock) {
2481 if (restrictBackground == mRestrictBackground) {
2482 // Ideally, UI should never allow this scenario...
2483 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2484 return;
2485 }
2486 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002487 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002488
2489 } finally {
2490 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002491 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002492
Felipe Leme29e72ea2016-09-08 13:26:55 -07002493 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2494 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002495 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002496 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002497 }
2498 }
2499
Felipe Lemef0823852016-06-08 13:43:08 -07002500 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002501 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002502 final boolean oldRestrictBackground = mRestrictBackground;
2503 mRestrictBackground = restrictBackground;
2504 // Must whitelist foreground apps before turning data saver mode on.
2505 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2506 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002507 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002508 try {
2509 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2510 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2511 mRestrictBackground = oldRestrictBackground;
2512 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002513 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002514 return;
2515 }
2516 } catch (RemoteException e) {
2517 // ignored; service lives in system_server
2518 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002519
2520 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2521 mRestrictBackgroundChangedInBsm = true;
2522 }
Felipe Lemef0823852016-06-08 13:43:08 -07002523 synchronized (mNetworkPoliciesSecondLock) {
2524 updateNotificationsNL();
2525 writePolicyAL();
2526 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002527 }
2528
Felipe Lemeb85a6372016-01-14 16:16:16 -08002529 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002530 public int getRestrictBackgroundByCaller() {
2531 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2532 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002533
Felipe Lemef0823852016-06-08 13:43:08 -07002534 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002535 // Must clear identity because getUidPolicy() is restricted to system.
2536 final long token = Binder.clearCallingIdentity();
2537 final int policy;
2538 try {
2539 policy = getUidPolicy(uid);
2540 } finally {
2541 Binder.restoreCallingIdentity(token);
2542 }
2543 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2544 // App is blacklisted.
2545 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2546 }
Felipe Leme1b103232016-01-22 09:44:57 -08002547 if (!mRestrictBackground) {
2548 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2549 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002550 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002551 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2552 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2553 }
2554 }
2555
2556 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002557 public boolean getRestrictBackground() {
2558 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2559
Felipe Lemef0823852016-06-08 13:43:08 -07002560 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002561 return mRestrictBackground;
2562 }
2563 }
2564
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002565 @Override
2566 public void setDeviceIdleMode(boolean enabled) {
2567 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002568 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2569 try {
2570 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002571 if (mDeviceIdleMode == enabled) {
2572 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002573 }
Felipe Lemeea014392016-09-06 13:59:54 -07002574 mDeviceIdleMode = enabled;
2575 if (mSystemReady) {
2576 // Device idle change means we need to rebuild rules for all
2577 // known apps, so do a global refresh.
2578 updateRulesForRestrictPowerUL();
2579 }
2580 }
2581 if (enabled) {
2582 EventLogTags.writeDeviceIdleOnPhase("net");
2583 } else {
2584 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002585 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002586 } finally {
2587 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002588 }
2589 }
2590
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002591 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002592 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2593 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002594 final long token = Binder.clearCallingIdentity();
2595 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002596 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2597 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2598 for (WifiConfiguration config : configs) {
2599 if (Objects.equals(resolveNetworkId(config), networkId)) {
2600 config.meteredOverride = meteredOverride;
2601 wm.updateNetwork(config);
2602 }
2603 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002604 } finally {
2605 Binder.restoreCallingIdentity(token);
2606 }
2607 }
2608
Jeff Sharkey46645002011-07-27 21:11:21 -07002609 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002610 @Deprecated
2611 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2612 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2613 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2614 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002615 }
2616
Jeff Sharkey53313d72017-07-13 16:47:32 -06002617 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2618 // Verify they're not lying about package name
2619 mAppOps.checkPackage(callingUid, callingPackage);
2620
Jeff Sharkey53313d72017-07-13 16:47:32 -06002621 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002622 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002623 final long token = Binder.clearCallingIdentity();
2624 try {
2625 si = mContext.getSystemService(SubscriptionManager.class)
2626 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002627 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002628 } finally {
2629 Binder.restoreCallingIdentity(token);
2630 }
2631
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002632 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002633 if (si != null) {
2634 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2635 return;
2636 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002637 }
2638
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002639 // Second check: has the CarrierService delegated access?
2640 if (config != null) {
2641 final String overridePackage = config
2642 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2643 if (!TextUtils.isEmpty(overridePackage)
2644 && Objects.equals(overridePackage, callingPackage)) {
2645 return;
2646 }
2647 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002648
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002649 // Third check: is caller the fallback/default CarrierService?
2650 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2651 if (!TextUtils.isEmpty(defaultPackage)
2652 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002653 return;
2654 }
2655
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002656 // Final check: does the caller hold a permission?
2657 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002658 }
2659
2660 @Override
2661 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2662 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2663
Jeff Sharkey53313d72017-07-13 16:47:32 -06002664 final String fake = SystemProperties.get("fw.fake_plan");
2665 if (!TextUtils.isEmpty(fake)) {
2666 final List<SubscriptionPlan> plans = new ArrayList<>();
2667 if ("month_hard".equals(fake)) {
2668 plans.add(SubscriptionPlan.Builder
2669 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2670 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002671 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2672 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2673 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2674 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2675 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002676 plans.add(SubscriptionPlan.Builder
2677 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2678 .setTitle("G-Mobile Happy")
2679 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2680 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2681 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2682 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2683 .build());
2684 plans.add(SubscriptionPlan.Builder
2685 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2686 .setTitle("G-Mobile, Charged after limit")
2687 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2688 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2689 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2690 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2691 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002692 } else if ("month_soft".equals(fake)) {
2693 plans.add(SubscriptionPlan.Builder
2694 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2695 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2696 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2697 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002698 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2699 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2700 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2701 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2702 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002703 plans.add(SubscriptionPlan.Builder
2704 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2705 .setTitle("G-Mobile, Throttled after limit")
2706 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2707 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2708 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2709 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2710 .build());
2711 plans.add(SubscriptionPlan.Builder
2712 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2713 .setTitle("G-Mobile, No data connection after limit")
2714 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2715 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2716 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2717 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2718 .build());
2719
Jeff Sharkey53313d72017-07-13 16:47:32 -06002720 } else if ("month_none".equals(fake)) {
2721 plans.add(SubscriptionPlan.Builder
2722 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2723 .setTitle("G-Mobile")
2724 .build());
2725 } else if ("prepaid".equals(fake)) {
2726 plans.add(SubscriptionPlan.Builder
2727 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2728 ZonedDateTime.now().plusDays(10))
2729 .setTitle("G-Mobile")
2730 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2731 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2732 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2733 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2734 .build());
2735 } else if ("prepaid_crazy".equals(fake)) {
2736 plans.add(SubscriptionPlan.Builder
2737 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2738 ZonedDateTime.now().plusDays(10))
2739 .setTitle("G-Mobile Anytime")
2740 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2741 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2742 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2743 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2744 .build());
2745 plans.add(SubscriptionPlan.Builder
2746 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2747 ZonedDateTime.now().plusDays(20))
2748 .setTitle("G-Mobile Nickel Nights")
2749 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002750 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2751 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002752 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2753 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2754 .build());
2755 plans.add(SubscriptionPlan.Builder
2756 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2757 ZonedDateTime.now().plusDays(20))
2758 .setTitle("G-Mobile Bonus 3G")
2759 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002760 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002761 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2762 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2763 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2764 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002765 } else if ("unlimited".equals(fake)) {
2766 plans.add(SubscriptionPlan.Builder
2767 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2768 ZonedDateTime.now().plusDays(10))
2769 .setTitle("G-Mobile Awesome")
2770 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2771 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2772 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2773 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2774 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002775 }
2776 return plans.toArray(new SubscriptionPlan[plans.size()]);
2777 }
2778
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002779 synchronized (mUidRulesFirstLock) {
2780 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002781 // Only give out plan details to the package that defined them,
2782 // so that we don't risk leaking plans between apps. We always
2783 // let in core system components (like the Settings app).
2784 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2785 if (Objects.equals(ownerPackage, callingPackage)
2786 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2787 return mSubscriptionPlans.get(subId);
2788 } else {
2789 Log.w(TAG, "Not returning plans because caller " + callingPackage
2790 + " doesn't match owner " + ownerPackage);
2791 return null;
2792 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002793 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002794 }
2795 }
2796
2797 @Override
2798 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2799 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2800
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002801 for (SubscriptionPlan plan : plans) {
2802 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002803 }
2804
2805 final long token = Binder.clearCallingIdentity();
2806 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002807 maybeRefreshTrustedTime();
2808 synchronized (mUidRulesFirstLock) {
2809 synchronized (mNetworkPoliciesSecondLock) {
2810 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002811 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002812
2813 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2814 .getSubscriberId(subId);
2815 ensureActiveMobilePolicyAL(subId, subscriberId);
2816 maybeUpdateMobilePolicyCycleAL(subId);
2817 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002818 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002819 }
2820 } finally {
2821 Binder.restoreCallingIdentity(token);
2822 }
2823 }
2824
2825 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002826 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002827 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002828
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002829 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2830
Dianne Hackborn497175b2014-07-01 12:56:08 -07002831 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002832 for (String arg : args) {
2833 argSet.add(arg);
2834 }
2835
Felipe Lemef0823852016-06-08 13:43:08 -07002836 synchronized (mUidRulesFirstLock) {
2837 synchronized (mNetworkPoliciesSecondLock) {
2838 if (argSet.contains("--unsnooze")) {
2839 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2840 mNetworkPolicy.valueAt(i).clearSnooze();
2841 }
2842
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002843 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002844
2845 fout.println("Cleared snooze timestamps");
2846 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002847 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002848
Felipe Lemef0823852016-06-08 13:43:08 -07002849 fout.print("System ready: "); fout.println(mSystemReady);
2850 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2851 fout.print("Restrict power: "); fout.println(mRestrictPower);
2852 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002853 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2854
2855 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002856 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002857 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002858 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2859 fout.println(mNetworkPolicy.valueAt(i).toString());
2860 }
2861 fout.decreaseIndent();
2862
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002863 fout.println();
2864 fout.println("Subscription plans:");
2865 fout.increaseIndent();
2866 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2867 final int subId = mSubscriptionPlans.keyAt(i);
2868 fout.println("Subscriber ID " + subId + ":");
2869 fout.increaseIndent();
2870 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2871 if (!ArrayUtils.isEmpty(plans)) {
2872 for (SubscriptionPlan plan : plans) {
2873 fout.println(plan);
2874 }
2875 }
2876 fout.decreaseIndent();
2877 }
2878 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002879
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002880 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002881 fout.println("Policy for UIDs:");
2882 fout.increaseIndent();
2883 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002884 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002885 final int uid = mUidPolicy.keyAt(i);
2886 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002887 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002888 fout.print(uid);
2889 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002890 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002891 fout.println();
2892 }
2893 fout.decreaseIndent();
2894
2895 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2896 if (size > 0) {
2897 fout.println("Power save whitelist (except idle) app ids:");
2898 fout.increaseIndent();
2899 for (int i = 0; i < size; i++) {
2900 fout.print("UID=");
2901 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2902 fout.print(": ");
2903 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2904 fout.println();
2905 }
2906 fout.decreaseIndent();
2907 }
2908
2909 size = mPowerSaveWhitelistAppIds.size();
2910 if (size > 0) {
2911 fout.println("Power save whitelist app ids:");
2912 fout.increaseIndent();
2913 for (int i = 0; i < size; i++) {
2914 fout.print("UID=");
2915 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2916 fout.print(": ");
2917 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2918 fout.println();
2919 }
2920 fout.decreaseIndent();
2921 }
2922
Felipe Lemef0823852016-06-08 13:43:08 -07002923 size = mDefaultRestrictBackgroundWhitelistUids.size();
2924 if (size > 0) {
2925 fout.println("Default restrict background whitelist uids:");
2926 fout.increaseIndent();
2927 for (int i = 0; i < size; i++) {
2928 fout.print("UID=");
2929 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2930 fout.println();
2931 }
2932 fout.decreaseIndent();
2933 }
2934
2935 size = mRestrictBackgroundWhitelistRevokedUids.size();
2936 if (size > 0) {
2937 fout.println("Default restrict background whitelist uids revoked by users:");
2938 fout.increaseIndent();
2939 for (int i = 0; i < size; i++) {
2940 fout.print("UID=");
2941 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2942 fout.println();
2943 }
2944 fout.decreaseIndent();
2945 }
2946
2947 final SparseBooleanArray knownUids = new SparseBooleanArray();
2948 collectKeys(mUidState, knownUids);
2949 collectKeys(mUidRules, knownUids);
2950
2951 fout.println("Status for all known UIDs:");
2952 fout.increaseIndent();
2953 size = knownUids.size();
2954 for (int i = 0; i < size; i++) {
2955 final int uid = knownUids.keyAt(i);
2956 fout.print("UID=");
2957 fout.print(uid);
2958
2959 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2960 fout.print(" state=");
2961 fout.print(state);
2962 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2963 fout.print(" (fg)");
2964 } else {
2965 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2966 ? " (fg svc)" : " (bg)");
2967 }
2968
2969 final int uidRules = mUidRules.get(uid, RULE_NONE);
2970 fout.print(" rules=");
2971 fout.print(uidRulesToString(uidRules));
2972 fout.println();
2973 }
2974 fout.decreaseIndent();
2975
2976 fout.println("Status for just UIDs with rules:");
2977 fout.increaseIndent();
2978 size = mUidRules.size();
2979 for (int i = 0; i < size; i++) {
2980 final int uid = mUidRules.keyAt(i);
2981 fout.print("UID=");
2982 fout.print(uid);
2983 final int uidRules = mUidRules.get(uid, RULE_NONE);
2984 fout.print(" rules=");
2985 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002986 fout.println();
2987 }
2988 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08002989
2990 fout.println("Observed uid state changes:");
2991 fout.increaseIndent();
2992 mObservedHistory.dumpUL(fout);
2993 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002994 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07002995 }
2996 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07002997
2998 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08002999 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003000 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003001 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003002 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003003 }
3004
3005 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003006 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003007 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3008
Felipe Lemef0823852016-06-08 13:43:08 -07003009 synchronized (mUidRulesFirstLock) {
3010 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003011 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003012 }
3013
Felipe Lemef0823852016-06-08 13:43:08 -07003014 private boolean isUidForegroundUL(int uid) {
3015 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003016 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3017 }
3018
Felipe Lemef0823852016-06-08 13:43:08 -07003019 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003020 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003021 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003022 }
3023
Felipe Lemef0823852016-06-08 13:43:08 -07003024 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003025 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3026 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3027 }
3028
Felipe Lemef0823852016-06-08 13:43:08 -07003029 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003030 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003031 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003032 }
3033
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003034 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003035 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003036 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3037 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003038 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003039 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003040 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3041 try {
3042 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3043 if (oldUidState != uidState) {
3044 // state changed, push updated rules
3045 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003046 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3047 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3048 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003049 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003050 if (mDeviceIdleMode) {
3051 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003052 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003053 if (mRestrictPower) {
3054 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003055 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003056 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003057 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003058 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003059 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003060 } finally {
3061 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003062 }
3063 }
3064
Felipe Lemef0823852016-06-08 13:43:08 -07003065 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003066 final int index = mUidState.indexOfKey(uid);
3067 if (index >= 0) {
3068 final int oldUidState = mUidState.valueAt(index);
3069 mUidState.removeAt(index);
3070 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003071 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003072 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003073 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003074 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003075 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003076 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003077 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003078 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003079 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003080 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003081 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003082 }
3083 }
3084
Felipe Lemef28983d2016-03-25 12:18:23 -07003085 // adjust stats accounting based on foreground status
3086 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003087 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3088 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3089 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3090 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003091 try {
3092 mNetworkStats.setUidForeground(uid, uidForeground);
3093 } catch (RemoteException e) {
3094 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003095 } finally {
3096 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003097 }
3098 }
3099
Sudheer Shankac9d94072017-02-22 22:13:55 +00003100 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3101 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003102 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003103 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003104 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003105 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003106 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003107 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003108 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003109 }
3110
Felipe Lemef0823852016-06-08 13:43:08 -07003111 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003112 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3113 try {
3114 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3115 mUidFirewallPowerSaveRules);
3116 } finally {
3117 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3118 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003119 }
3120
Felipe Lemef0823852016-06-08 13:43:08 -07003121 void updateRuleForRestrictPowerUL(int uid) {
3122 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003123 }
3124
Felipe Lemef0823852016-06-08 13:43:08 -07003125 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003126 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3127 try {
3128 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3129 mUidFirewallDozableRules);
3130 } finally {
3131 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3132 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003133 }
3134
Felipe Lemef0823852016-06-08 13:43:08 -07003135 void updateRuleForDeviceIdleUL(int uid) {
3136 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003137 }
3138
Felipe Lemef28983d2016-03-25 12:18:23 -07003139 // NOTE: since both fw_dozable and fw_powersave uses the same map
3140 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003141 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003142 SparseIntArray rules) {
3143 if (enabled) {
3144 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003145 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003146 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003147 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003148 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003149 for (int ui = users.size() - 1; ui >= 0; ui--) {
3150 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003151 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3152 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3153 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3154 updateRulesForWhitelistedAppIds(uidRules,
3155 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003156 }
3157 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003158 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003159 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003160 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3161 }
3162 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003163 setUidFirewallRulesAsync(chain, uidRules, CHAIN_TOGGLE_ENABLE);
3164 } else {
3165 setUidFirewallRulesAsync(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003166 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003167 }
3168
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003169 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3170 final SparseBooleanArray whitelistedAppIds, int userId) {
3171 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3172 if (whitelistedAppIds.valueAt(i)) {
3173 final int appId = whitelistedAppIds.keyAt(i);
3174 final int uid = UserHandle.getUid(userId, appId);
3175 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3176 }
3177 }
3178 }
3179
3180 /**
3181 * @param deviceIdleMode if true then we don't consider
3182 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3183 * whitelisted.
3184 */
3185 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003186 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003187 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3188 || mPowerSaveWhitelistAppIds.get(appId);
3189 if (!deviceIdleMode) {
3190 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3191 }
3192 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003193 }
3194
Felipe Lemef28983d2016-03-25 12:18:23 -07003195 // NOTE: since both fw_dozable and fw_powersave uses the same map
3196 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003197 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003198 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003199 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3200 chain == FIREWALL_CHAIN_DOZABLE);
3201 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003202 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003203 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003204 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003205 }
3206 }
3207 }
3208
Felipe Lemef0823852016-06-08 13:43:08 -07003209 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003210 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3211 try {
3212 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3213 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003214
Felipe Leme873a83a2016-09-07 11:34:10 -07003215 // Fully update the app idle firewall chain.
3216 final List<UserInfo> users = mUserManager.getUsers();
3217 for (int ui = users.size() - 1; ui >= 0; ui--) {
3218 UserInfo user = users.get(ui);
3219 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3220 for (int uid : idleUids) {
3221 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3222 // quick check: if this uid doesn't have INTERNET permission, it
3223 // doesn't have network access anyway, so it is a waste to mess
3224 // with it here.
3225 if (hasInternetPermissions(uid)) {
3226 uidRules.put(uid, FIREWALL_RULE_DENY);
3227 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003228 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003229 }
3230 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003231
Felipe Lemebc853dd2016-09-08 13:26:55 -07003232 setUidFirewallRulesAsync(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003233 } finally {
3234 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3235 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003236 }
3237
Felipe Lemef0823852016-06-08 13:43:08 -07003238 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003239 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003240
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003241 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3242 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3243 }
3244 try {
3245 int appId = UserHandle.getAppId(uid);
3246 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3247 && !isUidForegroundOnRestrictPowerUL(uid)) {
3248 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3249 } else {
3250 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3251 }
3252 } finally {
3253 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003254 }
3255 }
3256
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003257 /**
3258 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3259 * changed.
3260 */
Felipe Lemef0823852016-06-08 13:43:08 -07003261 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003262 boolean paroled = mUsageStats.isAppIdleParoleOn();
3263 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003264 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003265
3266 int ruleCount = mUidFirewallStandbyRules.size();
3267 for (int i = 0; i < ruleCount; i++) {
3268 int uid = mUidFirewallStandbyRules.keyAt(i);
3269 int oldRules = mUidRules.get(uid);
3270 if (enableChain) {
3271 // Chain wasn't enabled before and the other power-related
3272 // chains are whitelists, so we can clear the
3273 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3274 // the effective rules result in blocking network access.
3275 oldRules &= MASK_METERED_NETWORKS;
3276 } else {
3277 // Skip if it had no restrictions to begin with
3278 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3279 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003280 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3281 if (newUidRules == RULE_NONE) {
3282 mUidRules.delete(uid);
3283 } else {
3284 mUidRules.put(uid, newUidRules);
3285 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003286 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003287 }
3288
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003289 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003290 * Update rules that might be changed by {@link #mRestrictBackground},
3291 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003292 */
Felipe Lemef0823852016-06-08 13:43:08 -07003293 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003294 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3295 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3296 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3297 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003298 try {
Felipe Leme09700462016-09-08 09:33:48 -07003299 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003300 updateRulesForRestrictPowerUL();
3301 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003302
Felipe Leme873a83a2016-09-07 11:34:10 -07003303 // If the set of restricted networks may have changed, re-evaluate those.
3304 if (restrictedNetworksChanged) {
3305 normalizePoliciesNL();
3306 updateNetworkRulesNL();
3307 }
3308 } finally {
3309 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003310 }
3311 }
3312
Felipe Leme09700462016-09-08 09:33:48 -07003313 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003314 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003315 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3316 try {
3317 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003318 updateRulesForPowerSaveUL();
3319 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3320 } finally {
3321 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3322 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003323 }
3324
Felipe Lemef0823852016-06-08 13:43:08 -07003325 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003326 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3327 try {
3328 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3329 } finally {
3330 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3331 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003332 }
3333
3334 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3335 private static final int TYPE_RESTRICT_POWER = 2;
3336 @Retention(RetentionPolicy.SOURCE)
3337 @IntDef(flag = false, value = {
3338 TYPE_RESTRICT_BACKGROUND,
3339 TYPE_RESTRICT_POWER,
3340 })
3341 public @interface RestrictType {
3342 }
3343
3344 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003345 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003346 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3347 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3348 }
3349 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003350 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003351
3352 final PackageManager pm = mContext.getPackageManager();
3353 final List<UserInfo> users;
3354 final List<ApplicationInfo> apps;
3355
3356 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3357 try {
3358 users = mUserManager.getUsers();
3359 } finally {
3360 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3361 }
3362 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3363 try {
3364 apps = pm.getInstalledApplications(
3365 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3366 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3367 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3368 } finally {
3369 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3370 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003371
Felipe Leme873a83a2016-09-07 11:34:10 -07003372 final int usersSize = users.size();
3373 final int appsSize = apps.size();
3374 for (int i = 0; i < usersSize; i++) {
3375 final UserInfo user = users.get(i);
3376 for (int j = 0; j < appsSize; j++) {
3377 final ApplicationInfo app = apps.get(j);
3378 final int uid = UserHandle.getUid(user.id, app.uid);
3379 switch (type) {
3380 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003381 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003382 break;
3383 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003384 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003385 break;
3386 default:
3387 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3388 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003389 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003390 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003391 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003392 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003393 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003394 }
3395
Felipe Lemef0823852016-06-08 13:43:08 -07003396 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003397 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003398 for (int i = 0; i < users.size(); i++) {
3399 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003400 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003401 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003402 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003403 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003404 updateRuleForAppIdleUL(uid);
3405 updateRuleForDeviceIdleUL(uid);
3406 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003407 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003408 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003409 }
3410 }
3411 }
3412
Felipe Leme70c57c22016-03-29 10:45:13 -07003413 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3414 // methods below could be merged into a isUidValidForRules() method.
3415 private boolean isUidValidForBlacklistRules(int uid) {
3416 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003417 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003418 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003419 return true;
3420 }
3421
3422 return false;
3423 }
3424
Felipe Leme70c57c22016-03-29 10:45:13 -07003425 private boolean isUidValidForWhitelistRules(int uid) {
3426 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3427 }
3428
Amith Yamasani15e472352015-04-24 19:06:07 -07003429 private boolean isUidIdle(int uid) {
3430 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3431 final int userId = UserHandle.getUserId(uid);
3432
songjinshi0655edd2016-05-18 19:55:32 +08003433 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003434 for (String packageName : packages) {
3435 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3436 return false;
3437 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003438 }
3439 }
3440 return true;
3441 }
3442
3443 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003444 * Checks if an uid has INTERNET permissions.
3445 * <p>
3446 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003447 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003448 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003449 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003450 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003451 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003452 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003453 }
3454 } catch (RemoteException e) {
3455 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003456 return true;
3457 }
3458
3459 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003460 * Clears all state - internal and external - associated with an UID.
3461 */
3462 private void onUidDeletedUL(int uid) {
3463 // First cleanup in-memory state synchronously...
3464 mUidRules.delete(uid);
3465 mUidPolicy.delete(uid);
3466 mUidFirewallStandbyRules.delete(uid);
3467 mUidFirewallDozableRules.delete(uid);
3468 mUidFirewallPowerSaveRules.delete(uid);
3469 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3470 mPowerSaveWhitelistAppIds.delete(uid);
3471 mPowerSaveTempWhitelistAppIds.delete(uid);
3472
3473 // ...then update iptables asynchronously.
3474 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3475 }
3476
3477 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003478 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003479 *
Felipe Leme781ba142016-05-09 16:24:48 -07003480 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003481 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003482 * <li>Doze mode
3483 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003484 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003485 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003486 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003487 *
3488 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003489 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003490 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003491 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003492 updateRuleForDeviceIdleUL(uid);
3493 updateRuleForAppIdleUL(uid);
3494 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003495
3496 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003497 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003498
3499 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003500 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003501 }
3502
Felipe Leme70c57c22016-03-29 10:45:13 -07003503 /**
3504 * Applies network rules to bandwidth controllers based on process state and user-defined
3505 * restrictions (blacklist / whitelist).
3506 *
3507 * <p>
3508 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3509 * networks:
3510 * <ul>
3511 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3512 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3513 * also blacklisted.
3514 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3515 * no UIDs other those whitelisted will have access.
3516 * <ul>
3517 *
3518 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3519 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3520 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3521 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003522 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003523 * {@link INetworkManagementService}, but this method should also be called in events (like
3524 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3525 * following rules should also be applied:
3526 *
3527 * <ul>
3528 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3529 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3530 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3531 * {@code bw_penalty_box}.
3532 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3533 * </ul>
3534 *
3535 * <p>For optimization, the rules are only applied on user apps that have internet access
3536 * permission, since there is no need to change the {@code iptables} rule if the app does not
3537 * have permission to use the internet.
3538 *
3539 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003540 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003541 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003542 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003543 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3544 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3545 "updateRulesForDataUsageRestrictionsUL: " + uid);
3546 }
3547 try {
3548 updateRulesForDataUsageRestrictionsULInner(uid);
3549 } finally {
3550 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3551 }
3552 }
3553
3554 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003555 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003556 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003557 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003558 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003559
Dianne Hackborn497175b2014-07-01 12:56:08 -07003560 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003561 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003562 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003563
Felipe Leme781ba142016-05-09 16:24:48 -07003564 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003565 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003566 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3567 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003568
Felipe Leme70c57c22016-03-29 10:45:13 -07003569 // First step: define the new rule based on user restrictions and foreground state.
3570 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003571 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3572 newRule = RULE_TEMPORARY_ALLOW_METERED;
3573 } else if (isWhitelisted) {
3574 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003575 }
3576 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003577 if (isBlacklisted) {
3578 newRule = RULE_REJECT_METERED;
3579 } else if (mRestrictBackground && isWhitelisted) {
3580 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003581 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003582 }
Felipe Leme781ba142016-05-09 16:24:48 -07003583 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003584
Felipe Lemef28983d2016-03-25 12:18:23 -07003585 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003586 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003587 + ": isForeground=" +isForeground
3588 + ", isBlacklisted=" + isBlacklisted
3589 + ", isWhitelisted=" + isWhitelisted
3590 + ", oldRule=" + uidRulesToString(oldRule)
3591 + ", newRule=" + uidRulesToString(newRule)
3592 + ", newUidRules=" + uidRulesToString(newUidRules)
3593 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003594 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003595
Felipe Leme46c4fc32016-05-04 09:21:43 -07003596 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003597 mUidRules.delete(uid);
3598 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003599 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003600 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003601
Felipe Leme70c57c22016-03-29 10:45:13 -07003602 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003603 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003604 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003605 // Temporarily whitelist foreground app, removing from blacklist if necessary
3606 // (since bw_penalty_box prevails over bw_happy_box).
3607
3608 setMeteredNetworkWhitelist(uid, true);
3609 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3610 // but ideally it should be just:
3611 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003612 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003613 setMeteredNetworkBlacklist(uid, false);
3614 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003615 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003616 // Remove temporary whitelist from app that is not on foreground anymore.
3617
3618 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3619 // but ideally they should be just:
3620 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3621 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003622 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003623 setMeteredNetworkWhitelist(uid, false);
3624 }
Felipe Leme781ba142016-05-09 16:24:48 -07003625 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003626 setMeteredNetworkBlacklist(uid, true);
3627 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003628 } else if (hasRule(newRule, RULE_REJECT_METERED)
3629 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003630 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003631 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003632 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003633 // Since blacklist prevails over whitelist, we need to handle the special case
3634 // where app is whitelisted and blacklisted at the same time (although such
3635 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003636 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003637 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003638 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3639 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003640 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003641 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003642 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003643 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003644 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3645 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003646 + ", whitelisted=" + isWhitelisted
3647 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003648 + ", newRule=" + uidRulesToString(newUidRules)
3649 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003650 }
Felipe Leme781ba142016-05-09 16:24:48 -07003651
Sudheer Shankac9d94072017-02-22 22:13:55 +00003652 // Dispatch changed rule to existing listeners.
3653 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003654 }
3655 }
3656
3657 /**
3658 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3659 * listeners in case of change.
3660 * <p>
3661 * There are 3 power-related rules that affects whether an app has background access on
3662 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3663 * restriction, it's added to the equivalent firewall chain:
3664 * <ul>
3665 * <li>App is idle: {@code fw_standby} firewall chain.
3666 * <li>Device is idle: {@code fw_dozable} firewall chain.
3667 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3668 * </ul>
3669 * <p>
3670 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3671 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3672 * <p>
3673 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3674 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003675 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003676 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3677
Sudheer Shankac9d94072017-02-22 22:13:55 +00003678 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003679
Sudheer Shankac9d94072017-02-22 22:13:55 +00003680 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003681 mUidRules.delete(uid);
3682 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003683 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003684 }
3685 }
3686
3687 /**
3688 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3689 *
3690 * @param uid the uid of the app to update rules for
3691 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3692 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3693 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003694 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003695 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003696 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003697 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3698 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3699 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3700 + (paroled ? "P" : "-"));
3701 }
3702 try {
3703 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3704 } finally {
3705 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3706 }
3707 }
3708
3709 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003710 if (!isUidValidForBlacklistRules(uid)) {
3711 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003712 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003713 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003714
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003715 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003716 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003717 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003718
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003719 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003720 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3721 int newRule = RULE_NONE;
3722
3723 // First step: define the new rule based on user restrictions and foreground state.
3724
3725 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3726 // by considering the foreground and non-foreground states.
3727 if (isForeground) {
3728 if (restrictMode) {
3729 newRule = RULE_ALLOW_ALL;
3730 }
3731 } else if (restrictMode) {
3732 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3733 }
3734
3735 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3736
3737 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003738 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003739 + ", isIdle: " + isIdle
3740 + ", mRestrictPower: " + mRestrictPower
3741 + ", mDeviceIdleMode: " + mDeviceIdleMode
3742 + ", isForeground=" + isForeground
3743 + ", isWhitelisted=" + isWhitelisted
3744 + ", oldRule=" + uidRulesToString(oldRule)
3745 + ", newRule=" + uidRulesToString(newRule)
3746 + ", newUidRules=" + uidRulesToString(newUidRules)
3747 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3748 }
3749
Felipe Leme781ba142016-05-09 16:24:48 -07003750 // Second step: notify listeners if state changed.
3751 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003752 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003753 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003754 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003755 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3756 } else {
3757 // All scenarios should have been covered above
3758 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3759 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003760 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003761 + ", newRule=" + uidRulesToString(newUidRules)
3762 + ", oldRule=" + uidRulesToString(oldUidRules));
3763 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003764 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003765 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003766
Sudheer Shankac9d94072017-02-22 22:13:55 +00003767 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003768 }
3769
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003770 private class AppIdleStateChangeListener
3771 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3772
3773 @Override
3774 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3775 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003776 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3777 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003778 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003779 synchronized (mUidRulesFirstLock) {
3780 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003781 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003782 }
3783 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003784 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003785 }
3786
3787 @Override
3788 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003789 synchronized (mUidRulesFirstLock) {
3790 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003791 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003792 }
3793 }
3794
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003795 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3796 if (listener != null) {
3797 try {
3798 listener.onUidRulesChanged(uid, uidRules);
3799 } catch (RemoteException ignored) {
3800 }
3801 }
3802 }
3803
3804 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3805 String[] meteredIfaces) {
3806 if (listener != null) {
3807 try {
3808 listener.onMeteredIfacesChanged(meteredIfaces);
3809 } catch (RemoteException ignored) {
3810 }
3811 }
3812 }
3813
3814 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3815 boolean restrictBackground) {
3816 if (listener != null) {
3817 try {
3818 listener.onRestrictBackgroundChanged(restrictBackground);
3819 } catch (RemoteException ignored) {
3820 }
3821 }
3822 }
3823
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003824 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3825 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003826 if (listener != null) {
3827 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003828 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003829 } catch (RemoteException ignored) {
3830 }
3831 }
3832 }
3833
Makoto Onuki8e777332017-03-28 11:25:47 -07003834 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003835 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003836 public boolean handleMessage(Message msg) {
3837 switch (msg.what) {
3838 case MSG_RULES_CHANGED: {
3839 final int uid = msg.arg1;
3840 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003841 final int length = mListeners.beginBroadcast();
3842 for (int i = 0; i < length; i++) {
3843 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3844 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003845 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003846 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003847 return true;
3848 }
3849 case MSG_METERED_IFACES_CHANGED: {
3850 final String[] meteredIfaces = (String[]) msg.obj;
3851 final int length = mListeners.beginBroadcast();
3852 for (int i = 0; i < length; i++) {
3853 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003854 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003855 }
3856 mListeners.finishBroadcast();
3857 return true;
3858 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003859 case MSG_LIMIT_REACHED: {
3860 final String iface = (String) msg.obj;
3861
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003862 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003863 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003864 if (mMeteredIfaces.contains(iface)) {
3865 try {
3866 // force stats update to make sure we have
3867 // numbers that caused alert to trigger.
3868 mNetworkStats.forceUpdate();
3869 } catch (RemoteException e) {
3870 // ignored; service lives in system_server
3871 }
3872
Felipe Lemef0823852016-06-08 13:43:08 -07003873 updateNetworkEnabledNL();
3874 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003875 }
3876 }
3877 return true;
3878 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003879 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3880 final boolean restrictBackground = msg.arg1 != 0;
3881 final int length = mListeners.beginBroadcast();
3882 for (int i = 0; i < length; i++) {
3883 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003884 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003885 }
3886 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003887 final Intent intent =
3888 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3889 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3890 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3891 return true;
3892 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003893 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003894 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003895 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003896 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003897 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003898 final int length = mListeners.beginBroadcast();
3899 for (int i = 0; i < length; i++) {
3900 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003901 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003902 }
3903 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003904 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3905 if (notifyApp.booleanValue()) {
3906 broadcastRestrictBackgroundChanged(uid, notifyApp);
3907 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003908 return true;
3909 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003910 case MSG_ADVISE_PERSIST_THRESHOLD: {
3911 final long lowestRule = (Long) msg.obj;
3912 try {
3913 // make sure stats are recorded frequently enough; we aim
3914 // for 2MB threshold for 2GB/month rules.
3915 final long persistThreshold = lowestRule / 1000;
3916 mNetworkStats.advisePersistThreshold(persistThreshold);
3917 } catch (RemoteException e) {
3918 // ignored; service lives in system_server
3919 }
3920 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003921 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003922 case MSG_UPDATE_INTERFACE_QUOTA: {
3923 removeInterfaceQuota((String) msg.obj);
3924 // int params need to be stitched back into a long
3925 setInterfaceQuota((String) msg.obj,
3926 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3927 return true;
3928 }
3929 case MSG_REMOVE_INTERFACE_QUOTA: {
3930 removeInterfaceQuota((String) msg.obj);
3931 return true;
3932 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07003933 case MSG_SET_FIREWALL_RULES: {
3934 final int chain = msg.arg1;
3935 final int toggle = msg.arg2;
3936 final SparseIntArray uidRules = (SparseIntArray) msg.obj;
3937 if (uidRules != null) {
3938 setUidFirewallRules(chain, uidRules);
3939 }
3940 if (toggle != CHAIN_TOGGLE_NONE) {
3941 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
3942 }
3943 return true;
3944 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003945 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3946 resetUidFirewallRules(msg.arg1);
3947 return true;
3948 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003949 default: {
3950 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003951 }
3952 }
3953 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003954 };
3955
3956 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3957 @Override
3958 public boolean handleMessage(Message msg) {
3959 switch (msg.what) {
3960 case UID_MSG_STATE_CHANGED: {
3961 final int uid = msg.arg1;
3962 final int procState = msg.arg2;
3963 final long procStateSeq = (Long) msg.obj;
3964
3965 handleUidChanged(uid, procState, procStateSeq);
3966 return true;
3967 }
3968 case UID_MSG_GONE: {
3969 final int uid = msg.arg1;
3970 handleUidGone(uid);
3971 return true;
3972 }
3973 default: {
3974 return false;
3975 }
3976 }
3977 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003978
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003979 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003980
Makoto Onuki8e777332017-03-28 11:25:47 -07003981 void handleUidChanged(int uid, int procState, long procStateSeq) {
3982 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3983 try {
3984 synchronized (mUidRulesFirstLock) {
3985 // We received a uid state change callback, add it to the history so that it
3986 // will be useful for debugging.
3987 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
3988 // Now update the network policy rules as per the updated uid state.
3989 updateUidStateUL(uid, procState);
3990 // Updating the network rules is done, so notify AMS about this.
3991 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
3992 }
3993 } finally {
3994 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3995 }
3996 }
3997
3998 void handleUidGone(int uid) {
3999 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4000 try {
4001 synchronized (mUidRulesFirstLock) {
4002 removeUidStateUL(uid);
4003 }
4004 } finally {
4005 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4006 }
4007 }
4008
Felipe Leme57e3d312016-08-23 14:42:52 -07004009 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4010 final PackageManager pm = mContext.getPackageManager();
4011 final String[] packages = pm.getPackagesForUid(uid);
4012 if (packages != null) {
4013 final int userId = UserHandle.getUserId(uid);
4014 for (String packageName : packages) {
4015 final Intent intent =
4016 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4017 intent.setPackage(packageName);
4018 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4019 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4020 }
4021 }
4022 }
4023
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004024 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004025 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004026 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004027 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004028 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004029 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004030 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004031 }
4032 }
4033
4034 private void removeInterfaceQuota(String iface) {
4035 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004036 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004037 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004038 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004039 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004040 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004041 }
4042 }
4043
Felipe Leme70c57c22016-03-29 10:45:13 -07004044 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4045 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004046 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004047 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004048 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004049 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4050 } catch (RemoteException e) {
4051 // ignored; service lives in system_server
4052 }
4053 }
4054
4055 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4056 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4057 try {
4058 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4059 } catch (IllegalStateException e) {
4060 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004061 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004062 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004063 }
4064 }
4065
Felipe Lemebc853dd2016-09-08 13:26:55 -07004066 private static final int CHAIN_TOGGLE_NONE = 0;
4067 private static final int CHAIN_TOGGLE_ENABLE = 1;
4068 private static final int CHAIN_TOGGLE_DISABLE = 2;
4069 @Retention(RetentionPolicy.SOURCE)
4070 @IntDef(flag = false, value = {
4071 CHAIN_TOGGLE_NONE,
4072 CHAIN_TOGGLE_ENABLE,
4073 CHAIN_TOGGLE_DISABLE
4074 })
4075 public @interface ChainToggleType {
4076 }
4077
4078 /**
4079 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
4080 * {@link #enableFirewallChainUL(int, boolean)} asynchronously.
4081 *
4082 * @param chain firewall chain.
4083 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4084 * @param toggle whether the chain should be enabled, disabled, or not changed.
4085 */
4086 private void setUidFirewallRulesAsync(int chain, @Nullable SparseIntArray uidRules,
4087 @ChainToggleType int toggle) {
4088 mHandler.obtainMessage(MSG_SET_FIREWALL_RULES, chain, toggle, uidRules).sendToTarget();
4089 }
4090
Amith Yamasani15e472352015-04-24 19:06:07 -07004091 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004092 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4093 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4094 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004095 */
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004096 private void setUidFirewallRules(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004097 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004098 int size = uidRules.size();
4099 int[] uids = new int[size];
4100 int[] rules = new int[size];
4101 for(int index = size - 1; index >= 0; --index) {
4102 uids[index] = uidRules.keyAt(index);
4103 rules[index] = uidRules.valueAt(index);
4104 }
4105 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004106 } catch (IllegalStateException e) {
4107 Log.wtf(TAG, "problem setting firewall uid rules", e);
4108 } catch (RemoteException e) {
4109 // ignored; service lives in system_server
4110 }
4111 }
4112
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004113 /**
4114 * Add or remove a uid to the firewall blacklist for all network ifaces.
4115 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004116 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004117 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4118 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4119 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004120 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004121 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004122 if (chain == FIREWALL_CHAIN_DOZABLE) {
4123 mUidFirewallDozableRules.put(uid, rule);
4124 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4125 mUidFirewallStandbyRules.put(uid, rule);
4126 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4127 mUidFirewallPowerSaveRules.put(uid, rule);
4128 }
4129
4130 try {
4131 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4132 } catch (IllegalStateException e) {
4133 Log.wtf(TAG, "problem setting firewall uid rules", e);
4134 } catch (RemoteException e) {
4135 // ignored; service lives in system_server
4136 }
4137 } finally {
4138 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004139 }
4140 }
4141
4142 /**
4143 * Add or remove a uid to the firewall blacklist for all network ifaces.
4144 */
Felipe Lemef0823852016-06-08 13:43:08 -07004145 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004146 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4147 mFirewallChainStates.get(chain) == enable) {
4148 // All is the same, nothing to do.
4149 return;
4150 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004151 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004152 try {
4153 mNetworkManager.setFirewallChainEnabled(chain, enable);
4154 } catch (IllegalStateException e) {
4155 Log.wtf(TAG, "problem enable firewall chain", e);
4156 } catch (RemoteException e) {
4157 // ignored; service lives in system_server
4158 }
4159 }
4160
Felipe Leme03e95e22016-09-09 09:25:31 -07004161 /**
4162 * Resets all firewall rules associated with an UID.
4163 */
4164 private void resetUidFirewallRules(int uid) {
4165 try {
4166 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4167 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4168 mNetworkManager
4169 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4170 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4171 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4172 } catch (IllegalStateException e) {
4173 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4174 } catch (RemoteException e) {
4175 // ignored; service lives in system_server
4176 }
4177 }
4178
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004179 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4180 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004181 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004182 } catch (RuntimeException e) {
4183 Slog.w(TAG, "problem reading network stats: " + e);
4184 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004185 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004186 // ignored; service lives in system_server
4187 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004188 }
4189 }
4190
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004191 private boolean isBandwidthControlEnabled() {
4192 final long token = Binder.clearCallingIdentity();
4193 try {
4194 return mNetworkManager.isBandwidthControlEnabled();
4195 } catch (RemoteException e) {
4196 // ignored; service lives in system_server
4197 return false;
4198 } finally {
4199 Binder.restoreCallingIdentity(token);
4200 }
4201 }
4202
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004203 /**
4204 * Try refreshing {@link #mTime} when stale.
4205 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004206 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004207 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004208 mTime.forceRefresh();
4209 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004210 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004211
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004212 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004213 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4214 }
4215
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004216 private static Intent buildAllowBackgroundDataIntent() {
4217 return new Intent(ACTION_ALLOW_BACKGROUND);
4218 }
4219
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004220 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4221 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4222 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4223 return intent;
4224 }
4225
Wei Liu546cb772016-07-21 16:19:01 -07004226 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004227 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004228 intent.setComponent(ComponentName.unflattenFromString(
4229 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004230 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4231 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4232 return intent;
4233 }
4234
Wei Liu546cb772016-07-21 16:19:01 -07004235 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004236 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004237 intent.setComponent(ComponentName.unflattenFromString(
4238 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004239 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4240 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4241 return intent;
4242 }
4243
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004244 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004245 public void addIdleHandler(IdleHandler handler) {
4246 mHandler.getLooper().getQueue().addIdleHandler(handler);
4247 }
4248
jackqdyulei29c82ab2017-03-10 14:09:16 -08004249 @VisibleForTesting
4250 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4251 mRestrictBackgroundPowerState = result;
4252
4253 boolean restrictBackground = result.batterySaverEnabled;
4254 boolean shouldInvokeRestrictBackground;
4255 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4256 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4257
4258 if (result.globalBatterySaverEnabled) {
4259 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4260 // turn it on.
4261 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4262 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4263 localRestrictBgChangedInBsm = false;
4264 } else {
4265 // Try to restore the restrictBackground if it doesn't change in bsm
4266 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4267 restrictBackground = mRestrictBackgroundBeforeBsm;
4268 }
4269
4270 if (shouldInvokeRestrictBackground) {
4271 setRestrictBackground(restrictBackground);
4272 }
4273
4274 // Change it at last so setRestrictBackground() won't affect this variable
4275 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4276 }
4277
Jeff Sharkey1b861272011-05-22 00:34:52 -07004278 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4279 final int size = source.size();
4280 for (int i = 0; i < size; i++) {
4281 target.put(source.keyAt(i), true);
4282 }
4283 }
4284
Stuart Scottf1fb3972015-04-02 18:00:02 -07004285 @Override
4286 public void factoryReset(String subscriber) {
4287 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4288
Stuart Scotte3e314d2015-04-20 14:07:45 -07004289 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4290 return;
4291 }
4292
Stuart Scottf1fb3972015-04-02 18:00:02 -07004293 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004294 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004295 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4296 for (NetworkPolicy policy : policies) {
4297 if (policy.template.equals(template)) {
4298 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4299 policy.inferred = false;
4300 policy.clearSnooze();
4301 }
4302 }
4303 setNetworkPolicies(policies);
4304
4305 // Turn restrict background data off
4306 setRestrictBackground(false);
4307
Stuart Scotte3e314d2015-04-20 14:07:45 -07004308 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4309 // Remove app's "restrict background data" flag
4310 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4311 setUidPolicy(uid, POLICY_NONE);
4312 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004313 }
4314 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004315
Sudheer Shankab8f23162017-08-04 13:30:10 -07004316 @Override
4317 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4318 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4319 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4320 }
4321
4322 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4323 final int uidRules;
4324 final boolean isBackgroundRestricted;
4325 synchronized (mUidRulesFirstLock) {
4326 uidRules = mUidRules.get(uid, RULE_NONE);
4327 isBackgroundRestricted = mRestrictBackground;
4328 }
4329 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4330 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4331 return true;
4332 }
4333 if (!isNetworkMetered) {
4334 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4335 return false;
4336 }
4337 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4338 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4339 return true;
4340 }
4341 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4342 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4343 return false;
4344 }
4345 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4346 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4347 return false;
4348 }
4349 if (isBackgroundRestricted) {
4350 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4351 return true;
4352 }
4353 if (LOGV) logUidStatus(uid, "allowed by default");
4354 return false;
4355 }
4356
Felipe Lemed17fda42016-04-29 11:12:45 -07004357 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4358
4359 @Override
4360 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004361 synchronized (mUidRulesFirstLock) {
4362 boolean changed = removeUserStateUL(userId, false);
4363 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004364 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004365 synchronized (mNetworkPoliciesSecondLock) {
4366 writePolicyAL();
4367 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004368 }
4369 }
4370 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004371
4372 /**
4373 * @return true if the given uid is restricted from doing networking on metered networks.
4374 */
4375 @Override
4376 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4377 final int uidRules;
4378 final boolean isBackgroundRestricted;
4379 synchronized (mUidRulesFirstLock) {
4380 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4381 isBackgroundRestricted = mRestrictBackground;
4382 }
4383 return isBackgroundRestricted
4384 && !hasRule(uidRules, RULE_ALLOW_METERED)
4385 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4386 }
4387
4388 /**
4389 * @return true if networking is blocked on the given interface for the given uid according
4390 * to current networking policies.
4391 */
4392 @Override
4393 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004394 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004395 synchronized (mNetworkPoliciesSecondLock) {
4396 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004397 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004398 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004399 }
4400 }
4401
4402 private static boolean hasRule(int uidRules, int rule) {
4403 return (uidRules & rule) != 0;
4404 }
4405
4406 private static void logUidStatus(int uid, String descr) {
4407 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004408 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004409
4410 /**
4411 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4412 * (uid, procStateSeq) pairs.
4413 */
4414 @VisibleForTesting
4415 public static final class ProcStateSeqHistory {
4416 private static final int INVALID_UID = -1;
4417
4418 /**
4419 * Denotes maximum number of items this history can hold.
4420 */
4421 private final int mMaxCapacity;
4422 /**
4423 * Used for storing the uid information.
4424 */
4425 private final int[] mUids;
4426 /**
4427 * Used for storing the sequence numbers associated with {@link #mUids}.
4428 */
4429 private final long[] mProcStateSeqs;
4430 /**
4431 * Points to the next available slot for writing (uid, procStateSeq) pair.
4432 */
4433 private int mHistoryNext;
4434
4435 public ProcStateSeqHistory(int maxCapacity) {
4436 mMaxCapacity = maxCapacity;
4437 mUids = new int[mMaxCapacity];
4438 Arrays.fill(mUids, INVALID_UID);
4439 mProcStateSeqs = new long[mMaxCapacity];
4440 }
4441
4442 @GuardedBy("mUidRulesFirstLock")
4443 public void addProcStateSeqUL(int uid, long procStateSeq) {
4444 mUids[mHistoryNext] = uid;
4445 mProcStateSeqs[mHistoryNext] = procStateSeq;
4446 mHistoryNext = increaseNext(mHistoryNext, 1);
4447 }
4448
4449 @GuardedBy("mUidRulesFirstLock")
4450 public void dumpUL(IndentingPrintWriter fout) {
4451 if (mUids[0] == INVALID_UID) {
4452 fout.println("NONE");
4453 return;
4454 }
4455 int index = mHistoryNext;
4456 do {
4457 index = increaseNext(index, -1);
4458 if (mUids[index] == INVALID_UID) {
4459 break;
4460 }
4461 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4462 } while (index != mHistoryNext);
4463 }
4464
4465 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004466 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004467 }
4468
4469 private int increaseNext(int next, int increment) {
4470 next += increment;
4471 if (next >= mMaxCapacity) {
4472 next = 0;
4473 } else if (next < 0) {
4474 next = mMaxCapacity - 1;
4475 }
4476 return next;
4477 }
4478 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004479
4480 private class NotificationId {
4481 private final String mTag;
4482 private final int mId;
4483
4484 NotificationId(NetworkPolicy policy, int type) {
4485 mTag = buildNotificationTag(policy, type);
4486 mId = type;
4487 }
4488
4489 @Override
4490 public boolean equals(Object o) {
4491 if (this == o) return true;
4492 if (!(o instanceof NotificationId)) return false;
4493 NotificationId that = (NotificationId) o;
4494 return Objects.equals(mTag, that.mTag);
4495 }
4496
4497 @Override
4498 public int hashCode() {
4499 return Objects.hash(mTag);
4500 }
4501
4502 /**
4503 * Build unique tag that identifies an active {@link NetworkPolicy}
4504 * notification of a specific type, like {@link #TYPE_LIMIT}.
4505 */
4506 private String buildNotificationTag(NetworkPolicy policy, int type) {
4507 return TAG + ":" + policy.template.hashCode() + ":" + type;
4508 }
4509
4510 public String getTag() {
4511 return mTag;
4512 }
4513
4514 public int getId() {
4515 return mId;
4516 }
4517 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004518}