blob: 948e75e7467e7046fc1ba752dd5c362485e80f6a [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 Sharkey64c96ec2017-08-30 16:28:26 -060036import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
Jeff Sharkey22c055e2011-06-12 21:13:51 -070037import static android.net.NetworkPolicy.LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -070038import static android.net.NetworkPolicy.SNOOZE_NEVER;
Jeff Sharkey497e4432011-06-14 17:27:29 -070039import static android.net.NetworkPolicy.WARNING_DISABLED;
Jeff Sharkey14711eb2011-06-15 10:29:17 -070040import static android.net.NetworkPolicyManager.EXTRA_NETWORK_TEMPLATE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070041import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_DOZABLE;
Felipe Leme011b98f2016-02-10 17:28:31 -080042import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_POWERSAVE;
Xiaohui Chenb41c9f72015-06-17 15:55:37 -070043import static android.net.NetworkPolicyManager.FIREWALL_CHAIN_STANDBY;
44import static android.net.NetworkPolicyManager.FIREWALL_RULE_ALLOW;
Jeff Sharkeydc988062015-09-14 10:09:47 -070045import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
Amith Yamasani15e472352015-04-24 19:06:07 -070046import static android.net.NetworkPolicyManager.FIREWALL_RULE_DENY;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060047import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
48import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
Felipe Leme46b451f2016-08-19 08:46:17 -070049import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070050import static android.net.NetworkPolicyManager.POLICY_NONE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070051import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
Felipe Lemed31a97f2016-05-06 14:53:50 -070052import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Felipe Leme70c57c22016-03-29 10:45:13 -070053import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070054import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -070055import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070056import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Felipe Leme70c57c22016-03-29 10:45:13 -070057import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Sudheer Shankae359c3d2017-02-22 18:41:29 -080058import static android.net.NetworkPolicyManager.isProcStateAllowedWhileIdleOrPowerSaveMode;
59import static android.net.NetworkPolicyManager.isProcStateAllowedWhileOnRestrictBackground;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060060import static android.net.NetworkPolicyManager.resolveNetworkId;
Felipe Lemeb146f762016-08-19 09:52:16 -070061import static android.net.NetworkPolicyManager.uidPoliciesToString;
Felipe Leme46c4fc32016-05-04 09:21:43 -070062import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -070063import static android.net.NetworkTemplate.MATCH_MOBILE_3G_LOWER;
64import static android.net.NetworkTemplate.MATCH_MOBILE_4G;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -070065import static android.net.NetworkTemplate.MATCH_MOBILE_ALL;
66import static android.net.NetworkTemplate.MATCH_WIFI;
Jeff Sharkey4e814c32011-07-14 20:37:37 -070067import static android.net.NetworkTemplate.buildTemplateMobileAll;
Jeff Sharkey241dde22012-02-03 14:50:07 -080068import static android.net.TrafficStats.MB_IN_BYTES;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070069import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -070070import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
Jeff Sharkey43d2a172017-07-12 10:50:42 -060071import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070072import static android.text.format.DateUtils.DAY_IN_MILLIS;
Felipe Leme03e689d2016-03-02 16:17:38 -080073
Jeff Sharkey854b2b12012-04-13 16:03:40 -070074import static com.android.internal.util.ArrayUtils.appendInt;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070075import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070076import static com.android.internal.util.XmlUtils.readBooleanAttribute;
77import static com.android.internal.util.XmlUtils.readIntAttribute;
78import static com.android.internal.util.XmlUtils.readLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060079import static com.android.internal.util.XmlUtils.readStringAttribute;
Jeff Sharkeyded7b752013-03-22 13:43:41 -070080import static com.android.internal.util.XmlUtils.writeBooleanAttribute;
81import static com.android.internal.util.XmlUtils.writeIntAttribute;
82import static com.android.internal.util.XmlUtils.writeLongAttribute;
Jeff Sharkey17bebd22017-07-19 21:00:38 -060083import static com.android.internal.util.XmlUtils.writeStringAttribute;
Jeff Sharkey961e3042011-08-29 16:02:57 -070084import static com.android.server.NetworkManagementService.LIMIT_GLOBAL_ALERT;
Jeff Sharkey497e4432011-06-14 17:27:29 -070085import static com.android.server.net.NetworkStatsService.ACTION_NETWORK_STATS_UPDATED;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -060086
Jeff Sharkey21c9c452011-06-07 12:26:43 -070087import static org.xmlpull.v1.XmlPullParser.END_DOCUMENT;
Felipe Lemeb85a6372016-01-14 16:16:16 -080088import static org.xmlpull.v1.XmlPullParser.END_TAG;
Jeff Sharkey21c9c452011-06-07 12:26:43 -070089import static org.xmlpull.v1.XmlPullParser.START_TAG;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -070090
Dianne Hackborn88e98df2015-03-23 13:29:14 -070091import android.Manifest;
Felipe Lemef3e40642016-06-07 17:28:08 -070092import android.annotation.IntDef;
Felipe Lemebc853dd2016-09-08 13:26:55 -070093import android.annotation.Nullable;
Dianne Hackborn497175b2014-07-01 12:56:08 -070094import android.app.ActivityManager;
Sudheer Shankae7361852017-03-07 11:51:46 -080095import android.app.ActivityManagerInternal;
Dianne Hackborn88e98df2015-03-23 13:29:14 -070096import android.app.AppGlobals;
Svet Ganov16a16892015-04-16 10:32:04 -070097import android.app.AppOpsManager;
Jeff Sharkeya4620792011-05-20 15:29:23 -070098import android.app.IActivityManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -070099import android.app.INotificationManager;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700100import android.app.IUidObserver;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700101import android.app.Notification;
102import android.app.PendingIntent;
Amith Yamasani15e472352015-04-24 19:06:07 -0700103import android.app.usage.UsageStatsManagerInternal;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700104import android.content.BroadcastReceiver;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700105import android.content.ComponentName;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700106import android.content.Context;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700107import android.content.Intent;
108import android.content.IntentFilter;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700109import android.content.pm.ApplicationInfo;
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700110import android.content.pm.IPackageManager;
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -0700111import android.content.pm.PackageManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700112import android.content.pm.PackageManager.NameNotFoundException;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700113import android.content.pm.UserInfo;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700114import android.content.res.Resources;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700115import android.net.ConnectivityManager;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600116import android.net.ConnectivityManager.NetworkCallback;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700117import android.net.IConnectivityManager;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700118import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700119import android.net.INetworkPolicyListener;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700120import android.net.INetworkPolicyManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700121import android.net.INetworkStatsService;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import android.net.LinkProperties;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600123import android.net.Network;
124import android.net.NetworkCapabilities;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700125import android.net.NetworkIdentity;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700126import android.net.NetworkPolicy;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600127import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700128import android.net.NetworkQuotaInfo;
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600129import android.net.NetworkRequest;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700130import android.net.NetworkState;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -0700131import android.net.NetworkTemplate;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600132import android.net.TrafficStats;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700133import android.net.wifi.WifiConfiguration;
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700134import android.net.wifi.WifiManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -0700135import android.os.Binder;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700136import android.os.Environment;
137import android.os.Handler;
Amith Yamasani450a16b2013-09-18 16:28:50 -0700138import android.os.HandlerThread;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700139import android.os.IDeviceIdleController;
Ashish Sharma50fd36d2011-06-15 19:34:53 -0700140import android.os.INetworkManagementService;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700141import android.os.Message;
Jeff Sharkey163e6442011-10-31 16:37:52 -0700142import android.os.MessageQueue.IdleHandler;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700143import android.os.PersistableBundle;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700144import android.os.PowerManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700145import android.os.PowerManagerInternal;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600146import android.os.PowerSaveState;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800147import android.os.Process;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700148import android.os.RemoteCallbackList;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700149import android.os.RemoteException;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600150import android.os.ResultReceiver;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700151import android.os.ServiceManager;
Dianne Hackborn354736e2016-08-22 17:00:05 -0700152import android.os.ShellCallback;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600153import android.os.SystemProperties;
Felipe Leme873a83a2016-09-07 11:34:10 -0700154import android.os.Trace;
Dianne Hackbornf02b60a2012-08-16 10:48:27 -0700155import android.os.UserHandle;
Amith Yamasani258848d2012-08-10 17:06:33 -0700156import android.os.UserManager;
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700157import android.provider.Settings;
Narayan Kamath94bcdbc2017-07-17 15:32:53 +0100158import android.provider.Settings.Global;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700159import android.telephony.CarrierConfigManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600160import android.telephony.SubscriptionInfo;
Jeff Sharkey32566012014-12-02 18:30:14 -0800161import android.telephony.SubscriptionManager;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600162import android.telephony.SubscriptionPlan;
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700163import android.telephony.TelephonyManager;
Chris Wren8a3d56c2016-08-01 15:52:52 -0400164import android.text.TextUtils;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700165import android.text.format.Formatter;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700166import android.util.ArrayMap;
167import android.util.ArraySet;
Dianne Hackborn39606a02012-07-31 17:54:35 -0700168import android.util.AtomicFile;
Jeff Sharkeyb3d59572011-09-07 17:20:27 -0700169import android.util.Log;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700170import android.util.NtpTrustedTime;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700171import android.util.Pair;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600172import android.util.RecurrenceRule;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700173import android.util.Slog;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600174import android.util.SparseArray;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700175import android.util.SparseBooleanArray;
176import android.util.SparseIntArray;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700177import android.util.TrustedTime;
178import android.util.Xml;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700179
Jeff Sharkey497e4432011-06-14 17:27:29 -0700180import com.android.internal.R;
Felipe Lemef0823852016-06-08 13:43:08 -0700181import com.android.internal.annotations.GuardedBy;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800182import com.android.internal.annotations.VisibleForTesting;
Chris Wren193ae6b2017-03-31 15:17:11 -0400183import com.android.internal.messages.nano.SystemMessageProto.SystemMessage;
Geoffrey Pitschaf759c52017-02-15 09:35:38 -0500184import com.android.internal.notification.SystemNotificationChannels;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700185import com.android.internal.telephony.PhoneConstants;
Jeff Sharkey32566012014-12-02 18:30:14 -0800186import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600187import com.android.internal.util.DumpUtils;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700188import com.android.internal.util.FastXmlSerializer;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700189import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600190import com.android.internal.util.Preconditions;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700191import com.android.server.DeviceIdleController;
192import com.android.server.EventLogTags;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700193import com.android.server.LocalServices;
Makoto Onuki8e777332017-03-28 11:25:47 -0700194import com.android.server.ServiceThread;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800195import com.android.server.SystemConfig;
jackqdyulei455e90a2017-02-09 15:29:16 -0800196import com.android.server.power.BatterySaverPolicy.ServiceType;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600197
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -0600198import libcore.io.IoUtils;
199
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700200import org.xmlpull.v1.XmlPullParser;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700201import org.xmlpull.v1.XmlSerializer;
202
203import java.io.File;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700204import java.io.FileDescriptor;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700205import java.io.FileInputStream;
206import java.io.FileNotFoundException;
207import java.io.FileOutputStream;
208import java.io.IOException;
Jeff Sharkey1b861272011-05-22 00:34:52 -0700209import java.io.PrintWriter;
Felipe Lemef3e40642016-06-07 17:28:08 -0700210import java.lang.annotation.Retention;
211import java.lang.annotation.RetentionPolicy;
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +0100212import java.nio.charset.StandardCharsets;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600213import java.time.ZoneId;
Jeff Sharkey53313d72017-07-13 16:47:32 -0600214import java.time.ZonedDateTime;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700215import java.util.ArrayList;
216import java.util.Arrays;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700217import java.util.Calendar;
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600218import java.util.List;
Chris Wren193ae6b2017-03-31 15:17:11 -0400219import java.util.Objects;
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800220import java.util.concurrent.CountDownLatch;
221import java.util.concurrent.TimeUnit;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700222
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700223/**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700224 * Service that maintains low-level network policy rules, using
225 * {@link NetworkStatsService} statistics to drive those rules.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700226 * <p>
227 * Derives active rules by combining a given policy with other system status,
228 * and delivers to listeners, such as {@link ConnectivityManager}, for
229 * enforcement.
Felipe Lemef0823852016-06-08 13:43:08 -0700230 *
231 * <p>
Sudheer Shankac9d94072017-02-22 22:13:55 +0000232 * This class uses 2-3 locks to synchronize state:
Felipe Lemef0823852016-06-08 13:43:08 -0700233 * <ul>
234 * <li>{@code mUidRulesFirstLock}: used to guard state related to individual UIDs (such as firewall
235 * rules).
236 * <li>{@code mNetworkPoliciesSecondLock}: used to guard state related to network interfaces (such
237 * as network policies).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000238 * <li>{@code allLocks}: not a "real" lock, but an indication (through @GuardedBy) that all locks
239 * must be held.
Felipe Lemef0823852016-06-08 13:43:08 -0700240 * </ul>
241 *
242 * <p>
243 * As such, methods that require synchronization have the following prefixes:
244 * <ul>
245 * <li>{@code UL()}: require the "UID" lock ({@code mUidRulesFirstLock}).
246 * <li>{@code NL()}: require the "Network" lock ({@code mNetworkPoliciesSecondLock}).
Sudheer Shankac9d94072017-02-22 22:13:55 +0000247 * <li>{@code AL()}: require all locks, which must be obtained in order ({@code mUidRulesFirstLock}
248 * first, then {@code mNetworkPoliciesSecondLock}, then {@code mYetAnotherGuardThirdLock}, etc..
Felipe Lemef0823852016-06-08 13:43:08 -0700249 * </ul>
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700250 */
Xiaohui Chen8dca36d2015-06-19 12:44:59 -0700251public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub {
Felipe Lemede4e8e32016-02-02 18:55:22 -0800252 static final String TAG = "NetworkPolicy";
Hugo Benichi5d2f2b52017-04-07 08:53:25 +0900253 private static final boolean LOGD = false;
254 private static final boolean LOGV = false;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700255
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700256 private static final int VERSION_INIT = 1;
257 private static final int VERSION_ADDED_SNOOZE = 2;
Jeff Sharkey46645002011-07-27 21:11:21 -0700258 private static final int VERSION_ADDED_RESTRICT_BACKGROUND = 3;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800259 private static final int VERSION_ADDED_METERED = 4;
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800260 private static final int VERSION_SPLIT_SNOOZE = 5;
Jeff Sharkey9bf31502012-03-09 17:07:21 -0800261 private static final int VERSION_ADDED_TIMEZONE = 6;
Jeff Sharkey837f9242012-03-20 16:52:20 -0700262 private static final int VERSION_ADDED_INFERRED = 7;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700263 private static final int VERSION_SWITCH_APP_ID = 8;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700264 private static final int VERSION_ADDED_NETWORK_ID = 9;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700265 private static final int VERSION_SWITCH_UID = 10;
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600266 private static final int VERSION_ADDED_CYCLE = 11;
267 private static final int VERSION_LATEST = VERSION_ADDED_CYCLE;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700268
Sudheer Shankae7361852017-03-07 11:51:46 -0800269 /**
270 * Max items written to {@link #ProcStateSeqHistory}.
271 */
272 @VisibleForTesting
273 public static final int MAX_PROC_STATE_SEQ_HISTORY =
274 ActivityManager.isLowRamDeviceStatic() ? 50 : 200;
275
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800276 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400277 public static final int TYPE_WARNING = SystemMessage.NOTE_NET_WARNING;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800278 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400279 public static final int TYPE_LIMIT = SystemMessage.NOTE_NET_LIMIT;
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800280 @VisibleForTesting
Chris Wren193ae6b2017-03-31 15:17:11 -0400281 public static final int TYPE_LIMIT_SNOOZED = SystemMessage.NOTE_NET_LIMIT_SNOOZED;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700282
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700283 private static final String TAG_POLICY_LIST = "policy-list";
284 private static final String TAG_NETWORK_POLICY = "network-policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600285 private static final String TAG_SUBSCRIPTION_PLAN = "subscription-plan";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700286 private static final String TAG_UID_POLICY = "uid-policy";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700287 private static final String TAG_APP_POLICY = "app-policy";
Felipe Lemeb85a6372016-01-14 16:16:16 -0800288 private static final String TAG_WHITELIST = "whitelist";
289 private static final String TAG_RESTRICT_BACKGROUND = "restrict-background";
Felipe Lemea9505cc2016-02-26 10:28:41 -0800290 private static final String TAG_REVOKED_RESTRICT_BACKGROUND = "revoked-restrict-background";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700291
292 private static final String ATTR_VERSION = "version";
Jeff Sharkey46645002011-07-27 21:11:21 -0700293 private static final String ATTR_RESTRICT_BACKGROUND = "restrictBackground";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700294 private static final String ATTR_NETWORK_TEMPLATE = "networkTemplate";
295 private static final String ATTR_SUBSCRIBER_ID = "subscriberId";
Jeff Sharkey8fc27e82012-04-04 20:40:58 -0700296 private static final String ATTR_NETWORK_ID = "networkId";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600297 @Deprecated private static final String ATTR_CYCLE_DAY = "cycleDay";
298 @Deprecated private static final String ATTR_CYCLE_TIMEZONE = "cycleTimezone";
299 private static final String ATTR_CYCLE_START = "cycleStart";
300 private static final String ATTR_CYCLE_END = "cycleEnd";
301 private static final String ATTR_CYCLE_PERIOD = "cyclePeriod";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700302 private static final String ATTR_WARNING_BYTES = "warningBytes";
303 private static final String ATTR_LIMIT_BYTES = "limitBytes";
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700304 private static final String ATTR_LAST_SNOOZE = "lastSnooze";
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800305 private static final String ATTR_LAST_WARNING_SNOOZE = "lastWarningSnooze";
306 private static final String ATTR_LAST_LIMIT_SNOOZE = "lastLimitSnooze";
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -0800307 private static final String ATTR_METERED = "metered";
Jeff Sharkey837f9242012-03-20 16:52:20 -0700308 private static final String ATTR_INFERRED = "inferred";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700309 private static final String ATTR_UID = "uid";
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700310 private static final String ATTR_APP_ID = "appId";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700311 private static final String ATTR_POLICY = "policy";
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600312 private static final String ATTR_SUB_ID = "subId";
313 private static final String ATTR_TITLE = "title";
314 private static final String ATTR_SUMMARY = "summary";
315 private static final String ATTR_LIMIT_BEHAVIOR = "limitBehavior";
316 private static final String ATTR_USAGE_BYTES = "usageBytes";
317 private static final String ATTR_USAGE_TIME = "usageTime";
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600318 private static final String ATTR_OWNER_PACKAGE = "ownerPackage";
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700319
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800320 private static final String ACTION_ALLOW_BACKGROUND =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800321 "com.android.server.net.action.ALLOW_BACKGROUND";
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -0800322 private static final String ACTION_SNOOZE_WARNING =
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800323 "com.android.server.net.action.SNOOZE_WARNING";
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700324
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700325 private static final long TIME_CACHE_MAX_AGE = DAY_IN_MILLIS;
326
Svetoslav Ganov24c27752016-08-31 18:09:00 -0700327 private static final int MSG_RULES_CHANGED = 1;
Jeff Sharkey6f7af032011-11-01 18:25:15 -0700328 private static final int MSG_METERED_IFACES_CHANGED = 2;
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -0800329 private static final int MSG_LIMIT_REACHED = 5;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -0800330 private static final int MSG_RESTRICT_BACKGROUND_CHANGED = 6;
Jeff Sharkeye19f39b2012-05-24 10:21:16 -0700331 private static final int MSG_ADVISE_PERSIST_THRESHOLD = 7;
Amith Yamasani3646cbd2016-04-13 14:04:53 -0700332 private static final int MSG_UPDATE_INTERFACE_QUOTA = 10;
333 private static final int MSG_REMOVE_INTERFACE_QUOTA = 11;
Felipe Leme0ecfcd12016-09-06 12:49:48 -0700334 private static final int MSG_POLICIES_CHANGED = 13;
Felipe Leme03e95e22016-09-09 09:25:31 -0700335 private static final int MSG_RESET_FIREWALL_RULES_BY_UID = 15;
Jeff Sharkey4414cea2011-06-24 17:05:24 -0700336
Makoto Onuki8e777332017-03-28 11:25:47 -0700337 private static final int UID_MSG_STATE_CHANGED = 100;
338 private static final int UID_MSG_GONE = 101;
339
Jeff Sharkey75279902011-05-24 18:39:45 -0700340 private final Context mContext;
341 private final IActivityManager mActivityManager;
Jeff Sharkey75279902011-05-24 18:39:45 -0700342 private final INetworkStatsService mNetworkStats;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700343 private final INetworkManagementService mNetworkManager;
Amith Yamasani15e472352015-04-24 19:06:07 -0700344 private UsageStatsManagerInternal mUsageStats;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700345 private final TrustedTime mTime;
Stuart Scotte3e314d2015-04-20 14:07:45 -0700346 private final UserManager mUserManager;
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700347 private final CarrierConfigManager mCarrierConfigManager;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700348
349 private IConnectivityManager mConnManager;
Jeff Sharkey497e4432011-06-14 17:27:29 -0700350 private INotificationManager mNotifManager;
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700351 private PowerManagerInternal mPowerManagerInternal;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700352 private IDeviceIdleController mDeviceIdleController;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800353 @GuardedBy("mUidRulesFirstLock")
354 private PowerSaveState mRestrictBackgroundPowerState;
355
356 // Store the status of restrict background before turning on battery saver.
357 // Used to restore mRestrictBackground when battery saver is turned off.
358 private boolean mRestrictBackgroundBeforeBsm;
Jeff Sharkeya4620792011-05-20 15:29:23 -0700359
Felipe Lemef0823852016-06-08 13:43:08 -0700360 // See main javadoc for instructions on how to use these locks.
361 final Object mUidRulesFirstLock = new Object();
362 final Object mNetworkPoliciesSecondLock = new Object();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700363
Felipe Lemef0823852016-06-08 13:43:08 -0700364 @GuardedBy("allLocks") volatile boolean mSystemReady;
365
Felipe Lemef0823852016-06-08 13:43:08 -0700366 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackground;
367 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictPower;
368 @GuardedBy("mUidRulesFirstLock") volatile boolean mDeviceIdleMode;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800369 // Store whether user flipped restrict background in battery saver mode
370 @GuardedBy("mUidRulesFirstLock") volatile boolean mRestrictBackgroundChangedInBsm;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700371
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700372 private final boolean mSuppressDefaultPolicy;
373
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700374 /** Defined network policies. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600375 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800376 final ArrayMap<NetworkTemplate, NetworkPolicy> mNetworkPolicy = new ArrayMap<>();
Jeff Sharkey22c055e2011-06-12 21:13:51 -0700377
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600378 /** Map from subId to subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600379 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600380 final SparseArray<SubscriptionPlan[]> mSubscriptionPlans = new SparseArray<>();
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600381 /** Map from subId to package name that owns subscription plans. */
Jeff Sharkey4635f102017-09-01 11:27:13 -0600382 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkeyb74799882017-07-28 16:55:41 -0600383 final SparseArray<String> mSubscriptionPlansOwner = new SparseArray<>();
Jeff Sharkey17bebd22017-07-19 21:00:38 -0600384
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700385 /** Defined UID policies. */
Felipe Lemef0823852016-06-08 13:43:08 -0700386 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidPolicy = new SparseIntArray();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700387 /** Currently derived rules for each UID. */
Felipe Lemef0823852016-06-08 13:43:08 -0700388 @GuardedBy("mUidRulesFirstLock") final SparseIntArray mUidRules = new SparseIntArray();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700389
Felipe Lemef0823852016-06-08 13:43:08 -0700390 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700391 final SparseIntArray mUidFirewallStandbyRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700392 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkeydc988062015-09-14 10:09:47 -0700393 final SparseIntArray mUidFirewallDozableRules = new SparseIntArray();
Felipe Lemef0823852016-06-08 13:43:08 -0700394 @GuardedBy("mUidRulesFirstLock")
Felipe Leme011b98f2016-02-10 17:28:31 -0800395 final SparseIntArray mUidFirewallPowerSaveRules = new SparseIntArray();
Jeff Sharkeydc988062015-09-14 10:09:47 -0700396
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700397 /** Set of states for the child firewall chains. True if the chain is active. */
Felipe Lemef0823852016-06-08 13:43:08 -0700398 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700399 final SparseBooleanArray mFirewallChainStates = new SparseBooleanArray();
400
Jeff Sharkey32566012014-12-02 18:30:14 -0800401 /**
402 * UIDs that have been white-listed to always be able to have network access
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700403 * in power save mode, except device idle (doze) still applies.
404 * TODO: An int array might be sufficient
405 */
Felipe Lemef0823852016-06-08 13:43:08 -0700406 @GuardedBy("mUidRulesFirstLock")
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700407 private final SparseBooleanArray mPowerSaveWhitelistExceptIdleAppIds = new SparseBooleanArray();
408
409 /**
410 * UIDs that have been white-listed to always be able to have network access
Jeff Sharkey32566012014-12-02 18:30:14 -0800411 * in power save mode.
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700412 * TODO: An int array might be sufficient
Jeff Sharkey32566012014-12-02 18:30:14 -0800413 */
Felipe Lemef0823852016-06-08 13:43:08 -0700414 @GuardedBy("mUidRulesFirstLock")
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700415 private final SparseBooleanArray mPowerSaveWhitelistAppIds = new SparseBooleanArray();
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700416
Felipe Lemef0823852016-06-08 13:43:08 -0700417 @GuardedBy("mUidRulesFirstLock")
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700418 private final SparseBooleanArray mPowerSaveTempWhitelistAppIds = new SparseBooleanArray();
419
Felipe Lemeb85a6372016-01-14 16:16:16 -0800420 /**
Felipe Lemea9505cc2016-02-26 10:28:41 -0800421 * UIDs that have been initially white-listed by system to avoid restricted background.
422 */
Felipe Lemef0823852016-06-08 13:43:08 -0700423 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800424 private final SparseBooleanArray mDefaultRestrictBackgroundWhitelistUids =
425 new SparseBooleanArray();
426
427 /**
428 * UIDs that have been initially white-listed by system to avoid restricted background,
429 * but later revoked by user.
430 */
Felipe Lemef0823852016-06-08 13:43:08 -0700431 @GuardedBy("mUidRulesFirstLock")
Felipe Lemea9505cc2016-02-26 10:28:41 -0800432 private final SparseBooleanArray mRestrictBackgroundWhitelistRevokedUids =
433 new SparseBooleanArray();
434
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700435 /** Set of ifaces that are metered. */
Felipe Lemef0823852016-06-08 13:43:08 -0700436 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800437 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700438 /** Set of over-limit templates that have been notified. */
Felipe Lemef0823852016-06-08 13:43:08 -0700439 @GuardedBy("mNetworkPoliciesSecondLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800440 private final ArraySet<NetworkTemplate> mOverLimitNotified = new ArraySet<>();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700441
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700442 /** Set of currently active {@link Notification} tags. */
Felipe Lemef0823852016-06-08 13:43:08 -0700443 @GuardedBy("mNetworkPoliciesSecondLock")
Chris Wren193ae6b2017-03-31 15:17:11 -0400444 private final ArraySet<NotificationId> mActiveNotifs = new ArraySet<>();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700445
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700446 /** Foreground at UID granularity. */
Felipe Lemef0823852016-06-08 13:43:08 -0700447 @GuardedBy("mUidRulesFirstLock")
Jeff Sharkey32566012014-12-02 18:30:14 -0800448 final SparseIntArray mUidState = new SparseIntArray();
Dianne Hackborn497175b2014-07-01 12:56:08 -0700449
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600450 /** Map from network ID to last observed meteredness state */
451 @GuardedBy("mNetworkPoliciesSecondLock")
452 private final SparseBooleanArray mNetworkMetered = new SparseBooleanArray();
453
Jeff Sharkey32566012014-12-02 18:30:14 -0800454 private final RemoteCallbackList<INetworkPolicyListener>
455 mListeners = new RemoteCallbackList<>();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700456
Dianne Hackborn497175b2014-07-01 12:56:08 -0700457 final Handler mHandler;
Sudheer Shankaed25ce62017-03-29 20:46:30 -0700458 @VisibleForTesting
459 public final Handler mUidEventHandler;
Makoto Onuki8e777332017-03-28 11:25:47 -0700460
461 private final ServiceThread mUidEventThread;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700462
Felipe Lemef0823852016-06-08 13:43:08 -0700463 @GuardedBy("allLocks")
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700464 private final AtomicFile mPolicyFile;
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700465
Svet Ganov16a16892015-04-16 10:32:04 -0700466 private final AppOpsManager mAppOps;
467
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -0800468 private final IPackageManager mIPm;
469
Sudheer Shankae7361852017-03-07 11:51:46 -0800470 private ActivityManagerInternal mActivityManagerInternal;
471
472 /**
473 * This is used for debugging purposes. Whenever the IUidObserver.onUidStateChanged is called,
474 * the uid and procStateSeq will be written to this and will be printed as part of dump.
475 */
476 @VisibleForTesting
477 public ProcStateSeqHistory mObservedHistory
478 = new ProcStateSeqHistory(MAX_PROC_STATE_SEQ_HISTORY);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800479
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700480 // TODO: keep whitelist of system-critical services that should never have
481 // rules enforced, such as system, phone, and radio UIDs.
482
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700483 // TODO: migrate notifications to SystemUI
484
Jeff Sharkey75279902011-05-24 18:39:45 -0700485 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700486 INetworkStatsService networkStats, INetworkManagementService networkManagement) {
487 this(context, activityManager, networkStats, networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700488 AppGlobals.getPackageManager(), NtpTrustedTime.getInstance(context), getSystemDir(),
489 false);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700490 }
491
492 private static File getSystemDir() {
493 return new File(Environment.getDataDirectory(), "system");
494 }
495
496 public NetworkPolicyManagerService(Context context, IActivityManager activityManager,
Felipe Leme88f40ad2016-08-10 13:00:32 -0700497 INetworkStatsService networkStats, INetworkManagementService networkManagement,
Felipe Leme3d3308d2016-08-23 17:41:47 -0700498 IPackageManager pm, TrustedTime time, File systemDir, boolean suppressDefaultPolicy) {
Jeff Sharkeya4620792011-05-20 15:29:23 -0700499 mContext = checkNotNull(context, "missing context");
500 mActivityManager = checkNotNull(activityManager, "missing activityManager");
Jeff Sharkey75279902011-05-24 18:39:45 -0700501 mNetworkStats = checkNotNull(networkStats, "missing networkStats");
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -0700502 mNetworkManager = checkNotNull(networkManagement, "missing networkManagement");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700503 mDeviceIdleController = IDeviceIdleController.Stub.asInterface(ServiceManager.getService(
Dianne Hackborn1958e5e2015-06-12 18:11:41 -0700504 Context.DEVICE_IDLE_CONTROLLER));
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700505 mTime = checkNotNull(time, "missing TrustedTime");
Stuart Scotte3e314d2015-04-20 14:07:45 -0700506 mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700507 mCarrierConfigManager = mContext.getSystemService(CarrierConfigManager.class);
Felipe Leme3d3308d2016-08-23 17:41:47 -0700508 mIPm = pm;
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700509
Amith Yamasani450a16b2013-09-18 16:28:50 -0700510 HandlerThread thread = new HandlerThread(TAG);
511 thread.start();
512 mHandler = new Handler(thread.getLooper(), mHandlerCallback);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700513
Makoto Onuki8e777332017-03-28 11:25:47 -0700514 // We create another thread for the UID events, which are more time-critical.
515 mUidEventThread = new ServiceThread(TAG + ".uid", Process.THREAD_PRIORITY_FOREGROUND,
516 /*allowIo=*/ false);
517 mUidEventThread.start();
518 mUidEventHandler = new Handler(mUidEventThread.getLooper(), mUidEventHandlerCallback);
519
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700520 mSuppressDefaultPolicy = suppressDefaultPolicy;
521
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700522 mPolicyFile = new AtomicFile(new File(systemDir, "netpolicy.xml"));
Svet Ganov16a16892015-04-16 10:32:04 -0700523
524 mAppOps = context.getSystemService(AppOpsManager.class);
Felipe Lemeb85a6372016-01-14 16:16:16 -0800525
Felipe Lemed17fda42016-04-29 11:12:45 -0700526 // Expose private service for system components to use.
527 LocalServices.addService(NetworkPolicyManagerInternal.class,
528 new NetworkPolicyManagerInternalImpl());
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700529 }
530
531 public void bindConnectivityManager(IConnectivityManager connManager) {
532 mConnManager = checkNotNull(connManager, "missing IConnectivityManager");
Jeff Sharkeya4620792011-05-20 15:29:23 -0700533 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700534
Jeff Sharkey497e4432011-06-14 17:27:29 -0700535 public void bindNotificationManager(INotificationManager notifManager) {
536 mNotifManager = checkNotNull(notifManager, "missing INotificationManager");
537 }
538
Felipe Lemef0823852016-06-08 13:43:08 -0700539 void updatePowerSaveWhitelistUL() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700540 try {
Dianne Hackborn4a503b12015-08-06 22:19:06 -0700541 int[] whitelist = mDeviceIdleController.getAppIdWhitelistExceptIdle();
542 mPowerSaveWhitelistExceptIdleAppIds.clear();
543 if (whitelist != null) {
544 for (int uid : whitelist) {
545 mPowerSaveWhitelistExceptIdleAppIds.put(uid, true);
546 }
547 }
548 whitelist = mDeviceIdleController.getAppIdWhitelist();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700549 mPowerSaveWhitelistAppIds.clear();
550 if (whitelist != null) {
551 for (int uid : whitelist) {
552 mPowerSaveWhitelistAppIds.put(uid, true);
553 }
554 }
555 } catch (RemoteException e) {
556 }
557 }
558
Felipe Lemea9505cc2016-02-26 10:28:41 -0800559 /**
560 * Whitelists pre-defined apps for restrict background, but only if the user didn't already
561 * revoke the whitelist.
562 *
Felipe Leme46b451f2016-08-19 08:46:17 -0700563 * @return whether any uid has been whitelisted.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800564 */
Felipe Lemef0823852016-06-08 13:43:08 -0700565 boolean addDefaultRestrictBackgroundWhitelistUidsUL() {
Felipe Lemea9505cc2016-02-26 10:28:41 -0800566 final List<UserInfo> users = mUserManager.getUsers();
567 final int numberUsers = users.size();
568
Felipe Lemea110eec2016-04-29 09:58:06 -0700569 boolean changed = false;
570 for (int i = 0; i < numberUsers; i++) {
571 final UserInfo user = users.get(i);
Felipe Lemef0823852016-06-08 13:43:08 -0700572 changed = addDefaultRestrictBackgroundWhitelistUidsUL(user.id) || changed;
Felipe Lemea110eec2016-04-29 09:58:06 -0700573 }
574 return changed;
575 }
576
Felipe Lemef0823852016-06-08 13:43:08 -0700577 private boolean addDefaultRestrictBackgroundWhitelistUidsUL(int userId) {
Felipe Lemea110eec2016-04-29 09:58:06 -0700578 final SystemConfig sysConfig = SystemConfig.getInstance();
579 final PackageManager pm = mContext.getPackageManager();
Felipe Lemea9505cc2016-02-26 10:28:41 -0800580 final ArraySet<String> allowDataUsage = sysConfig.getAllowInDataUsageSave();
581 boolean changed = false;
582 for (int i = 0; i < allowDataUsage.size(); i++) {
583 final String pkg = allowDataUsage.valueAt(i);
584 if (LOGD)
Felipe Lemea110eec2016-04-29 09:58:06 -0700585 Slog.d(TAG, "checking restricted background whitelisting for package " + pkg
586 + " and user " + userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800587 final ApplicationInfo app;
588 try {
Felipe Lemea110eec2016-04-29 09:58:06 -0700589 app = pm.getApplicationInfoAsUser(pkg, PackageManager.MATCH_SYSTEM_ONLY, userId);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800590 } catch (PackageManager.NameNotFoundException e) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700591 if (LOGD) Slog.d(TAG, "No ApplicationInfo for package " + pkg);
592 // Ignore it - some apps on allow-in-data-usage-save are optional.
Felipe Lemea9505cc2016-02-26 10:28:41 -0800593 continue;
594 }
595 if (!app.isPrivilegedApp()) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700596 Slog.e(TAG, "addDefaultRestrictBackgroundWhitelistUidsUL(): "
597 + "skipping non-privileged app " + pkg);
Felipe Lemea9505cc2016-02-26 10:28:41 -0800598 continue;
599 }
Felipe Lemea110eec2016-04-29 09:58:06 -0700600 final int uid = UserHandle.getUid(userId, app.uid);
601 mDefaultRestrictBackgroundWhitelistUids.append(uid, true);
602 if (LOGD)
603 Slog.d(TAG, "Adding uid " + uid + " (user " + userId + ") to default restricted "
604 + "background whitelist. Revoked status: "
Felipe Lemea9505cc2016-02-26 10:28:41 -0800605 + mRestrictBackgroundWhitelistRevokedUids.get(uid));
Felipe Lemea110eec2016-04-29 09:58:06 -0700606 if (!mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
Felipe Lemea1252b22016-08-31 08:47:50 -0700607 if (LOGD)
608 Slog.d(TAG, "adding default package " + pkg + " (uid " + uid + " for user "
609 + userId + ") to restrict background whitelist");
Felipe Leme46b451f2016-08-19 08:46:17 -0700610 setUidPolicyUncheckedUL(uid, POLICY_ALLOW_METERED_BACKGROUND, false);
Felipe Lemea110eec2016-04-29 09:58:06 -0700611 changed = true;
Felipe Lemea9505cc2016-02-26 10:28:41 -0800612 }
613 }
614 return changed;
615 }
616
Felipe Lemef0823852016-06-08 13:43:08 -0700617 void updatePowerSaveTempWhitelistUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700618 try {
Amith Yamasani06f08062015-06-12 13:23:33 -0700619 // Clear the states of the current whitelist
620 final int N = mPowerSaveTempWhitelistAppIds.size();
621 for (int i = 0; i < N; i++) {
622 mPowerSaveTempWhitelistAppIds.setValueAt(i, false);
623 }
624 // Update the states with the new whitelist
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700625 final int[] whitelist = mDeviceIdleController.getAppIdTempWhitelist();
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700626 if (whitelist != null) {
627 for (int uid : whitelist) {
628 mPowerSaveTempWhitelistAppIds.put(uid, true);
629 }
630 }
631 } catch (RemoteException e) {
632 }
633 }
634
Amith Yamasani06f08062015-06-12 13:23:33 -0700635 /**
636 * Remove unnecessary entries in the temp whitelist
637 */
Felipe Lemef0823852016-06-08 13:43:08 -0700638 void purgePowerSaveTempWhitelistUL() {
Amith Yamasani06f08062015-06-12 13:23:33 -0700639 final int N = mPowerSaveTempWhitelistAppIds.size();
640 for (int i = N - 1; i >= 0; i--) {
641 if (mPowerSaveTempWhitelistAppIds.valueAt(i) == false) {
642 mPowerSaveTempWhitelistAppIds.removeAt(i);
643 }
644 }
645 }
646
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800647 private void initService(CountDownLatch initCompleteSignal) {
Felipe Leme873a83a2016-09-07 11:34:10 -0700648 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "systemReady");
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800649 final int oldPriority = Process.getThreadPriority(Process.myTid());
Felipe Leme873a83a2016-09-07 11:34:10 -0700650 try {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800651 // Boost thread's priority during system server init
652 Process.setThreadPriority(Process.THREAD_PRIORITY_FOREGROUND);
Felipe Leme873a83a2016-09-07 11:34:10 -0700653 if (!isBandwidthControlEnabled()) {
654 Slog.w(TAG, "bandwidth controls disabled, unable to enforce policy");
655 return;
656 }
Jeff Sharkey8c1dc722012-05-04 14:49:37 -0700657
Felipe Leme873a83a2016-09-07 11:34:10 -0700658 mUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);
Amith Yamasani15e472352015-04-24 19:06:07 -0700659
Felipe Leme873a83a2016-09-07 11:34:10 -0700660 synchronized (mUidRulesFirstLock) {
661 synchronized (mNetworkPoliciesSecondLock) {
662 updatePowerSaveWhitelistUL();
663 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
664 mPowerManagerInternal.registerLowPowerModeObserver(
665 new PowerManagerInternal.LowPowerModeListener() {
jackqdyulei455e90a2017-02-09 15:29:16 -0800666 @Override
667 public int getServiceType() {
668 return ServiceType.NETWORK_FIREWALL;
Felipe Leme873a83a2016-09-07 11:34:10 -0700669 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800670
671 @Override
672 public void onLowPowerModeChanged(PowerSaveState result) {
673 final boolean enabled = result.batterySaverEnabled;
jackqdyulei29c82ab2017-03-10 14:09:16 -0800674 if (LOGD) {
675 Slog.d(TAG, "onLowPowerModeChanged(" + enabled + ")");
676 }
jackqdyulei455e90a2017-02-09 15:29:16 -0800677 synchronized (mUidRulesFirstLock) {
678 if (mRestrictPower != enabled) {
679 mRestrictPower = enabled;
680 updateRulesForRestrictPowerUL();
681 }
682 }
683 }
jackqdyulei29c82ab2017-03-10 14:09:16 -0800684 });
jackqdyulei455e90a2017-02-09 15:29:16 -0800685 mRestrictPower = mPowerManagerInternal.getLowPowerState(
686 ServiceType.NETWORK_FIREWALL).batterySaverEnabled;
Felipe Leme873a83a2016-09-07 11:34:10 -0700687
688 mSystemReady = true;
689
690 // read policy from disk
691 readPolicyAL();
692
jackqdyulei29c82ab2017-03-10 14:09:16 -0800693 // Update the restrictBackground if battery saver is turned on
694 mRestrictBackgroundBeforeBsm = mRestrictBackground;
695 mRestrictBackgroundPowerState = mPowerManagerInternal
696 .getLowPowerState(ServiceType.DATA_SAVER);
697 final boolean localRestrictBackground =
698 mRestrictBackgroundPowerState.batterySaverEnabled;
699 if (localRestrictBackground && localRestrictBackground != mRestrictBackground) {
700 mRestrictBackground = localRestrictBackground;
701 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
702 mRestrictBackground ? 1 : 0, 0).sendToTarget();
703 }
704 mPowerManagerInternal.registerLowPowerModeObserver(
705 new PowerManagerInternal.LowPowerModeListener() {
706 @Override
707 public int getServiceType() {
708 return ServiceType.DATA_SAVER;
709 }
710
711 @Override
712 public void onLowPowerModeChanged(PowerSaveState result) {
713 synchronized (mUidRulesFirstLock) {
714 updateRestrictBackgroundByLowPowerModeUL(result);
715 }
716 }
717 });
718
Felipe Leme873a83a2016-09-07 11:34:10 -0700719 if (addDefaultRestrictBackgroundWhitelistUidsUL()) {
720 writePolicyAL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700721 }
Felipe Lemef0823852016-06-08 13:43:08 -0700722
Felipe Leme873a83a2016-09-07 11:34:10 -0700723 setRestrictBackgroundUL(mRestrictBackground);
724 updateRulesForGlobalChangeAL(false);
725 updateNotificationsNL();
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -0700726 }
Felipe Lemea9505cc2016-02-26 10:28:41 -0800727 }
Felipe Leme873a83a2016-09-07 11:34:10 -0700728
Sudheer Shankae7361852017-03-07 11:51:46 -0800729 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class);
Felipe Leme873a83a2016-09-07 11:34:10 -0700730 try {
731 mActivityManager.registerUidObserver(mUidObserver,
Sudheer Shankac9d94072017-02-22 22:13:55 +0000732 ActivityManager.UID_OBSERVER_PROCSTATE|ActivityManager.UID_OBSERVER_GONE,
Dianne Hackborn5614bf52016-11-07 17:26:41 -0800733 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Felipe Leme873a83a2016-09-07 11:34:10 -0700734 mNetworkManager.registerObserver(mAlertObserver);
735 } catch (RemoteException e) {
736 // ignored; both services live in system_server
737 }
738
739 // listen for changes to power save whitelist
740 final IntentFilter whitelistFilter = new IntentFilter(
741 PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED);
742 mContext.registerReceiver(mPowerSaveWhitelistReceiver, whitelistFilter, null, mHandler);
743
744 DeviceIdleController.LocalService deviceIdleService
745 = LocalServices.getService(DeviceIdleController.LocalService.class);
746 deviceIdleService.setNetworkPolicyTempWhitelistCallback(mTempPowerSaveChangedCallback);
747
748 // watch for network interfaces to be claimed
749 final IntentFilter connFilter = new IntentFilter(CONNECTIVITY_ACTION);
750 mContext.registerReceiver(mConnReceiver, connFilter, CONNECTIVITY_INTERNAL, mHandler);
751
752 // listen for package changes to update policy
753 final IntentFilter packageFilter = new IntentFilter();
754 packageFilter.addAction(ACTION_PACKAGE_ADDED);
755 packageFilter.addDataScheme("package");
756 mContext.registerReceiver(mPackageReceiver, packageFilter, null, mHandler);
757
758 // listen for UID changes to update policy
759 mContext.registerReceiver(
760 mUidRemovedReceiver, new IntentFilter(ACTION_UID_REMOVED), null, mHandler);
761
762 // listen for user changes to update policy
763 final IntentFilter userFilter = new IntentFilter();
764 userFilter.addAction(ACTION_USER_ADDED);
765 userFilter.addAction(ACTION_USER_REMOVED);
766 mContext.registerReceiver(mUserReceiver, userFilter, null, mHandler);
767
768 // listen for stats update events
769 final IntentFilter statsFilter = new IntentFilter(ACTION_NETWORK_STATS_UPDATED);
770 mContext.registerReceiver(
771 mStatsReceiver, statsFilter, READ_NETWORK_USAGE_HISTORY, mHandler);
772
773 // listen for restrict background changes from notifications
774 final IntentFilter allowFilter = new IntentFilter(ACTION_ALLOW_BACKGROUND);
775 mContext.registerReceiver(mAllowReceiver, allowFilter, MANAGE_NETWORK_POLICY, mHandler);
776
777 // listen for snooze warning from notifications
778 final IntentFilter snoozeWarningFilter = new IntentFilter(ACTION_SNOOZE_WARNING);
779 mContext.registerReceiver(mSnoozeWarningReceiver, snoozeWarningFilter,
780 MANAGE_NETWORK_POLICY, mHandler);
781
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600782 // listen for configured wifi networks to be loaded
783 final IntentFilter wifiFilter =
784 new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION);
785 mContext.registerReceiver(mWifiReceiver, wifiFilter, null, mHandler);
Felipe Leme873a83a2016-09-07 11:34:10 -0700786
Ammar Aijazi6ce48e22017-03-28 15:43:22 -0700787 // listen for carrier config changes to update data cycle information
788 final IntentFilter carrierConfigFilter = new IntentFilter(
789 ACTION_CARRIER_CONFIG_CHANGED);
790 mContext.registerReceiver(mCarrierConfigReceiver, carrierConfigFilter, null, mHandler);
791
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600792 // listen for meteredness changes
793 mContext.getSystemService(ConnectivityManager.class).registerNetworkCallback(
794 new NetworkRequest.Builder().build(), mNetworkCallback);
795
Felipe Leme873a83a2016-09-07 11:34:10 -0700796 mUsageStats.addAppIdleStateChangeListener(new AppIdleStateChangeListener());
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800797 // tell systemReady() that the service has been initialized
798 initCompleteSignal.countDown();
Felipe Leme873a83a2016-09-07 11:34:10 -0700799 } finally {
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800800 // Restore the default priority after init is done
801 Process.setThreadPriority(oldPriority);
Felipe Leme873a83a2016-09-07 11:34:10 -0700802 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700803 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -0700804 }
805
Fyodor Kupolov311b9fa2016-12-02 16:24:35 -0800806 public CountDownLatch networkScoreAndNetworkManagementServiceReady() {
807 final CountDownLatch initCompleteSignal = new CountDownLatch(1);
808 mHandler.post(() -> initService(initCompleteSignal));
809 return initCompleteSignal;
810 }
811
812 public void systemReady(CountDownLatch initCompleteSignal) {
813 // wait for initService to complete
814 try {
815 if (!initCompleteSignal.await(30, TimeUnit.SECONDS)) {
816 throw new IllegalStateException("Service " + TAG +" init timeout");
817 }
818 } catch (InterruptedException e) {
819 Thread.currentThread().interrupt();
820 throw new IllegalStateException("Service " + TAG + " init interrupted", e);
821 }
822 }
823
Sudheer Shankac9d94072017-02-22 22:13:55 +0000824 final private IUidObserver mUidObserver = new IUidObserver.Stub() {
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700825 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700826 mUidEventHandler.obtainMessage(UID_MSG_STATE_CHANGED,
827 uid, procState, procStateSeq).sendToTarget();
Dianne Hackborna93c2c12012-05-31 15:29:36 -0700828 }
829
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700830 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki8e777332017-03-28 11:25:47 -0700831 mUidEventHandler.obtainMessage(UID_MSG_GONE, uid, 0).sendToTarget();
Jeff Sharkeya4620792011-05-20 15:29:23 -0700832 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700833
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700834 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700835 }
836
Dianne Hackborn3e99f652017-07-05 16:33:56 -0700837 @Override public void onUidIdle(int uid, boolean disabled) {
838 }
839
840 @Override public void onUidCachedChanged(int uid, boolean cached) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700841 }
Jeff Sharkeya4620792011-05-20 15:29:23 -0700842 };
843
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700844 final private BroadcastReceiver mPowerSaveWhitelistReceiver = new BroadcastReceiver() {
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700845 @Override
846 public void onReceive(Context context, Intent intent) {
847 // on background handler thread, and POWER_SAVE_WHITELIST_CHANGED is protected
Felipe Lemef0823852016-06-08 13:43:08 -0700848 synchronized (mUidRulesFirstLock) {
849 updatePowerSaveWhitelistUL();
850 updateRulesForRestrictPowerUL();
Felipe Leme09700462016-09-08 09:33:48 -0700851 updateRulesForAppIdleUL();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700852 }
853 }
854 };
855
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700856 final private Runnable mTempPowerSaveChangedCallback = new Runnable() {
857 @Override
858 public void run() {
Felipe Lemef0823852016-06-08 13:43:08 -0700859 synchronized (mUidRulesFirstLock) {
860 updatePowerSaveTempWhitelistUL();
861 updateRulesForTempWhitelistChangeUL();
862 purgePowerSaveTempWhitelistUL();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700863 }
864 }
865 };
866
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700867 final private BroadcastReceiver mPackageReceiver = new BroadcastReceiver() {
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700868 @Override
869 public void onReceive(Context context, Intent intent) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700870 // on background handler thread, and PACKAGE_ADDED is protected
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700871
872 final String action = intent.getAction();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700873 final int uid = intent.getIntExtra(EXTRA_UID, -1);
874 if (uid == -1) return;
Jeff Sharkey8a8b5812012-03-21 18:13:36 -0700875
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700876 if (ACTION_PACKAGE_ADDED.equals(action)) {
877 // update rules for UID, since it might be subject to
878 // global background data policy
879 if (LOGV) Slog.v(TAG, "ACTION_PACKAGE_ADDED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700880 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700881 updateRestrictionRulesForUidUL(uid);
Jeff Sharkey02e21d62011-07-17 15:53:33 -0700882 }
Jeff Sharkeyb09540f2011-06-19 01:08:12 -0700883 }
884 }
885 };
886
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700887 final private BroadcastReceiver mUidRemovedReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700888 @Override
889 public void onReceive(Context context, Intent intent) {
890 // on background handler thread, and UID_REMOVED is protected
891
892 final int uid = intent.getIntExtra(EXTRA_UID, -1);
893 if (uid == -1) return;
894
895 // remove any policy and update rules to clean up
896 if (LOGV) Slog.v(TAG, "ACTION_UID_REMOVED for uid=" + uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700897 synchronized (mUidRulesFirstLock) {
Felipe Leme03e95e22016-09-09 09:25:31 -0700898 onUidDeletedUL(uid);
Felipe Lemef0823852016-06-08 13:43:08 -0700899 synchronized (mNetworkPoliciesSecondLock) {
900 writePolicyAL();
901 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700902 }
903 }
904 };
905
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700906 final private BroadcastReceiver mUserReceiver = new BroadcastReceiver() {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700907 @Override
908 public void onReceive(Context context, Intent intent) {
909 // on background handler thread, and USER_ADDED and USER_REMOVED
910 // broadcasts are protected
911
912 final String action = intent.getAction();
913 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
914 if (userId == -1) return;
915
Amith Yamasani15e472352015-04-24 19:06:07 -0700916 switch (action) {
917 case ACTION_USER_REMOVED:
918 case ACTION_USER_ADDED:
Felipe Lemef0823852016-06-08 13:43:08 -0700919 synchronized (mUidRulesFirstLock) {
Fyodor Kupolova31c5912016-01-22 11:26:09 -0800920 // Remove any persistable state for the given user; both cleaning up after a
Amith Yamasani15e472352015-04-24 19:06:07 -0700921 // USER_REMOVED, and one last sanity check during USER_ADDED
Felipe Lemef0823852016-06-08 13:43:08 -0700922 removeUserStateUL(userId, true);
Felipe Lemea110eec2016-04-29 09:58:06 -0700923 if (action == ACTION_USER_ADDED) {
924 // Add apps that are whitelisted by default.
Felipe Lemef0823852016-06-08 13:43:08 -0700925 addDefaultRestrictBackgroundWhitelistUidsUL(userId);
Felipe Lemea110eec2016-04-29 09:58:06 -0700926 }
927 // Update global restrict for that user
Felipe Lemef0823852016-06-08 13:43:08 -0700928 synchronized (mNetworkPoliciesSecondLock) {
929 updateRulesForGlobalChangeAL(true);
930 }
Amith Yamasani15e472352015-04-24 19:06:07 -0700931 }
932 break;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -0700933 }
934 }
935 };
936
Jeff Sharkey21c9c452011-06-07 12:26:43 -0700937 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -0700938 * Receiver that watches for {@link INetworkStatsService} updates, which we
939 * use to check against {@link NetworkPolicy#warningBytes}.
940 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700941 final private BroadcastReceiver mStatsReceiver = new BroadcastReceiver() {
Jeff Sharkey497e4432011-06-14 17:27:29 -0700942 @Override
943 public void onReceive(Context context, Intent intent) {
944 // on background handler thread, and verified
945 // READ_NETWORK_USAGE_HISTORY permission above.
946
Jeff Sharkey684c54a2011-11-16 17:46:30 -0800947 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -0700948 synchronized (mNetworkPoliciesSecondLock) {
949 updateNetworkEnabledNL();
950 updateNotificationsNL();
Jeff Sharkey497e4432011-06-14 17:27:29 -0700951 }
952 }
953 };
954
955 /**
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700956 * Receiver that watches for {@link Notification} control of
957 * {@link #mRestrictBackground}.
958 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700959 final private BroadcastReceiver mAllowReceiver = new BroadcastReceiver() {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -0700960 @Override
961 public void onReceive(Context context, Intent intent) {
962 // on background handler thread, and verified MANAGE_NETWORK_POLICY
963 // permission above.
964
965 setRestrictBackground(false);
966 }
967 };
968
969 /**
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800970 * Receiver that watches for {@link Notification} control of
971 * {@link NetworkPolicy#lastWarningSnooze}.
972 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -0700973 final private BroadcastReceiver mSnoozeWarningReceiver = new BroadcastReceiver() {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -0800974 @Override
975 public void onReceive(Context context, Intent intent) {
976 // on background handler thread, and verified MANAGE_NETWORK_POLICY
977 // permission above.
978
979 final NetworkTemplate template = intent.getParcelableExtra(EXTRA_NETWORK_TEMPLATE);
980 performSnooze(template, TYPE_WARNING);
981 }
982 };
983
984 /**
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600985 * Receiver that watches for {@link WifiConfiguration} to be loaded so that
Jeff Sharkey64c96ec2017-08-30 16:28:26 -0600986 * we can perform upgrade logic. After initial upgrade logic, it updates
987 * {@link #mMeteredIfaces} based on configuration changes.
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700988 */
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600989 final private BroadcastReceiver mWifiReceiver = new BroadcastReceiver() {
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -0700990 @Override
991 public void onReceive(Context context, Intent intent) {
Hugo Benichi446c9c92017-04-10 09:41:10 +0900992 synchronized (mUidRulesFirstLock) {
993 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey43d2a172017-07-12 10:50:42 -0600994 upgradeWifiMeteredOverrideAL();
Jeff Sharkeyb43a2922017-09-13 17:30:45 -0600995 }
996 }
997 // Only need to perform upgrade logic once
998 mContext.unregisterReceiver(this);
999 }
1000 };
1001
1002 private final NetworkCallback mNetworkCallback = new NetworkCallback() {
1003 @Override
1004 public void onCapabilitiesChanged(Network network,
1005 NetworkCapabilities networkCapabilities) {
1006 if (network == null || networkCapabilities == null) return;
1007
1008 synchronized (mNetworkPoliciesSecondLock) {
1009 final boolean oldMetered = mNetworkMetered.get(network.netId, false);
1010 final boolean newMetered = !networkCapabilities
1011 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1012
1013 if ((oldMetered != newMetered) || mNetworkMetered.indexOfKey(network.netId) < 0) {
1014 mNetworkMetered.put(network.netId, newMetered);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001015 updateNetworkRulesNL();
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07001016 }
1017 }
1018 }
1019 };
1020
1021 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001022 * Observer that watches for {@link INetworkManagementService} alerts.
1023 */
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07001024 final private INetworkManagementEventObserver mAlertObserver
1025 = new BaseNetworkObserver() {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001026 @Override
1027 public void limitReached(String limitName, String iface) {
1028 // only someone like NMS should be calling us
1029 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
1030
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08001031 if (!LIMIT_GLOBAL_ALERT.equals(limitName)) {
1032 mHandler.obtainMessage(MSG_LIMIT_REACHED, iface).sendToTarget();
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001033 }
1034 }
1035 };
1036
1037 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001038 * Check {@link NetworkPolicy} against current {@link INetworkStatsService}
1039 * to show visible notifications as needed.
1040 */
Felipe Lemef0823852016-06-08 13:43:08 -07001041 void updateNotificationsNL() {
1042 if (LOGV) Slog.v(TAG, "updateNotificationsNL()");
Jeff Sharkey497e4432011-06-14 17:27:29 -07001043
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001044 // keep track of previously active notifications
Chris Wren193ae6b2017-03-31 15:17:11 -04001045 final ArraySet<NotificationId> beforeNotifs = new ArraySet<NotificationId>(mActiveNotifs);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001046 mActiveNotifs.clear();
Jeff Sharkey497e4432011-06-14 17:27:29 -07001047
1048 // TODO: when switching to kernel notifications, compute next future
1049 // cycle boundary to recompute notifications.
1050
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001051 // examine stats for each active policy
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001052 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1053 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001054 // ignore policies that aren't relevant to user
1055 if (!isTemplateRelevant(policy.template)) continue;
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001056 if (!policy.hasCycle()) continue;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001057
Jeff Sharkey53313d72017-07-13 16:47:32 -06001058 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1059 .cycleIterator(policy).next();
1060 final long start = cycle.first.toInstant().toEpochMilli();
1061 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001062 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001063
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001064 if (policy.isOverLimit(totalBytes)) {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001065 if (policy.lastLimitSnooze >= start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001066 enqueueNotification(policy, TYPE_LIMIT_SNOOZED, totalBytes);
1067 } else {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001068 enqueueNotification(policy, TYPE_LIMIT, totalBytes);
Felipe Lemef0823852016-06-08 13:43:08 -07001069 notifyOverLimitNL(policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001070 }
1071
Jeff Sharkey497e4432011-06-14 17:27:29 -07001072 } else {
Felipe Lemef0823852016-06-08 13:43:08 -07001073 notifyUnderLimitNL(policy.template);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001074
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001075 if (policy.isOverWarning(totalBytes) && policy.lastWarningSnooze < start) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001076 enqueueNotification(policy, TYPE_WARNING, totalBytes);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001077 }
1078 }
Jeff Sharkey02e21d62011-07-17 15:53:33 -07001079 }
1080
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001081 // cancel stale notifications that we didn't renew above
Dianne Hackborn497175b2014-07-01 12:56:08 -07001082 for (int i = beforeNotifs.size()-1; i >= 0; i--) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001083 final NotificationId notificationId = beforeNotifs.valueAt(i);
1084 if (!mActiveNotifs.contains(notificationId)) {
1085 cancelNotification(notificationId);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001086 }
1087 }
1088 }
1089
1090 /**
1091 * Test if given {@link NetworkTemplate} is relevant to user based on
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001092 * current device state, such as when
1093 * {@link TelephonyManager#getSubscriberId()} matches. This is regardless of
1094 * data connection status.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001095 */
1096 private boolean isTemplateRelevant(NetworkTemplate template) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001097 if (template.isMatchRuleMobile()) {
1098 final TelephonyManager tele = TelephonyManager.from(mContext);
1099 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001100
Jeff Sharkey32566012014-12-02 18:30:14 -08001101 // Mobile template is relevant when any active subscriber matches
1102 final int[] subIds = sub.getActiveSubscriptionIdList();
1103 for (int subId : subIds) {
1104 final String subscriberId = tele.getSubscriberId(subId);
1105 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001106 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1107 true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001108 if (template.matches(probeIdent)) {
1109 return true;
Jeff Sharkey3a66cf32012-03-20 17:00:01 -07001110 }
Jeff Sharkey32566012014-12-02 18:30:14 -08001111 }
1112 return false;
1113 } else {
1114 return true;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001115 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001116 }
1117
1118 /**
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001119 * Notify that given {@link NetworkTemplate} is over
1120 * {@link NetworkPolicy#limitBytes}, potentially showing dialog to user.
1121 */
Felipe Lemef0823852016-06-08 13:43:08 -07001122 private void notifyOverLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001123 if (!mOverLimitNotified.contains(template)) {
Wei Liu546cb772016-07-21 16:19:01 -07001124 mContext.startActivity(buildNetworkOverLimitIntent(mContext.getResources(), template));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001125 mOverLimitNotified.add(template);
1126 }
1127 }
1128
Felipe Lemef0823852016-06-08 13:43:08 -07001129 private void notifyUnderLimitNL(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001130 mOverLimitNotified.remove(template);
1131 }
1132
1133 /**
Jeff Sharkey497e4432011-06-14 17:27:29 -07001134 * Show notification for combined {@link NetworkPolicy} and specific type,
1135 * like {@link #TYPE_LIMIT}. Okay to call multiple times.
1136 */
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001137 private void enqueueNotification(NetworkPolicy policy, int type, long totalBytes) {
Chris Wren193ae6b2017-03-31 15:17:11 -04001138 final NotificationId notificationId = new NotificationId(policy, type);
Geoffrey Pitschaf759c52017-02-15 09:35:38 -05001139 final Notification.Builder builder =
1140 new Notification.Builder(mContext, SystemNotificationChannels.NETWORK_STATUS);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001141 builder.setOnlyAlertOnce(true);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001142 builder.setWhen(0L);
Alan Viverette4a357cd2015-03-18 18:37:18 -07001143 builder.setColor(mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02001144 com.android.internal.R.color.system_notification_accent_color));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001145
1146 final Resources res = mContext.getResources();
Chris Wren8a3d56c2016-08-01 15:52:52 -04001147 CharSequence body = null;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001148 switch (type) {
1149 case TYPE_WARNING: {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001150 final CharSequence title = res.getText(R.string.data_usage_warning_title);
Chris Wren8a3d56c2016-08-01 15:52:52 -04001151 body = res.getString(R.string.data_usage_warning_body);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001152
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001153 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001154 builder.setTicker(title);
1155 builder.setContentTitle(title);
1156 builder.setContentText(body);
Sanket Padawec015e1c2016-08-11 16:34:10 -07001157 builder.setDefaults(Notification.DEFAULT_ALL);
Julia Reynoldsbad42972017-04-25 13:52:49 -04001158 builder.setChannelId(SystemNotificationChannels.NETWORK_ALERTS);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001159
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001160 final Intent snoozeIntent = buildSnoozeWarningIntent(policy.template);
1161 builder.setDeleteIntent(PendingIntent.getBroadcast(
1162 mContext, 0, snoozeIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1163
Wei Liu546cb772016-07-21 16:19:01 -07001164 final Intent viewIntent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001165 builder.setContentIntent(PendingIntent.getActivity(
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001166 mContext, 0, viewIntent, PendingIntent.FLAG_UPDATE_CURRENT));
1167
Jeff Sharkey497e4432011-06-14 17:27:29 -07001168 break;
1169 }
1170 case TYPE_LIMIT: {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001171 body = res.getText(R.string.data_usage_limit_body);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001172
1173 final CharSequence title;
John Spurlockaedebda2014-07-14 14:36:32 -04001174 int icon = R.drawable.stat_notify_disabled_data;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001175 switch (policy.template.getMatchRule()) {
1176 case MATCH_MOBILE_3G_LOWER:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001177 title = res.getText(R.string.data_usage_3g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001178 break;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07001179 case MATCH_MOBILE_4G:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001180 title = res.getText(R.string.data_usage_4g_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001181 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001182 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001183 title = res.getText(R.string.data_usage_mobile_limit_title);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001184 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001185 case MATCH_WIFI:
1186 title = res.getText(R.string.data_usage_wifi_limit_title);
John Spurlockaedebda2014-07-14 14:36:32 -04001187 icon = R.drawable.stat_notify_error;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001188 break;
1189 default:
1190 title = null;
1191 break;
Jeff Sharkey497e4432011-06-14 17:27:29 -07001192 }
1193
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001194 builder.setOngoing(true);
John Spurlockaedebda2014-07-14 14:36:32 -04001195 builder.setSmallIcon(icon);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001196 builder.setTicker(title);
1197 builder.setContentTitle(title);
1198 builder.setContentText(body);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001199
Wei Liu546cb772016-07-21 16:19:01 -07001200 final Intent intent = buildNetworkOverLimitIntent(res, policy.template);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001201 builder.setContentIntent(PendingIntent.getActivity(
1202 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
1203 break;
1204 }
1205 case TYPE_LIMIT_SNOOZED: {
1206 final long overBytes = totalBytes - policy.limitBytes;
Chris Wren8a3d56c2016-08-01 15:52:52 -04001207 body = res.getString(R.string.data_usage_limit_snoozed_body,
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001208 Formatter.formatFileSize(mContext, overBytes));
1209
1210 final CharSequence title;
1211 switch (policy.template.getMatchRule()) {
1212 case MATCH_MOBILE_3G_LOWER:
1213 title = res.getText(R.string.data_usage_3g_limit_snoozed_title);
1214 break;
1215 case MATCH_MOBILE_4G:
1216 title = res.getText(R.string.data_usage_4g_limit_snoozed_title);
1217 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001218 case MATCH_MOBILE_ALL:
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001219 title = res.getText(R.string.data_usage_mobile_limit_snoozed_title);
1220 break;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001221 case MATCH_WIFI:
1222 title = res.getText(R.string.data_usage_wifi_limit_snoozed_title);
1223 break;
1224 default:
1225 title = null;
1226 break;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001227 }
1228
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001229 builder.setOngoing(true);
Jeff Sharkey50e7e512011-10-10 16:50:35 -07001230 builder.setSmallIcon(R.drawable.stat_notify_error);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001231 builder.setTicker(title);
1232 builder.setContentTitle(title);
1233 builder.setContentText(body);
1234
Wei Liu546cb772016-07-21 16:19:01 -07001235 final Intent intent = buildViewDataUsageIntent(res, policy.template);
Jeff Sharkey14711eb2011-06-15 10:29:17 -07001236 builder.setContentIntent(PendingIntent.getActivity(
1237 mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
Jeff Sharkey497e4432011-06-14 17:27:29 -07001238 break;
1239 }
1240 }
1241
1242 // TODO: move to NotificationManager once we can mock it
1243 try {
1244 final String packageName = mContext.getPackageName();
Chris Wren193ae6b2017-03-31 15:17:11 -04001245 if (!TextUtils.isEmpty(body)) {
Chris Wren8a3d56c2016-08-01 15:52:52 -04001246 builder.setStyle(new Notification.BigTextStyle()
1247 .bigText(body));
1248 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07001249 mNotifManager.enqueueNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001250 packageName, packageName, notificationId.getTag(), notificationId.getId(),
Julia Reynoldsfea6f7b2017-04-19 13:50:12 -04001251 builder.build(), UserHandle.USER_ALL);
Chris Wren193ae6b2017-03-31 15:17:11 -04001252 mActiveNotifs.add(notificationId);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001253 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001254 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001255 }
1256 }
1257
Chris Wren193ae6b2017-03-31 15:17:11 -04001258 private void cancelNotification(NotificationId notificationId) {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001259 // TODO: move to NotificationManager once we can mock it
1260 try {
1261 final String packageName = mContext.getPackageName();
1262 mNotifManager.cancelNotificationWithTag(
Chris Wren193ae6b2017-03-31 15:17:11 -04001263 packageName, notificationId.getTag(), notificationId.getId(),
1264 UserHandle.USER_ALL);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001265 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001266 // ignored; service lives in system_server
Jeff Sharkey497e4432011-06-14 17:27:29 -07001267 }
1268 }
1269
1270 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001271 * Receiver that watches for {@link IConnectivityManager} to claim network
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001272 * interfaces. Used to apply {@link NetworkPolicy} to matching networks.
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001273 */
Jeff Sharkeyb09540f2011-06-19 01:08:12 -07001274 private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001275 @Override
1276 public void onReceive(Context context, Intent intent) {
1277 // on background handler thread, and verified CONNECTIVITY_INTERNAL
1278 // permission above.
Jeff Sharkey684c54a2011-11-16 17:46:30 -08001279
1280 maybeRefreshTrustedTime();
Hugo Benichi446c9c92017-04-10 09:41:10 +09001281 synchronized (mUidRulesFirstLock) {
1282 synchronized (mNetworkPoliciesSecondLock) {
1283 ensureActiveMobilePolicyAL();
1284 normalizePoliciesNL();
1285 updateNetworkEnabledNL();
1286 updateNetworkRulesNL();
1287 updateNotificationsNL();
1288 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001289 }
1290 }
1291 };
1292
1293 /**
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001294 * Update mobile policies with data cycle information from {@link CarrierConfigManager}
1295 * if necessary.
1296 *
1297 * @param subId that has its associated NetworkPolicy updated if necessary
1298 * @return if any policies were updated
1299 */
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001300 private boolean maybeUpdateMobilePolicyCycleAL(int subId) {
1301 if (LOGV) Slog.v(TAG, "maybeUpdateMobilePolicyCycleAL()");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001302
1303 boolean policyUpdated = false;
1304 final String subscriberId = TelephonyManager.from(mContext).getSubscriberId(subId);
1305
1306 // find and update the mobile NetworkPolicy for this subscriber id
1307 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001308 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001309 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1310 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1311 if (template.matches(probeIdent)) {
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001312 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1313 policyUpdated |= updateDefaultMobilePolicyAL(subId, policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001314 }
1315 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001316 return policyUpdated;
1317 }
1318
1319 /**
1320 * Returns the cycle day that should be used for a mobile NetworkPolicy.
1321 *
1322 * It attempts to get an appropriate cycle day 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 fallbackCycleDay to return if the CarrierConfig can't be read.
1327 * @return cycleDay to use in the mobile NetworkPolicy.
1328 */
1329 @VisibleForTesting
1330 public int getCycleDayFromCarrierConfig(@Nullable PersistableBundle config,
1331 int fallbackCycleDay) {
1332 if (config == null) {
1333 return fallbackCycleDay;
1334 }
1335 int cycleDay =
1336 config.getInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT);
1337 if (cycleDay == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1338 return fallbackCycleDay;
1339 }
1340 // validate cycleDay value
1341 final Calendar cal = Calendar.getInstance();
1342 if (cycleDay < cal.getMinimum(Calendar.DAY_OF_MONTH) ||
1343 cycleDay > cal.getMaximum(Calendar.DAY_OF_MONTH)) {
1344 Slog.e(TAG, "Invalid date in "
1345 + "CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT: " + cycleDay);
1346 return fallbackCycleDay;
1347 }
1348 return cycleDay;
1349 }
1350
1351 /**
1352 * Returns the warning bytes that should be used for a mobile NetworkPolicy.
1353 *
1354 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1355 * to do so, it returns the fallback value.
1356 *
1357 * @param config The CarrierConfig to read the value from.
1358 * @param fallbackWarningBytes to return if the CarrierConfig can't be read.
1359 * @return warningBytes to use in the mobile NetworkPolicy.
1360 */
1361 @VisibleForTesting
1362 public long getWarningBytesFromCarrierConfig(@Nullable PersistableBundle config,
1363 long fallbackWarningBytes) {
1364 if (config == null) {
1365 return fallbackWarningBytes;
1366 }
1367 long warningBytes =
1368 config.getLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG);
1369
1370 if (warningBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1371 return WARNING_DISABLED;
1372 } else if (warningBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1373 return getPlatformDefaultWarningBytes();
1374 } else if (warningBytes < 0) {
1375 Slog.e(TAG, "Invalid value in "
1376 + "CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG; expected a "
1377 + "non-negative value but got: " + warningBytes);
1378 return fallbackWarningBytes;
1379 }
1380
1381 return warningBytes;
1382 }
1383
1384 /**
1385 * Returns the limit bytes that should be used for a mobile NetworkPolicy.
1386 *
1387 * It attempts to get an appropriate value from the passed in CarrierConfig. If it's unable
1388 * to do so, it returns the fallback value.
1389 *
1390 * @param config The CarrierConfig to read the value from.
1391 * @param fallbackLimitBytes to return if the CarrierConfig can't be read.
1392 * @return limitBytes to use in the mobile NetworkPolicy.
1393 */
1394 @VisibleForTesting
1395 public long getLimitBytesFromCarrierConfig(@Nullable PersistableBundle config,
1396 long fallbackLimitBytes) {
1397 if (config == null) {
1398 return fallbackLimitBytes;
1399 }
1400 long limitBytes =
1401 config.getLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG);
1402
1403 if (limitBytes == DATA_CYCLE_THRESHOLD_DISABLED) {
1404 return LIMIT_DISABLED;
1405 } else if (limitBytes == DATA_CYCLE_USE_PLATFORM_DEFAULT) {
1406 return getPlatformDefaultLimitBytes();
1407 } else if (limitBytes < 0) {
1408 Slog.e(TAG, "Invalid value in "
1409 + "CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG; expected a "
1410 + "non-negative value but got: " + limitBytes);
1411 return fallbackLimitBytes;
1412 }
1413 return limitBytes;
1414 }
1415
1416 /**
1417 * Receiver that watches for {@link CarrierConfigManager} to be changed.
1418 */
1419 private BroadcastReceiver mCarrierConfigReceiver = new BroadcastReceiver() {
1420 @Override
1421 public void onReceive(Context context, Intent intent) {
1422 // No need to do a permission check, because the ACTION_CARRIER_CONFIG_CHANGED
1423 // broadcast is protected and can't be spoofed. Runs on a background handler thread.
1424
1425 if (!intent.hasExtra(PhoneConstants.SUBSCRIPTION_KEY)) {
1426 return;
1427 }
1428 final int subId = intent.getIntExtra(PhoneConstants.SUBSCRIPTION_KEY, -1);
1429 final TelephonyManager tele = TelephonyManager.from(mContext);
1430 final String subscriberId = tele.getSubscriberId(subId);
1431
1432 maybeRefreshTrustedTime();
1433 synchronized (mUidRulesFirstLock) {
1434 synchronized (mNetworkPoliciesSecondLock) {
Hugo Benichi446c9c92017-04-10 09:41:10 +09001435 final boolean added = ensureActiveMobilePolicyAL(subId, subscriberId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001436 if (added) return;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001437 final boolean updated = maybeUpdateMobilePolicyCycleAL(subId);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001438 if (!updated) return;
1439 // update network and notification rules, as the data cycle changed and it's
1440 // possible that we should be triggering warnings/limits now
1441 handleNetworkPoliciesUpdateAL(true);
1442 }
1443 }
1444 }
1445 };
1446
1447 /**
1448 * Handles all tasks that need to be run after a new network policy has been set, or an existing
1449 * one has been updated.
1450 *
1451 * @param shouldNormalizePolicies true iff network policies need to be normalized after the
1452 * update.
1453 */
1454 void handleNetworkPoliciesUpdateAL(boolean shouldNormalizePolicies) {
1455 if (shouldNormalizePolicies) {
1456 normalizePoliciesNL();
1457 }
1458 updateNetworkEnabledNL();
1459 updateNetworkRulesNL();
1460 updateNotificationsNL();
1461 writePolicyAL();
1462 }
1463
1464 /**
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001465 * Proactively control network data connections when they exceed
1466 * {@link NetworkPolicy#limitBytes}.
1467 */
Felipe Lemef0823852016-06-08 13:43:08 -07001468 void updateNetworkEnabledNL() {
1469 if (LOGV) Slog.v(TAG, "updateNetworkEnabledNL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001470
1471 // TODO: reset any policy-disabled networks when any policy is removed
1472 // completely, which is currently rare case.
1473
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001474 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
1475 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001476 // shortcut when policy has no limit
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001477 if (policy.limitBytes == LIMIT_DISABLED || !policy.hasCycle()) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001478 setNetworkTemplateEnabled(policy.template, true);
1479 continue;
1480 }
1481
Jeff Sharkey53313d72017-07-13 16:47:32 -06001482 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1483 .cycleIterator(policy).next();
1484 final long start = cycle.first.toInstant().toEpochMilli();
1485 final long end = cycle.second.toInstant().toEpochMilli();
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001486 final long totalBytes = getTotalBytes(policy.template, start, end);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001487
1488 // disable data connection when over limit and not snoozed
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001489 final boolean overLimitWithoutSnooze = policy.isOverLimit(totalBytes)
1490 && policy.lastLimitSnooze < start;
1491 final boolean networkEnabled = !overLimitWithoutSnooze;
Jeff Sharkey8e9992a2011-08-23 18:37:23 -07001492
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001493 setNetworkTemplateEnabled(policy.template, networkEnabled);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001494 }
1495 }
1496
1497 /**
Jeff Sharkey32566012014-12-02 18:30:14 -08001498 * Proactively disable networks that match the given
1499 * {@link NetworkTemplate}.
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001500 */
1501 private void setNetworkTemplateEnabled(NetworkTemplate template, boolean enabled) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001502 // TODO: reach into ConnectivityManager to proactively disable bringing
1503 // up this network, since we know that traffic will be blocked.
Jack Yu8781b682016-07-08 14:28:51 -07001504
1505 if (template.getMatchRule() == MATCH_MOBILE_ALL) {
1506 // If mobile data usage hits the limit or if the user resumes the data, we need to
1507 // notify telephony.
1508 final SubscriptionManager sm = SubscriptionManager.from(mContext);
1509 final TelephonyManager tm = TelephonyManager.from(mContext);
1510
1511 final int[] subIds = sm.getActiveSubscriptionIdList();
1512 for (int subId : subIds) {
1513 final String subscriberId = tm.getSubscriberId(subId);
1514 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001515 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true,
1516 true);
Jack Yu8781b682016-07-08 14:28:51 -07001517 // Template is matched when subscriber id matches.
1518 if (template.matches(probeIdent)) {
1519 tm.setPolicyDataEnabled(enabled, subId);
1520 }
1521 }
1522 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001523 }
1524
1525 /**
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001526 * Collect all ifaces from a {@link NetworkState} into the given set.
1527 */
1528 private static void collectIfaces(ArraySet<String> ifaces, NetworkState state) {
1529 final String baseIface = state.linkProperties.getInterfaceName();
1530 if (baseIface != null) {
1531 ifaces.add(baseIface);
1532 }
1533 for (LinkProperties stackedLink : state.linkProperties.getStackedLinks()) {
1534 final String stackedIface = stackedLink.getInterfaceName();
1535 if (stackedIface != null) {
1536 ifaces.add(stackedIface);
1537 }
1538 }
1539 }
1540
1541 /**
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001542 * Examine all connected {@link NetworkState}, looking for
1543 * {@link NetworkPolicy} that need to be enforced. When matches found, set
1544 * remaining quota based on usage cycle and historical stats.
1545 */
Felipe Lemef0823852016-06-08 13:43:08 -07001546 void updateNetworkRulesNL() {
1547 if (LOGV) Slog.v(TAG, "updateNetworkRulesNL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001548
1549 final NetworkState[] states;
1550 try {
1551 states = mConnManager.getAllNetworkState();
1552 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07001553 // ignored; service lives in system_server
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001554 return;
1555 }
1556
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07001557 // First, generate identities of all connected networks so we can
1558 // quickly compare them against all defined policies below.
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001559 final ArrayMap<NetworkState, NetworkIdentity> identified = new ArrayMap<>();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001560 for (NetworkState state : states) {
Wei Liub8eaf452016-01-25 10:32:27 -08001561 if (state.networkInfo != null && state.networkInfo.isConnected()) {
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001562 final NetworkIdentity ident = NetworkIdentity.buildNetworkIdentity(mContext, state,
1563 true);
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001564 identified.put(state, ident);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001565 }
1566 }
1567
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001568 final ArraySet<String> newMeteredIfaces = new ArraySet<>();
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001569 long lowestRule = Long.MAX_VALUE;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001570
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001571 // For every well-defined policy, compute remaining data based on
1572 // current cycle and historical stats, and push to kernel.
1573 final ArraySet<String> matchingIfaces = new ArraySet<>();
1574 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1575 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
1576
1577 // Collect all ifaces that match this policy
1578 matchingIfaces.clear();
1579 for (int j = identified.size() - 1; j >= 0; j--) {
1580 if (policy.template.matches(identified.valueAt(j))) {
1581 collectIfaces(matchingIfaces, identified.keyAt(j));
1582 }
1583 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001584
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001585 if (LOGD) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001586 Slog.d(TAG, "Applying " + policy + " to ifaces " + matchingIfaces);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001587 }
1588
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001589 final boolean hasWarning = policy.warningBytes != LIMIT_DISABLED;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001590 final boolean hasLimit = policy.limitBytes != LIMIT_DISABLED;
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001591 if (hasLimit || policy.metered) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001592 final long quotaBytes;
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001593 if (hasLimit && policy.hasCycle()) {
1594 final Pair<ZonedDateTime, ZonedDateTime> cycle = NetworkPolicyManager
1595 .cycleIterator(policy).next();
1596 final long start = cycle.first.toInstant().toEpochMilli();
1597 final long end = cycle.second.toInstant().toEpochMilli();
1598 final long totalBytes = getTotalBytes(policy.template, start, end);
1599
1600 if (policy.lastLimitSnooze >= start) {
1601 // snoozing past quota, but we still need to restrict apps,
1602 // so push really high quota.
1603 quotaBytes = Long.MAX_VALUE;
1604 } else {
1605 // remaining "quota" bytes are based on total usage in
1606 // current cycle. kernel doesn't like 0-byte rules, so we
1607 // set 1-byte quota and disable the radio later.
1608 quotaBytes = Math.max(1, policy.limitBytes - totalBytes);
1609 }
1610 } else {
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001611 // metered network, but no policy limit; we still need to
1612 // restrict apps, so push really high quota.
1613 quotaBytes = Long.MAX_VALUE;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001614 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001615
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001616 if (matchingIfaces.size() > 1) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001617 // TODO: switch to shared quota once NMS supports
1618 Slog.w(TAG, "shared quota unsupported; generating rule for each iface");
Ashish Sharma50fd36d2011-06-15 19:34:53 -07001619 }
1620
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001621 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1622 final String iface = matchingIfaces.valueAt(j);
1623 setInterfaceQuotaAsync(iface, quotaBytes);
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001624 newMeteredIfaces.add(iface);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001625 }
1626 }
Jeff Sharkeyac3fcb12012-05-02 18:11:52 -07001627
1628 // keep track of lowest warning or limit of active policies
1629 if (hasWarning && policy.warningBytes < lowestRule) {
1630 lowestRule = policy.warningBytes;
1631 }
1632 if (hasLimit && policy.limitBytes < lowestRule) {
1633 lowestRule = policy.limitBytes;
1634 }
1635 }
1636
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001637 // One final pass to catch any metered ifaces that don't have explicitly
1638 // defined policies; typically Wi-Fi networks.
1639 for (NetworkState state : states) {
1640 if (state.networkInfo != null && state.networkInfo.isConnected()
1641 && !state.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
1642 matchingIfaces.clear();
1643 collectIfaces(matchingIfaces, state);
1644 for (int j = matchingIfaces.size() - 1; j >= 0; j--) {
1645 final String iface = matchingIfaces.valueAt(j);
1646 if (!newMeteredIfaces.contains(iface)) {
1647 setInterfaceQuotaAsync(iface, Long.MAX_VALUE);
1648 newMeteredIfaces.add(iface);
1649 }
1650 }
1651 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07001652 }
1653
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001654 // Remove quota from any interfaces that are no longer metered.
Dianne Hackborn497175b2014-07-01 12:56:08 -07001655 for (int i = mMeteredIfaces.size() - 1; i >= 0; i--) {
1656 final String iface = mMeteredIfaces.valueAt(i);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001657 if (!newMeteredIfaces.contains(iface)) {
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001658 removeInterfaceQuotaAsync(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07001659 }
1660 }
1661 mMeteredIfaces = newMeteredIfaces;
1662
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001663 final String[] meteredIfaces = mMeteredIfaces.toArray(new String[mMeteredIfaces.size()]);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07001664 mHandler.obtainMessage(MSG_METERED_IFACES_CHANGED, meteredIfaces).sendToTarget();
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06001665
1666 mHandler.obtainMessage(MSG_ADVISE_PERSIST_THRESHOLD, lowestRule).sendToTarget();
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001667 }
1668
1669 /**
1670 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1671 * have at least a default mobile policy defined.
1672 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001673 private void ensureActiveMobilePolicyAL() {
1674 if (LOGV) Slog.v(TAG, "ensureActiveMobilePolicyAL()");
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07001675 if (mSuppressDefaultPolicy) return;
1676
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001677 final TelephonyManager tele = TelephonyManager.from(mContext);
Jeff Sharkey32566012014-12-02 18:30:14 -08001678 final SubscriptionManager sub = SubscriptionManager.from(mContext);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001679
Jeff Sharkey32566012014-12-02 18:30:14 -08001680 final int[] subIds = sub.getActiveSubscriptionIdList();
1681 for (int subId : subIds) {
1682 final String subscriberId = tele.getSubscriberId(subId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001683 ensureActiveMobilePolicyAL(subId, subscriberId);
Jeff Sharkey32566012014-12-02 18:30:14 -08001684 }
1685 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001686
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001687 /**
1688 * Once any {@link #mNetworkPolicy} are loaded from disk, ensure that we
1689 * have at least a default mobile policy defined.
1690 *
1691 * @param subId to build a default policy for
1692 * @param subscriberId that we check for an existing policy
1693 * @return true if a mobile network policy was added, or false one already existed.
1694 */
Hugo Benichi446c9c92017-04-10 09:41:10 +09001695 private boolean ensureActiveMobilePolicyAL(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001696 // Poke around to see if we already have a policy
1697 final NetworkIdentity probeIdent = new NetworkIdentity(TYPE_MOBILE,
Lorenzo Colittid3e4a1e2018-01-19 01:12:04 +09001698 TelephonyManager.NETWORK_TYPE_UNKNOWN, subscriberId, null, false, true, true);
Jeff Sharkey32566012014-12-02 18:30:14 -08001699 for (int i = mNetworkPolicy.size() - 1; i >= 0; i--) {
1700 final NetworkTemplate template = mNetworkPolicy.keyAt(i);
1701 if (template.matches(probeIdent)) {
1702 if (LOGD) {
1703 Slog.d(TAG, "Found template " + template + " which matches subscriber "
1704 + NetworkIdentity.scrubSubscriberId(subscriberId));
1705 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001706 return false;
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001707 }
1708 }
1709
Jeff Sharkey32566012014-12-02 18:30:14 -08001710 Slog.i(TAG, "No policy for subscriber " + NetworkIdentity.scrubSubscriberId(subscriberId)
1711 + "; generating default policy");
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001712 final NetworkPolicy policy = buildDefaultMobilePolicy(subId, subscriberId);
Hugo Benichi446c9c92017-04-10 09:41:10 +09001713 addNetworkPolicyAL(policy);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001714 return true;
1715 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001716
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001717 private long getPlatformDefaultWarningBytes() {
Fan Zhangda71ca02016-09-12 17:36:22 -07001718 final int dataWarningConfig = mContext.getResources().getInteger(
1719 com.android.internal.R.integer.config_networkPolicyDefaultWarning);
Fan Zhangda71ca02016-09-12 17:36:22 -07001720 if (dataWarningConfig == WARNING_DISABLED) {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001721 return WARNING_DISABLED;
Fan Zhangda71ca02016-09-12 17:36:22 -07001722 } else {
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001723 return dataWarningConfig * MB_IN_BYTES;
Fan Zhangda71ca02016-09-12 17:36:22 -07001724 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001725 }
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001726
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001727 private long getPlatformDefaultLimitBytes() {
1728 return LIMIT_DISABLED;
1729 }
1730
1731 @VisibleForTesting
1732 public NetworkPolicy buildDefaultMobilePolicy(int subId, String subscriberId) {
Jeff Sharkey32566012014-12-02 18:30:14 -08001733 final NetworkTemplate template = buildTemplateMobileAll(subscriberId);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001734 final RecurrenceRule cycleRule = NetworkPolicy
1735 .buildRule(ZonedDateTime.now().getDayOfMonth(), ZoneId.systemDefault());
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001736 final NetworkPolicy policy = new NetworkPolicy(template, cycleRule,
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001737 getPlatformDefaultWarningBytes(), getPlatformDefaultLimitBytes(),
1738 SNOOZE_NEVER, SNOOZE_NEVER, true, true);
1739 synchronized (mUidRulesFirstLock) {
1740 synchronized (mNetworkPoliciesSecondLock) {
1741 updateDefaultMobilePolicyAL(subId, policy);
1742 }
1743 }
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07001744 return policy;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001745 }
1746
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06001747 /**
1748 * Update the given {@link NetworkPolicy} based on any carrier-provided
1749 * defaults via {@link SubscriptionPlan} or {@link CarrierConfigManager}.
1750 * Leaves policy untouched if the user has modified it.
1751 *
1752 * @return if the policy was modified
1753 */
1754 private boolean updateDefaultMobilePolicyAL(int subId, NetworkPolicy policy) {
1755 if (!policy.inferred) {
1756 if (LOGD) Slog.d(TAG, "Ignoring user-defined policy " + policy);
1757 return false;
1758 }
1759
1760 final NetworkPolicy original = new NetworkPolicy(policy.template, policy.cycleRule,
1761 policy.warningBytes, policy.limitBytes, policy.lastWarningSnooze,
1762 policy.lastLimitSnooze, policy.metered, policy.inferred);
1763
1764 final SubscriptionPlan[] plans = mSubscriptionPlans.get(subId);
1765 if (!ArrayUtils.isEmpty(plans)) {
1766 final SubscriptionPlan plan = plans[0];
1767 policy.cycleRule = plan.getCycleRule();
1768 final long planLimitBytes = plan.getDataLimitBytes();
1769 if (planLimitBytes == SubscriptionPlan.BYTES_UNKNOWN) {
1770 policy.warningBytes = getPlatformDefaultWarningBytes();
1771 policy.limitBytes = getPlatformDefaultLimitBytes();
1772 } else if (planLimitBytes == SubscriptionPlan.BYTES_UNLIMITED) {
1773 policy.warningBytes = NetworkPolicy.WARNING_DISABLED;
1774 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1775 } else {
1776 policy.warningBytes = (planLimitBytes * 9) / 10;
1777 switch (plan.getDataLimitBehavior()) {
1778 case SubscriptionPlan.LIMIT_BEHAVIOR_BILLED:
1779 case SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED:
1780 policy.limitBytes = planLimitBytes;
1781 break;
1782 default:
1783 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
1784 break;
1785 }
1786 }
1787 } else {
1788 final PersistableBundle config = mCarrierConfigManager.getConfigForSubId(subId);
1789 final int currentCycleDay;
1790 if (policy.cycleRule.isMonthly()) {
1791 currentCycleDay = policy.cycleRule.start.getDayOfMonth();
1792 } else {
1793 currentCycleDay = NetworkPolicy.CYCLE_NONE;
1794 }
1795 final int cycleDay = getCycleDayFromCarrierConfig(config, currentCycleDay);
1796 policy.cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.systemDefault());
1797 policy.warningBytes = getWarningBytesFromCarrierConfig(config, policy.warningBytes);
1798 policy.limitBytes = getLimitBytesFromCarrierConfig(config, policy.limitBytes);
1799 }
1800
1801 if (policy.equals(original)) {
1802 return false;
1803 } else {
1804 Slog.d(TAG, "Updated " + original + " to " + policy);
1805 return true;
1806 }
1807 }
1808
Felipe Lemef0823852016-06-08 13:43:08 -07001809 private void readPolicyAL() {
1810 if (LOGV) Slog.v(TAG, "readPolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001811
1812 // clear any existing policy and read from disk
Jeff Sharkey22c055e2011-06-12 21:13:51 -07001813 mNetworkPolicy.clear();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001814 mSubscriptionPlans.clear();
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001815 mSubscriptionPlansOwner.clear();
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001816 mUidPolicy.clear();
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001817
1818 FileInputStream fis = null;
1819 try {
1820 fis = mPolicyFile.openRead();
1821 final XmlPullParser in = Xml.newPullParser();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01001822 in.setInput(fis, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001823
Felipe Leme46b451f2016-08-19 08:46:17 -07001824 // Must save the <restrict-background> tags and convert them to <uid-policy> later,
1825 // to skip UIDs that were explicitly blacklisted.
1826 final SparseBooleanArray whitelistedRestrictBackground = new SparseBooleanArray();
1827
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001828 int type;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001829 int version = VERSION_INIT;
Felipe Lemeb85a6372016-01-14 16:16:16 -08001830 boolean insideWhitelist = false;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001831 while ((type = in.next()) != END_DOCUMENT) {
1832 final String tag = in.getName();
1833 if (type == START_TAG) {
1834 if (TAG_POLICY_LIST.equals(tag)) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001835 final boolean oldValue = mRestrictBackground;
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001836 version = readIntAttribute(in, ATTR_VERSION);
Jeff Sharkey46645002011-07-27 21:11:21 -07001837 if (version >= VERSION_ADDED_RESTRICT_BACKGROUND) {
1838 mRestrictBackground = readBooleanAttribute(
1839 in, ATTR_RESTRICT_BACKGROUND);
1840 } else {
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07001841 mRestrictBackground = false;
Jeff Sharkey46645002011-07-27 21:11:21 -07001842 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001843 if (mRestrictBackground != oldValue) {
1844 // Some early services may have read the default value,
1845 // so notify them that it's changed
1846 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED,
1847 mRestrictBackground ? 1 : 0, 0).sendToTarget();
1848 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001849
1850 } else if (TAG_NETWORK_POLICY.equals(tag)) {
1851 final int networkTemplate = readIntAttribute(in, ATTR_NETWORK_TEMPLATE);
1852 final String subscriberId = in.getAttributeValue(null, ATTR_SUBSCRIBER_ID);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07001853 final String networkId;
1854 if (version >= VERSION_ADDED_NETWORK_ID) {
1855 networkId = in.getAttributeValue(null, ATTR_NETWORK_ID);
1856 } else {
1857 networkId = null;
1858 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001859 final RecurrenceRule cycleRule;
1860 if (version >= VERSION_ADDED_CYCLE) {
1861 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1862 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1863 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1864 cycleRule = new RecurrenceRule(
1865 RecurrenceRule.convertZonedDateTime(start),
1866 RecurrenceRule.convertZonedDateTime(end),
1867 RecurrenceRule.convertPeriod(period));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001868 } else {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001869 final int cycleDay = readIntAttribute(in, ATTR_CYCLE_DAY);
1870 final String cycleTimezone;
1871 if (version >= VERSION_ADDED_TIMEZONE) {
1872 cycleTimezone = in.getAttributeValue(null, ATTR_CYCLE_TIMEZONE);
1873 } else {
1874 cycleTimezone = "UTC";
1875 }
1876 cycleRule = NetworkPolicy.buildRule(cycleDay, ZoneId.of(cycleTimezone));
Jeff Sharkey9bf31502012-03-09 17:07:21 -08001877 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001878 final long warningBytes = readLongAttribute(in, ATTR_WARNING_BYTES);
1879 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001880 final long lastLimitSnooze;
1881 if (version >= VERSION_SPLIT_SNOOZE) {
1882 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_LIMIT_SNOOZE);
1883 } else if (version >= VERSION_ADDED_SNOOZE) {
1884 lastLimitSnooze = readLongAttribute(in, ATTR_LAST_SNOOZE);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001885 } else {
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001886 lastLimitSnooze = SNOOZE_NEVER;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07001887 }
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08001888 final boolean metered;
1889 if (version >= VERSION_ADDED_METERED) {
1890 metered = readBooleanAttribute(in, ATTR_METERED);
1891 } else {
1892 switch (networkTemplate) {
1893 case MATCH_MOBILE_3G_LOWER:
1894 case MATCH_MOBILE_4G:
1895 case MATCH_MOBILE_ALL:
1896 metered = true;
1897 break;
1898 default:
1899 metered = false;
1900 }
1901 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08001902 final long lastWarningSnooze;
1903 if (version >= VERSION_SPLIT_SNOOZE) {
1904 lastWarningSnooze = readLongAttribute(in, ATTR_LAST_WARNING_SNOOZE);
1905 } else {
1906 lastWarningSnooze = SNOOZE_NEVER;
1907 }
Jeff Sharkey837f9242012-03-20 16:52:20 -07001908 final boolean inferred;
1909 if (version >= VERSION_ADDED_INFERRED) {
1910 inferred = readBooleanAttribute(in, ATTR_INFERRED);
1911 } else {
1912 inferred = false;
1913 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001914
Jeff Sharkey32566012014-12-02 18:30:14 -08001915 final NetworkTemplate template = new NetworkTemplate(networkTemplate,
1916 subscriberId, networkId);
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001917 if (template.isPersistable()) {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001918 mNetworkPolicy.put(template, new NetworkPolicy(template, cycleRule,
1919 warningBytes, limitBytes, lastWarningSnooze,
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06001920 lastLimitSnooze, metered, inferred));
1921 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06001922
1923 } else if (TAG_SUBSCRIPTION_PLAN.equals(tag)) {
1924 final String start = readStringAttribute(in, ATTR_CYCLE_START);
1925 final String end = readStringAttribute(in, ATTR_CYCLE_END);
1926 final String period = readStringAttribute(in, ATTR_CYCLE_PERIOD);
1927 final SubscriptionPlan.Builder builder = new SubscriptionPlan.Builder(
1928 RecurrenceRule.convertZonedDateTime(start),
1929 RecurrenceRule.convertZonedDateTime(end),
1930 RecurrenceRule.convertPeriod(period));
1931 builder.setTitle(readStringAttribute(in, ATTR_TITLE));
1932 builder.setSummary(readStringAttribute(in, ATTR_SUMMARY));
1933
1934 final long limitBytes = readLongAttribute(in, ATTR_LIMIT_BYTES,
1935 SubscriptionPlan.BYTES_UNKNOWN);
1936 final int limitBehavior = readIntAttribute(in, ATTR_LIMIT_BEHAVIOR,
1937 SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN);
1938 if (limitBytes != SubscriptionPlan.BYTES_UNKNOWN
1939 && limitBehavior != SubscriptionPlan.LIMIT_BEHAVIOR_UNKNOWN) {
1940 builder.setDataLimit(limitBytes, limitBehavior);
1941 }
1942
1943 final long usageBytes = readLongAttribute(in, ATTR_USAGE_BYTES,
1944 SubscriptionPlan.BYTES_UNKNOWN);
1945 final long usageTime = readLongAttribute(in, ATTR_USAGE_TIME,
1946 SubscriptionPlan.TIME_UNKNOWN);
1947 if (usageBytes != SubscriptionPlan.BYTES_UNKNOWN
1948 && usageTime != SubscriptionPlan.TIME_UNKNOWN) {
1949 builder.setDataUsage(usageBytes, usageTime);
1950 }
1951
1952 final int subId = readIntAttribute(in, ATTR_SUB_ID);
1953 final SubscriptionPlan plan = builder.build();
1954 mSubscriptionPlans.put(subId, ArrayUtils.appendElement(
1955 SubscriptionPlan.class, mSubscriptionPlans.get(subId), plan));
1956
Jeff Sharkeyb74799882017-07-28 16:55:41 -06001957 final String ownerPackage = readStringAttribute(in, ATTR_OWNER_PACKAGE);
1958 mSubscriptionPlansOwner.put(subId, ownerPackage);
1959
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001960 } else if (TAG_UID_POLICY.equals(tag)) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001961 final int uid = readIntAttribute(in, ATTR_UID);
1962 final int policy = readIntAttribute(in, ATTR_POLICY);
1963
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001964 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001965 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey497e4432011-06-14 17:27:29 -07001966 } else {
1967 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
1968 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001969 } else if (TAG_APP_POLICY.equals(tag)) {
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001970 final int appId = readIntAttribute(in, ATTR_APP_ID);
1971 final int policy = readIntAttribute(in, ATTR_POLICY);
1972
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001973 // TODO: set for other users during upgrade
Xiaohui Chenbe3b0672015-09-02 13:29:22 -07001974 // app policy is deprecated so this is only used in pre system user split.
1975 final int uid = UserHandle.getUid(UserHandle.USER_SYSTEM, appId);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001976 if (UserHandle.isApp(uid)) {
Felipe Lemef0823852016-06-08 13:43:08 -07001977 setUidPolicyUncheckedUL(uid, policy, false);
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001978 } else {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07001979 Slog.w(TAG, "unable to apply policy to UID " + uid + "; ignoring");
Jeff Sharkey8a8b5812012-03-21 18:13:36 -07001980 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001981 } else if (TAG_WHITELIST.equals(tag)) {
1982 insideWhitelist = true;
1983 } else if (TAG_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1984 final int uid = readIntAttribute(in, ATTR_UID);
Felipe Leme46b451f2016-08-19 08:46:17 -07001985 whitelistedRestrictBackground.append(uid, true);
Felipe Lemea9505cc2016-02-26 10:28:41 -08001986 } else if (TAG_REVOKED_RESTRICT_BACKGROUND.equals(tag) && insideWhitelist) {
1987 final int uid = readIntAttribute(in, ATTR_UID);
1988 mRestrictBackgroundWhitelistRevokedUids.put(uid, true);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001989 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08001990 } else if (type == END_TAG) {
1991 if (TAG_WHITELIST.equals(tag)) {
1992 insideWhitelist = false;
1993 }
1994
Jeff Sharkey21c9c452011-06-07 12:26:43 -07001995 }
1996 }
1997
Felipe Leme46b451f2016-08-19 08:46:17 -07001998 final int size = whitelistedRestrictBackground.size();
1999 for (int i = 0; i < size; i++) {
2000 final int uid = whitelistedRestrictBackground.keyAt(i);
2001 final int policy = mUidPolicy.get(uid, POLICY_NONE);
2002 if ((policy & POLICY_REJECT_METERED_BACKGROUND) != 0) {
2003 Slog.w(TAG, "ignoring restrict-background-whitelist for " + uid
2004 + " because its policy is " + uidPoliciesToString(policy));
2005 continue;
2006 }
2007 if (UserHandle.isApp(uid)) {
2008 final int newPolicy = policy | POLICY_ALLOW_METERED_BACKGROUND;
2009 if (LOGV)
2010 Log.v(TAG, "new policy for " + uid + ": " + uidPoliciesToString(newPolicy));
2011 setUidPolicyUncheckedUL(uid, newPolicy, false);
2012 } else {
2013 Slog.w(TAG, "unable to update policy on UID " + uid);
2014 }
2015 }
2016
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002017 } catch (FileNotFoundException e) {
2018 // missing policy is okay, probably first boot
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002019 upgradeDefaultBackgroundDataUL();
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002020 } catch (Exception e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07002021 Log.wtf(TAG, "problem reading network policy", e);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002022 } finally {
2023 IoUtils.closeQuietly(fis);
2024 }
2025 }
2026
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002027 /**
2028 * Upgrade legacy background data flags, notifying listeners of one last
2029 * change to always-true.
2030 */
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002031 private void upgradeDefaultBackgroundDataUL() {
2032 // This method is only called when we're unable to find the network policy flag, which
2033 // usually happens on first boot of a new device and not one that has received an OTA.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002034
Narayan Kamath94bcdbc2017-07-17 15:32:53 +01002035 // Seed from the default value configured for this device.
2036 mRestrictBackground = Settings.Global.getInt(
2037 mContext.getContentResolver(), Global.DEFAULT_RESTRICT_BACKGROUND_DATA, 0) == 1;
2038
2039 // NOTE: We used to read the legacy setting here :
2040 //
2041 // final int legacyFlagValue = Settings.Secure.getInt(
2042 // mContext.getContentResolver(), Settings.Secure.BACKGROUND_DATA, ..);
2043 //
2044 // This is no longer necessary because we will never upgrade directly from Gingerbread
2045 // to O+. Devices upgrading from ICS onwards to O will have a netpolicy.xml file that
2046 // contains the correct value that we will continue to use.
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07002047 }
2048
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002049 /**
2050 * Perform upgrade step of moving any user-defined meterness overrides over
2051 * into {@link WifiConfiguration}.
2052 */
2053 private void upgradeWifiMeteredOverrideAL() {
2054 boolean modified = false;
2055 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2056 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2057 for (int i = 0; i < mNetworkPolicy.size(); ) {
2058 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
2059 if (policy.template.getMatchRule() == NetworkTemplate.MATCH_WIFI
2060 && !policy.inferred) {
2061 mNetworkPolicy.removeAt(i);
2062 modified = true;
2063
2064 final String networkId = resolveNetworkId(policy.template.getNetworkId());
2065 for (WifiConfiguration config : configs) {
2066 if (Objects.equals(resolveNetworkId(config), networkId)) {
2067 Slog.d(TAG, "Found network " + networkId + "; upgrading metered hint");
2068 config.meteredOverride = policy.metered
2069 ? WifiConfiguration.METERED_OVERRIDE_METERED
2070 : WifiConfiguration.METERED_OVERRIDE_NOT_METERED;
2071 wm.updateNetwork(config);
2072 }
2073 }
2074 } else {
2075 i++;
2076 }
2077 }
2078 if (modified) {
2079 writePolicyAL();
2080 }
2081 }
2082
Felipe Lemef0823852016-06-08 13:43:08 -07002083 void writePolicyAL() {
2084 if (LOGV) Slog.v(TAG, "writePolicyAL()");
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002085
2086 FileOutputStream fos = null;
2087 try {
2088 fos = mPolicyFile.startWrite();
2089
2090 XmlSerializer out = new FastXmlSerializer();
Wojciech Staszkiewicz9e9e2e72015-05-08 14:58:46 +01002091 out.setOutput(fos, StandardCharsets.UTF_8.name());
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002092 out.startDocument(null, true);
2093
2094 out.startTag(null, TAG_POLICY_LIST);
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002095 writeIntAttribute(out, ATTR_VERSION, VERSION_LATEST);
Jeff Sharkey46645002011-07-27 21:11:21 -07002096 writeBooleanAttribute(out, ATTR_RESTRICT_BACKGROUND, mRestrictBackground);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002097
2098 // write all known network policies
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002099 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2100 final NetworkPolicy policy = mNetworkPolicy.valueAt(i);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002101 final NetworkTemplate template = policy.template;
Jeff Sharkey7474fe7b2016-03-21 13:12:59 -06002102 if (!template.isPersistable()) continue;
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002103
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002104 out.startTag(null, TAG_NETWORK_POLICY);
Jeff Sharkey1b5a2a92011-06-18 18:34:16 -07002105 writeIntAttribute(out, ATTR_NETWORK_TEMPLATE, template.getMatchRule());
2106 final String subscriberId = template.getSubscriberId();
2107 if (subscriberId != null) {
2108 out.attribute(null, ATTR_SUBSCRIBER_ID, subscriberId);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002109 }
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002110 final String networkId = template.getNetworkId();
2111 if (networkId != null) {
2112 out.attribute(null, ATTR_NETWORK_ID, networkId);
2113 }
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002114 writeStringAttribute(out, ATTR_CYCLE_START,
2115 RecurrenceRule.convertZonedDateTime(policy.cycleRule.start));
2116 writeStringAttribute(out, ATTR_CYCLE_END,
2117 RecurrenceRule.convertZonedDateTime(policy.cycleRule.end));
2118 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2119 RecurrenceRule.convertPeriod(policy.cycleRule.period));
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002120 writeLongAttribute(out, ATTR_WARNING_BYTES, policy.warningBytes);
2121 writeLongAttribute(out, ATTR_LIMIT_BYTES, policy.limitBytes);
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002122 writeLongAttribute(out, ATTR_LAST_WARNING_SNOOZE, policy.lastWarningSnooze);
2123 writeLongAttribute(out, ATTR_LAST_LIMIT_SNOOZE, policy.lastLimitSnooze);
Jeff Sharkeyf60d0af2011-11-30 15:28:02 -08002124 writeBooleanAttribute(out, ATTR_METERED, policy.metered);
Jeff Sharkey837f9242012-03-20 16:52:20 -07002125 writeBooleanAttribute(out, ATTR_INFERRED, policy.inferred);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002126 out.endTag(null, TAG_NETWORK_POLICY);
2127 }
2128
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002129 // write all known subscription plans
2130 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2131 final int subId = mSubscriptionPlans.keyAt(i);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002132 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002133 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2134 if (ArrayUtils.isEmpty(plans)) continue;
2135
2136 for (SubscriptionPlan plan : plans) {
2137 out.startTag(null, TAG_SUBSCRIPTION_PLAN);
2138 writeIntAttribute(out, ATTR_SUB_ID, subId);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002139 writeStringAttribute(out, ATTR_OWNER_PACKAGE, ownerPackage);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002140 final RecurrenceRule cycleRule = plan.getCycleRule();
2141 writeStringAttribute(out, ATTR_CYCLE_START,
2142 RecurrenceRule.convertZonedDateTime(cycleRule.start));
2143 writeStringAttribute(out, ATTR_CYCLE_END,
2144 RecurrenceRule.convertZonedDateTime(cycleRule.end));
2145 writeStringAttribute(out, ATTR_CYCLE_PERIOD,
2146 RecurrenceRule.convertPeriod(cycleRule.period));
2147 writeStringAttribute(out, ATTR_TITLE, plan.getTitle());
2148 writeStringAttribute(out, ATTR_SUMMARY, plan.getSummary());
2149 writeLongAttribute(out, ATTR_LIMIT_BYTES, plan.getDataLimitBytes());
2150 writeIntAttribute(out, ATTR_LIMIT_BEHAVIOR, plan.getDataLimitBehavior());
2151 writeLongAttribute(out, ATTR_USAGE_BYTES, plan.getDataUsageBytes());
2152 writeLongAttribute(out, ATTR_USAGE_TIME, plan.getDataUsageTime());
2153 out.endTag(null, TAG_SUBSCRIPTION_PLAN);
2154 }
2155 }
2156
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002157 // write all known uid policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002158 for (int i = 0; i < mUidPolicy.size(); i++) {
2159 final int uid = mUidPolicy.keyAt(i);
2160 final int policy = mUidPolicy.valueAt(i);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002161
Jeff Sharkey497e4432011-06-14 17:27:29 -07002162 // skip writing empty policies
2163 if (policy == POLICY_NONE) continue;
2164
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002165 out.startTag(null, TAG_UID_POLICY);
2166 writeIntAttribute(out, ATTR_UID, uid);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002167 writeIntAttribute(out, ATTR_POLICY, policy);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002168 out.endTag(null, TAG_UID_POLICY);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002169 }
2170
2171 out.endTag(null, TAG_POLICY_LIST);
Felipe Lemeb85a6372016-01-14 16:16:16 -08002172
2173 // write all whitelists
2174 out.startTag(null, TAG_WHITELIST);
2175
Felipe Lemea9505cc2016-02-26 10:28:41 -08002176 // revoked restrict background whitelist
Felipe Leme46b451f2016-08-19 08:46:17 -07002177 int size = mRestrictBackgroundWhitelistRevokedUids.size();
Felipe Lemea9505cc2016-02-26 10:28:41 -08002178 for (int i = 0; i < size; i++) {
2179 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2180 out.startTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2181 writeIntAttribute(out, ATTR_UID, uid);
2182 out.endTag(null, TAG_REVOKED_RESTRICT_BACKGROUND);
2183 }
2184
Felipe Lemeb85a6372016-01-14 16:16:16 -08002185 out.endTag(null, TAG_WHITELIST);
2186
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002187 out.endDocument();
2188
2189 mPolicyFile.finishWrite(fos);
2190 } catch (IOException e) {
2191 if (fos != null) {
2192 mPolicyFile.failWrite(fos);
2193 }
2194 }
2195 }
2196
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002197 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002198 public void setUidPolicy(int uid, int policy) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002199 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002200
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002201 if (!UserHandle.isApp(uid)) {
2202 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002203 }
Felipe Lemef0823852016-06-08 13:43:08 -07002204 synchronized (mUidRulesFirstLock) {
Julia Reynolds72f83d62015-07-27 15:10:42 -04002205 final long token = Binder.clearCallingIdentity();
2206 try {
2207 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2208 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002209 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Julia Reynolds72f83d62015-07-27 15:10:42 -04002210 }
2211 } finally {
2212 Binder.restoreCallingIdentity(token);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002213 }
2214 }
Jeff Sharkey497e4432011-06-14 17:27:29 -07002215 }
2216
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002217 @Override
2218 public void addUidPolicy(int uid, int policy) {
2219 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002220
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002221 if (!UserHandle.isApp(uid)) {
2222 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2223 }
2224
Felipe Lemef0823852016-06-08 13:43:08 -07002225 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002226 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2227 policy |= oldPolicy;
2228 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002229 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Jeff Sharkey497e4432011-06-14 17:27:29 -07002230 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002231 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002232 }
2233
2234 @Override
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002235 public void removeUidPolicy(int uid, int policy) {
2236 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2237
2238 if (!UserHandle.isApp(uid)) {
2239 throw new IllegalArgumentException("cannot apply policy to UID " + uid);
2240 }
2241
Felipe Lemef0823852016-06-08 13:43:08 -07002242 synchronized (mUidRulesFirstLock) {
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002243 final int oldPolicy = mUidPolicy.get(uid, POLICY_NONE);
2244 policy = oldPolicy & ~policy;
2245 if (oldPolicy != policy) {
Felipe Lemef0823852016-06-08 13:43:08 -07002246 setUidPolicyUncheckedUL(uid, oldPolicy, policy, true);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002247 }
2248 }
2249 }
2250
Felipe Lemef0823852016-06-08 13:43:08 -07002251 private void setUidPolicyUncheckedUL(int uid, int oldPolicy, int policy, boolean persist) {
2252 setUidPolicyUncheckedUL(uid, policy, persist);
Felipe Leme923845f2016-03-02 13:42:48 -08002253
Felipe Leme57e3d312016-08-23 14:42:52 -07002254 final boolean notifyApp;
2255 if (!isUidValidForWhitelistRules(uid)) {
2256 notifyApp = false;
2257 } else {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002258 final boolean wasBlacklisted = oldPolicy == POLICY_REJECT_METERED_BACKGROUND;
2259 final boolean isBlacklisted = policy == POLICY_REJECT_METERED_BACKGROUND;
2260 final boolean wasWhitelisted = oldPolicy == POLICY_ALLOW_METERED_BACKGROUND;
2261 final boolean isWhitelisted = policy == POLICY_ALLOW_METERED_BACKGROUND;
Felipe Leme57e3d312016-08-23 14:42:52 -07002262 final boolean wasBlocked = wasBlacklisted || (mRestrictBackground && !wasWhitelisted);
2263 final boolean isBlocked = isBlacklisted || (mRestrictBackground && !isWhitelisted);
Felipe Leme03f90292016-09-08 18:10:32 -07002264 if ((wasWhitelisted && (!isWhitelisted || isBlacklisted))
2265 && mDefaultRestrictBackgroundWhitelistUids.get(uid)
2266 && !mRestrictBackgroundWhitelistRevokedUids.get(uid)) {
2267 if (LOGD)
2268 Slog.d(TAG, "Adding uid " + uid + " to revoked restrict background whitelist");
2269 mRestrictBackgroundWhitelistRevokedUids.append(uid, true);
2270 }
Felipe Leme57e3d312016-08-23 14:42:52 -07002271 notifyApp = wasBlocked != isBlocked;
2272 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07002273 mHandler.obtainMessage(MSG_POLICIES_CHANGED, uid, policy, Boolean.valueOf(notifyApp))
2274 .sendToTarget();
Felipe Leme923845f2016-03-02 13:42:48 -08002275 }
2276
Felipe Lemef0823852016-06-08 13:43:08 -07002277 private void setUidPolicyUncheckedUL(int uid, int policy, boolean persist) {
Felipe Leme03f90292016-09-08 18:10:32 -07002278 if (policy == POLICY_NONE) {
2279 mUidPolicy.delete(uid);
2280 } else {
2281 mUidPolicy.put(uid, policy);
2282 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002283
2284 // uid policy changed, recompute rules and persist policy.
Sudheer Shankac9d94072017-02-22 22:13:55 +00002285 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002286 if (persist) {
Felipe Lemef0823852016-06-08 13:43:08 -07002287 synchronized (mNetworkPoliciesSecondLock) {
2288 writePolicyAL();
2289 }
Dianne Hackbornbe7c50e2014-06-30 14:43:28 -07002290 }
2291 }
2292
2293 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002294 public int getUidPolicy(int uid) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002295 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2296
Felipe Lemef0823852016-06-08 13:43:08 -07002297 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002298 return mUidPolicy.get(uid, POLICY_NONE);
Jeff Sharkeya4620792011-05-20 15:29:23 -07002299 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07002300 }
2301
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002302 @Override
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002303 public int[] getUidsWithPolicy(int policy) {
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002304 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2305
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002306 int[] uids = new int[0];
Felipe Lemef0823852016-06-08 13:43:08 -07002307 synchronized (mUidRulesFirstLock) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002308 for (int i = 0; i < mUidPolicy.size(); i++) {
2309 final int uid = mUidPolicy.keyAt(i);
2310 final int uidPolicy = mUidPolicy.valueAt(i);
Felipe Leme6f51a0a2016-08-24 15:11:51 -07002311 if ((policy == POLICY_NONE && uidPolicy == POLICY_NONE) ||
2312 (uidPolicy & policy) != 0) {
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002313 uids = appendInt(uids, uid);
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002314 }
2315 }
2316 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002317 return uids;
2318 }
2319
2320 /**
Felipe Lemed17fda42016-04-29 11:12:45 -07002321 * Removes any persistable state associated with given {@link UserHandle}, persisting
2322 * if any changes that are made.
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002323 */
Felipe Lemef0823852016-06-08 13:43:08 -07002324 boolean removeUserStateUL(int userId, boolean writePolicy) {
Felipe Lemed17fda42016-04-29 11:12:45 -07002325
Felipe Lemef0823852016-06-08 13:43:08 -07002326 if (LOGV) Slog.v(TAG, "removeUserStateUL()");
Felipe Lemed17fda42016-04-29 11:12:45 -07002327 boolean changed = false;
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002328
Felipe Lemea110eec2016-04-29 09:58:06 -07002329 // Remove entries from revoked default restricted background UID whitelist
2330 for (int i = mRestrictBackgroundWhitelistRevokedUids.size() - 1; i >= 0; i--) {
2331 final int uid = mRestrictBackgroundWhitelistRevokedUids.keyAt(i);
2332 if (UserHandle.getUserId(uid) == userId) {
2333 mRestrictBackgroundWhitelistRevokedUids.removeAt(i);
Felipe Lemed17fda42016-04-29 11:12:45 -07002334 changed = true;
Felipe Lemea110eec2016-04-29 09:58:06 -07002335 }
2336 }
2337
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002338 // Remove associated UID policies
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002339 int[] uids = new int[0];
2340 for (int i = 0; i < mUidPolicy.size(); i++) {
2341 final int uid = mUidPolicy.keyAt(i);
2342 if (UserHandle.getUserId(uid) == userId) {
2343 uids = appendInt(uids, uid);
2344 }
2345 }
2346
2347 if (uids.length > 0) {
2348 for (int uid : uids) {
2349 mUidPolicy.delete(uid);
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002350 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002351 changed = true;
Fyodor Kupolova31c5912016-01-22 11:26:09 -08002352 }
Felipe Lemef0823852016-06-08 13:43:08 -07002353 synchronized (mNetworkPoliciesSecondLock) {
2354 updateRulesForGlobalChangeAL(true);
2355 if (writePolicy && changed) {
2356 writePolicyAL();
2357 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07002358 }
Felipe Lemed17fda42016-04-29 11:12:45 -07002359 return changed;
Jeff Sharkey854b2b12012-04-13 16:03:40 -07002360 }
2361
2362 @Override
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002363 public void registerListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002364 // TODO: create permission for observing network policy
2365 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002366 mListeners.register(listener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002367 }
2368
2369 @Override
2370 public void unregisterListener(INetworkPolicyListener listener) {
Jeff Sharkey1a303952011-06-16 13:04:20 -07002371 // TODO: create permission for observing network policy
2372 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002373 mListeners.unregister(listener);
2374 }
2375
Jeff Sharkey1b861272011-05-22 00:34:52 -07002376 @Override
Jeff Sharkey22c055e2011-06-12 21:13:51 -07002377 public void setNetworkPolicies(NetworkPolicy[] policies) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002378 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2379
Felipe Leme6a05eee2016-02-19 14:43:51 -08002380 final long token = Binder.clearCallingIdentity();
2381 try {
2382 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07002383 synchronized (mUidRulesFirstLock) {
2384 synchronized (mNetworkPoliciesSecondLock) {
2385 normalizePoliciesNL(policies);
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002386 handleNetworkPoliciesUpdateAL(false);
Felipe Lemef0823852016-06-08 13:43:08 -07002387 }
Felipe Leme6a05eee2016-02-19 14:43:51 -08002388 }
2389 } finally {
2390 Binder.restoreCallingIdentity(token);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002391 }
2392 }
2393
Hugo Benichi446c9c92017-04-10 09:41:10 +09002394 void addNetworkPolicyAL(NetworkPolicy policy) {
Svet Ganov16a16892015-04-16 10:32:04 -07002395 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Jeff Sharkey32566012014-12-02 18:30:14 -08002396 policies = ArrayUtils.appendElement(NetworkPolicy.class, policies, policy);
2397 setNetworkPolicies(policies);
Jeff Sharkey9f6e4ba2012-04-19 23:01:08 -07002398 }
2399
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002400 @Override
Svet Ganov16a16892015-04-16 10:32:04 -07002401 public NetworkPolicy[] getNetworkPolicies(String callingPackage) {
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002402 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002403 try {
Amit Mahajana9e72a72015-07-30 16:04:13 -07002404 mContext.enforceCallingOrSelfPermission(READ_PRIVILEGED_PHONE_STATE, TAG);
2405 // SKIP checking run-time OP_READ_PHONE_STATE since caller or self has PRIVILEGED
2406 // permission
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002407 } catch (SecurityException e) {
2408 mContext.enforceCallingOrSelfPermission(READ_PHONE_STATE, TAG);
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002409
Amit Mahajan7c5befa2015-07-14 10:26:00 -07002410 if (mAppOps.noteOp(AppOpsManager.OP_READ_PHONE_STATE, Binder.getCallingUid(),
2411 callingPackage) != AppOpsManager.MODE_ALLOWED) {
2412 return new NetworkPolicy[0];
2413 }
Svet Ganov16a16892015-04-16 10:32:04 -07002414 }
2415
Felipe Lemef0823852016-06-08 13:43:08 -07002416 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002417 final int size = mNetworkPolicy.size();
2418 final NetworkPolicy[] policies = new NetworkPolicy[size];
2419 for (int i = 0; i < size; i++) {
2420 policies[i] = mNetworkPolicy.valueAt(i);
2421 }
2422 return policies;
2423 }
2424 }
2425
Felipe Lemef0823852016-06-08 13:43:08 -07002426 private void normalizePoliciesNL() {
2427 normalizePoliciesNL(getNetworkPolicies(mContext.getOpPackageName()));
Jeff Sharkey32566012014-12-02 18:30:14 -08002428 }
2429
Felipe Lemef0823852016-06-08 13:43:08 -07002430 private void normalizePoliciesNL(NetworkPolicy[] policies) {
Jeff Sharkey32566012014-12-02 18:30:14 -08002431 final TelephonyManager tele = TelephonyManager.from(mContext);
2432 final String[] merged = tele.getMergedSubscriberIds();
2433
2434 mNetworkPolicy.clear();
2435 for (NetworkPolicy policy : policies) {
2436 // When two normalized templates conflict, prefer the most
2437 // restrictive policy
2438 policy.template = NetworkTemplate.normalize(policy.template, merged);
2439 final NetworkPolicy existing = mNetworkPolicy.get(policy.template);
2440 if (existing == null || existing.compareTo(policy) > 0) {
2441 if (existing != null) {
2442 Slog.d(TAG, "Normalization replaced " + existing + " with " + policy);
2443 }
2444 mNetworkPolicy.put(policy.template, policy);
2445 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002446 }
2447 }
2448
2449 @Override
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002450 public void snoozeLimit(NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002451 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkey6c0b4f32012-06-12 21:06:30 -07002452
2453 final long token = Binder.clearCallingIdentity();
2454 try {
2455 performSnooze(template, TYPE_LIMIT);
2456 } finally {
2457 Binder.restoreCallingIdentity(token);
2458 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002459 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002460
Dianne Hackborn497175b2014-07-01 12:56:08 -07002461 void performSnooze(NetworkTemplate template, int type) {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08002462 maybeRefreshTrustedTime();
2463 final long currentTime = currentTimeMillis();
Felipe Lemef0823852016-06-08 13:43:08 -07002464 synchronized (mUidRulesFirstLock) {
2465 synchronized (mNetworkPoliciesSecondLock) {
2466 // find and snooze local policy that matches
2467 final NetworkPolicy policy = mNetworkPolicy.get(template);
2468 if (policy == null) {
2469 throw new IllegalArgumentException("unable to find policy for " + template);
2470 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002471
Felipe Lemef0823852016-06-08 13:43:08 -07002472 switch (type) {
2473 case TYPE_WARNING:
2474 policy.lastWarningSnooze = currentTime;
2475 break;
2476 case TYPE_LIMIT:
2477 policy.lastLimitSnooze = currentTime;
2478 break;
2479 default:
2480 throw new IllegalArgumentException("unexpected type");
2481 }
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002482
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002483 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002484 }
Jeff Sharkey21c9c452011-06-07 12:26:43 -07002485 }
2486 }
2487
2488 @Override
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002489 public void onTetheringChanged(String iface, boolean tethering) {
2490 // No need to enforce permission because setRestrictBackground() will do it.
2491 if (LOGD) Log.d(TAG, "onTetherStateChanged(" + iface + ", " + tethering + ")");
Felipe Lemef0823852016-06-08 13:43:08 -07002492 synchronized (mUidRulesFirstLock) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002493 if (mRestrictBackground && tethering) {
2494 Log.d(TAG, "Tethering on (" + iface +"); disable Data Saver");
2495 setRestrictBackground(false);
2496 }
2497 }
2498 }
2499
2500 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002501 public void setRestrictBackground(boolean restrictBackground) {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002502 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setRestrictBackground");
Felipe Leme6a05eee2016-02-19 14:43:51 -08002503 try {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002504 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2505 final long token = Binder.clearCallingIdentity();
2506 try {
2507 maybeRefreshTrustedTime();
2508 synchronized (mUidRulesFirstLock) {
2509 if (restrictBackground == mRestrictBackground) {
2510 // Ideally, UI should never allow this scenario...
2511 Slog.w(TAG, "setRestrictBackground: already " + restrictBackground);
2512 return;
2513 }
2514 setRestrictBackgroundUL(restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002515 }
Felipe Leme29e72ea2016-09-08 13:26:55 -07002516
2517 } finally {
2518 Binder.restoreCallingIdentity(token);
Felipe Leme6a05eee2016-02-19 14:43:51 -08002519 }
Jeff Sharkey46645002011-07-27 21:11:21 -07002520
Felipe Leme29e72ea2016-09-08 13:26:55 -07002521 mHandler.obtainMessage(MSG_RESTRICT_BACKGROUND_CHANGED, restrictBackground ? 1 : 0, 0)
2522 .sendToTarget();
Felipe Leme6a05eee2016-02-19 14:43:51 -08002523 } finally {
Felipe Leme29e72ea2016-09-08 13:26:55 -07002524 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkey46645002011-07-27 21:11:21 -07002525 }
2526 }
2527
Felipe Lemef0823852016-06-08 13:43:08 -07002528 private void setRestrictBackgroundUL(boolean restrictBackground) {
Felipe Leme80f0d0f22016-06-21 13:41:22 -07002529 Slog.d(TAG, "setRestrictBackgroundUL(): " + restrictBackground);
Felipe Leme70c57c22016-03-29 10:45:13 -07002530 final boolean oldRestrictBackground = mRestrictBackground;
2531 mRestrictBackground = restrictBackground;
2532 // Must whitelist foreground apps before turning data saver mode on.
2533 // TODO: there is no need to iterate through all apps here, just those in the foreground,
2534 // so it could call AM to get the UIDs of such apps, and iterate through them instead.
Felipe Leme873a83a2016-09-07 11:34:10 -07002535 updateRulesForRestrictBackgroundUL();
Felipe Leme70c57c22016-03-29 10:45:13 -07002536 try {
2537 if (!mNetworkManager.setDataSaverModeEnabled(mRestrictBackground)) {
2538 Slog.e(TAG, "Could not change Data Saver Mode on NMS to " + mRestrictBackground);
2539 mRestrictBackground = oldRestrictBackground;
2540 // TODO: if it knew the foreground apps (see TODO above), it could call
Felipe Lemef0823852016-06-08 13:43:08 -07002541 // updateRulesForRestrictBackgroundUL() again to restore state.
Felipe Leme70c57c22016-03-29 10:45:13 -07002542 return;
2543 }
2544 } catch (RemoteException e) {
2545 // ignored; service lives in system_server
2546 }
jackqdyulei29c82ab2017-03-10 14:09:16 -08002547
2548 if (mRestrictBackgroundPowerState.globalBatterySaverEnabled) {
2549 mRestrictBackgroundChangedInBsm = true;
2550 }
Felipe Lemef0823852016-06-08 13:43:08 -07002551 synchronized (mNetworkPoliciesSecondLock) {
2552 updateNotificationsNL();
2553 writePolicyAL();
2554 }
Felipe Leme70c57c22016-03-29 10:45:13 -07002555 }
2556
Felipe Lemeb85a6372016-01-14 16:16:16 -08002557 @Override
Felipe Leme1b103232016-01-22 09:44:57 -08002558 public int getRestrictBackgroundByCaller() {
2559 mContext.enforceCallingOrSelfPermission(ACCESS_NETWORK_STATE, TAG);
2560 final int uid = Binder.getCallingUid();
Felipe Leme923845f2016-03-02 13:42:48 -08002561
Felipe Lemef0823852016-06-08 13:43:08 -07002562 synchronized (mUidRulesFirstLock) {
Felipe Leme923845f2016-03-02 13:42:48 -08002563 // Must clear identity because getUidPolicy() is restricted to system.
2564 final long token = Binder.clearCallingIdentity();
2565 final int policy;
2566 try {
2567 policy = getUidPolicy(uid);
2568 } finally {
2569 Binder.restoreCallingIdentity(token);
2570 }
2571 if (policy == POLICY_REJECT_METERED_BACKGROUND) {
2572 // App is blacklisted.
2573 return RESTRICT_BACKGROUND_STATUS_ENABLED;
2574 }
Felipe Leme1b103232016-01-22 09:44:57 -08002575 if (!mRestrictBackground) {
2576 return RESTRICT_BACKGROUND_STATUS_DISABLED;
2577 }
Felipe Leme46b451f2016-08-19 08:46:17 -07002578 return (mUidPolicy.get(uid) & POLICY_ALLOW_METERED_BACKGROUND) != 0
Felipe Leme1b103232016-01-22 09:44:57 -08002579 ? RESTRICT_BACKGROUND_STATUS_WHITELISTED
2580 : RESTRICT_BACKGROUND_STATUS_ENABLED;
2581 }
2582 }
2583
2584 @Override
Jeff Sharkey46645002011-07-27 21:11:21 -07002585 public boolean getRestrictBackground() {
2586 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
2587
Felipe Lemef0823852016-06-08 13:43:08 -07002588 synchronized (mUidRulesFirstLock) {
Jeff Sharkey46645002011-07-27 21:11:21 -07002589 return mRestrictBackground;
2590 }
2591 }
2592
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002593 @Override
2594 public void setDeviceIdleMode(boolean enabled) {
2595 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Felipe Leme873a83a2016-09-07 11:34:10 -07002596 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "setDeviceIdleMode");
2597 try {
2598 synchronized (mUidRulesFirstLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002599 if (mDeviceIdleMode == enabled) {
2600 return;
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002601 }
Felipe Lemeea014392016-09-06 13:59:54 -07002602 mDeviceIdleMode = enabled;
2603 if (mSystemReady) {
2604 // Device idle change means we need to rebuild rules for all
2605 // known apps, so do a global refresh.
2606 updateRulesForRestrictPowerUL();
2607 }
2608 }
2609 if (enabled) {
2610 EventLogTags.writeDeviceIdleOnPhase("net");
2611 } else {
2612 EventLogTags.writeDeviceIdleOffPhase("net");
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002613 }
Felipe Leme873a83a2016-09-07 11:34:10 -07002614 } finally {
2615 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07002616 }
2617 }
2618
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002619 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002620 public void setWifiMeteredOverride(String networkId, int meteredOverride) {
2621 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002622 final long token = Binder.clearCallingIdentity();
2623 try {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002624 final WifiManager wm = mContext.getSystemService(WifiManager.class);
2625 final List<WifiConfiguration> configs = wm.getConfiguredNetworks();
2626 for (WifiConfiguration config : configs) {
2627 if (Objects.equals(resolveNetworkId(config), networkId)) {
2628 config.meteredOverride = meteredOverride;
2629 wm.updateNetwork(config);
2630 }
2631 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07002632 } finally {
2633 Binder.restoreCallingIdentity(token);
2634 }
2635 }
2636
Jeff Sharkey46645002011-07-27 21:11:21 -07002637 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002638 @Deprecated
2639 public NetworkQuotaInfo getNetworkQuotaInfo(NetworkState state) {
2640 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
2641 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
2642 return new NetworkQuotaInfo();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07002643 }
2644
Jeff Sharkey53313d72017-07-13 16:47:32 -06002645 private void enforceSubscriptionPlanAccess(int subId, int callingUid, String callingPackage) {
2646 // Verify they're not lying about package name
2647 mAppOps.checkPackage(callingUid, callingPackage);
2648
Jeff Sharkey53313d72017-07-13 16:47:32 -06002649 final SubscriptionInfo si;
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002650 final PersistableBundle config;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002651 final long token = Binder.clearCallingIdentity();
2652 try {
2653 si = mContext.getSystemService(SubscriptionManager.class)
2654 .getActiveSubscriptionInfo(subId);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002655 config = mCarrierConfigManager.getConfigForSubId(subId);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002656 } finally {
2657 Binder.restoreCallingIdentity(token);
2658 }
2659
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002660 // First check: is caller the CarrierService?
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002661 if (si != null) {
2662 if (si.isEmbedded() && si.canManageSubscription(mContext, callingPackage)) {
2663 return;
2664 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002665 }
2666
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002667 // Second check: has the CarrierService delegated access?
2668 if (config != null) {
2669 final String overridePackage = config
2670 .getString(CarrierConfigManager.KEY_CONFIG_PLANS_PACKAGE_OVERRIDE_STRING, null);
2671 if (!TextUtils.isEmpty(overridePackage)
2672 && Objects.equals(overridePackage, callingPackage)) {
2673 return;
2674 }
2675 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002676
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002677 // Third check: is caller the fallback/default CarrierService?
2678 final String defaultPackage = mCarrierConfigManager.getDefaultCarrierServicePackageName();
2679 if (!TextUtils.isEmpty(defaultPackage)
2680 && Objects.equals(defaultPackage, callingPackage)) {
Jeff Sharkey53313d72017-07-13 16:47:32 -06002681 return;
2682 }
2683
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002684 // Final check: does the caller hold a permission?
2685 mContext.enforceCallingOrSelfPermission(MANAGE_SUBSCRIPTION_PLANS, TAG);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002686 }
2687
2688 @Override
2689 public SubscriptionPlan[] getSubscriptionPlans(int subId, String callingPackage) {
2690 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2691
Jeff Sharkey53313d72017-07-13 16:47:32 -06002692 final String fake = SystemProperties.get("fw.fake_plan");
2693 if (!TextUtils.isEmpty(fake)) {
2694 final List<SubscriptionPlan> plans = new ArrayList<>();
2695 if ("month_hard".equals(fake)) {
2696 plans.add(SubscriptionPlan.Builder
2697 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2698 .setTitle("G-Mobile")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002699 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2700 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2701 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2702 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2703 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002704 plans.add(SubscriptionPlan.Builder
2705 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2706 .setTitle("G-Mobile Happy")
2707 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2708 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2709 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2710 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2711 .build());
2712 plans.add(SubscriptionPlan.Builder
2713 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2714 .setTitle("G-Mobile, Charged after limit")
2715 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2716 SubscriptionPlan.LIMIT_BEHAVIOR_BILLED)
2717 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2718 ZonedDateTime.now().minusHours(36).toInstant().toEpochMilli())
2719 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002720 } else if ("month_soft".equals(fake)) {
2721 plans.add(SubscriptionPlan.Builder
2722 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2723 .setTitle("G-Mobile is the carriers name who this plan belongs to")
2724 .setSummary("Crazy unlimited bandwidth plan with incredibly long title "
2725 + "that should be cut off to prevent UI from looking terrible")
Jeff Sharkey53313d72017-07-13 16:47:32 -06002726 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2727 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2728 .setDataUsage(1 * TrafficStats.GB_IN_BYTES,
2729 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2730 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002731 plans.add(SubscriptionPlan.Builder
2732 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2733 .setTitle("G-Mobile, Throttled after limit")
2734 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2735 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2736 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2737 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2738 .build());
2739 plans.add(SubscriptionPlan.Builder
2740 .createRecurringMonthly(ZonedDateTime.parse("2017-03-14T00:00:00.000Z"))
2741 .setTitle("G-Mobile, No data connection after limit")
2742 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2743 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2744 .setDataUsage(5 * TrafficStats.GB_IN_BYTES,
2745 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2746 .build());
2747
Jeff Sharkey53313d72017-07-13 16:47:32 -06002748 } else if ("month_none".equals(fake)) {
2749 plans.add(SubscriptionPlan.Builder
2750 .createRecurringMonthly(ZonedDateTime.parse("2007-03-14T00:00:00.000Z"))
2751 .setTitle("G-Mobile")
2752 .build());
2753 } else if ("prepaid".equals(fake)) {
2754 plans.add(SubscriptionPlan.Builder
2755 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2756 ZonedDateTime.now().plusDays(10))
2757 .setTitle("G-Mobile")
2758 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2759 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2760 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2761 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2762 .build());
2763 } else if ("prepaid_crazy".equals(fake)) {
2764 plans.add(SubscriptionPlan.Builder
2765 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2766 ZonedDateTime.now().plusDays(10))
2767 .setTitle("G-Mobile Anytime")
2768 .setDataLimit(512 * TrafficStats.MB_IN_BYTES,
2769 SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED)
2770 .setDataUsage(100 * TrafficStats.MB_IN_BYTES,
2771 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2772 .build());
2773 plans.add(SubscriptionPlan.Builder
2774 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2775 ZonedDateTime.now().plusDays(20))
2776 .setTitle("G-Mobile Nickel Nights")
2777 .setSummary("5¢/GB between 1-5AM")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002778 .setDataLimit(5 * TrafficStats.GB_IN_BYTES,
2779 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
Jeff Sharkey53313d72017-07-13 16:47:32 -06002780 .setDataUsage(15 * TrafficStats.MB_IN_BYTES,
2781 ZonedDateTime.now().minusHours(30).toInstant().toEpochMilli())
2782 .build());
2783 plans.add(SubscriptionPlan.Builder
2784 .createNonrecurring(ZonedDateTime.now().minusDays(10),
2785 ZonedDateTime.now().plusDays(20))
2786 .setTitle("G-Mobile Bonus 3G")
2787 .setSummary("Unlimited 3G data")
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002788 .setDataLimit(1 * TrafficStats.GB_IN_BYTES,
Jeff Sharkey53313d72017-07-13 16:47:32 -06002789 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2790 .setDataUsage(300 * TrafficStats.MB_IN_BYTES,
2791 ZonedDateTime.now().minusHours(1).toInstant().toEpochMilli())
2792 .build());
Rajeev Kumar4701beb2017-07-26 17:03:45 -07002793 } else if ("unlimited".equals(fake)) {
2794 plans.add(SubscriptionPlan.Builder
2795 .createNonrecurring(ZonedDateTime.now().minusDays(20),
2796 ZonedDateTime.now().plusDays(10))
2797 .setTitle("G-Mobile Awesome")
2798 .setDataLimit(SubscriptionPlan.BYTES_UNLIMITED,
2799 SubscriptionPlan.LIMIT_BEHAVIOR_THROTTLED)
2800 .setDataUsage(50 * TrafficStats.MB_IN_BYTES,
2801 ZonedDateTime.now().minusHours(3).toInstant().toEpochMilli())
2802 .build());
Jeff Sharkey53313d72017-07-13 16:47:32 -06002803 }
2804 return plans.toArray(new SubscriptionPlan[plans.size()]);
2805 }
2806
Jeff Sharkey4635f102017-09-01 11:27:13 -06002807 synchronized (mNetworkPoliciesSecondLock) {
2808 // Only give out plan details to the package that defined them,
2809 // so that we don't risk leaking plans between apps. We always
2810 // let in core system components (like the Settings app).
2811 final String ownerPackage = mSubscriptionPlansOwner.get(subId);
2812 if (Objects.equals(ownerPackage, callingPackage)
2813 || (UserHandle.getCallingAppId() == android.os.Process.SYSTEM_UID)) {
2814 return mSubscriptionPlans.get(subId);
2815 } else {
2816 Log.w(TAG, "Not returning plans because caller " + callingPackage
2817 + " doesn't match owner " + ownerPackage);
2818 return null;
Jeff Sharkey53313d72017-07-13 16:47:32 -06002819 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002820 }
2821 }
2822
2823 @Override
2824 public void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage) {
2825 enforceSubscriptionPlanAccess(subId, Binder.getCallingUid(), callingPackage);
2826
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002827 for (SubscriptionPlan plan : plans) {
2828 Preconditions.checkNotNull(plan);
Jeff Sharkey53313d72017-07-13 16:47:32 -06002829 }
2830
2831 final long token = Binder.clearCallingIdentity();
2832 try {
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002833 maybeRefreshTrustedTime();
2834 synchronized (mUidRulesFirstLock) {
2835 synchronized (mNetworkPoliciesSecondLock) {
2836 mSubscriptionPlans.put(subId, plans);
Jeff Sharkeyb74799882017-07-28 16:55:41 -06002837 mSubscriptionPlansOwner.put(subId, callingPackage);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002838
2839 final String subscriberId = mContext.getSystemService(TelephonyManager.class)
2840 .getSubscriberId(subId);
2841 ensureActiveMobilePolicyAL(subId, subscriberId);
2842 maybeUpdateMobilePolicyCycleAL(subId);
2843 handleNetworkPoliciesUpdateAL(true);
Jeff Sharkey17bebd22017-07-19 21:00:38 -06002844 }
Jeff Sharkey53313d72017-07-13 16:47:32 -06002845 }
2846 } finally {
2847 Binder.restoreCallingIdentity(token);
2848 }
2849 }
2850
2851 @Override
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002852 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06002853 if (!DumpUtils.checkDumpPermission(mContext, TAG, writer)) return;
Jeff Sharkey1b861272011-05-22 00:34:52 -07002854
Jeff Sharkey8fc27e82012-04-04 20:40:58 -07002855 final IndentingPrintWriter fout = new IndentingPrintWriter(writer, " ");
2856
Dianne Hackborn497175b2014-07-01 12:56:08 -07002857 final ArraySet<String> argSet = new ArraySet<String>(args.length);
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002858 for (String arg : args) {
2859 argSet.add(arg);
2860 }
2861
Felipe Lemef0823852016-06-08 13:43:08 -07002862 synchronized (mUidRulesFirstLock) {
2863 synchronized (mNetworkPoliciesSecondLock) {
2864 if (argSet.contains("--unsnooze")) {
2865 for (int i = mNetworkPolicy.size()-1; i >= 0; i--) {
2866 mNetworkPolicy.valueAt(i).clearSnooze();
2867 }
2868
Ammar Aijazi6ce48e22017-03-28 15:43:22 -07002869 handleNetworkPoliciesUpdateAL(true);
Felipe Lemef0823852016-06-08 13:43:08 -07002870
2871 fout.println("Cleared snooze timestamps");
2872 return;
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07002873 }
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08002874
Felipe Lemef0823852016-06-08 13:43:08 -07002875 fout.print("System ready: "); fout.println(mSystemReady);
2876 fout.print("Restrict background: "); fout.println(mRestrictBackground);
2877 fout.print("Restrict power: "); fout.println(mRestrictPower);
2878 fout.print("Device idle: "); fout.println(mDeviceIdleMode);
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002879 fout.print("Metered ifaces: "); fout.println(String.valueOf(mMeteredIfaces));
2880
2881 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002882 fout.println("Network policies:");
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002883 fout.increaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002884 for (int i = 0; i < mNetworkPolicy.size(); i++) {
2885 fout.println(mNetworkPolicy.valueAt(i).toString());
2886 }
2887 fout.decreaseIndent();
2888
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002889 fout.println();
2890 fout.println("Subscription plans:");
2891 fout.increaseIndent();
2892 for (int i = 0; i < mSubscriptionPlans.size(); i++) {
2893 final int subId = mSubscriptionPlans.keyAt(i);
2894 fout.println("Subscriber ID " + subId + ":");
2895 fout.increaseIndent();
2896 final SubscriptionPlan[] plans = mSubscriptionPlans.valueAt(i);
2897 if (!ArrayUtils.isEmpty(plans)) {
2898 for (SubscriptionPlan plan : plans) {
2899 fout.println(plan);
2900 }
2901 }
2902 fout.decreaseIndent();
2903 }
2904 fout.decreaseIndent();
Felipe Lemef0823852016-06-08 13:43:08 -07002905
Jeff Sharkey0f2910c2017-07-30 16:52:51 -06002906 fout.println();
Felipe Lemef0823852016-06-08 13:43:08 -07002907 fout.println("Policy for UIDs:");
2908 fout.increaseIndent();
2909 int size = mUidPolicy.size();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002910 for (int i = 0; i < size; i++) {
Felipe Lemef0823852016-06-08 13:43:08 -07002911 final int uid = mUidPolicy.keyAt(i);
2912 final int policy = mUidPolicy.valueAt(i);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07002913 fout.print("UID=");
Felipe Lemef0823852016-06-08 13:43:08 -07002914 fout.print(uid);
2915 fout.print(" policy=");
Felipe Lemeb146f762016-08-19 09:52:16 -07002916 fout.print(uidPoliciesToString(policy));
Felipe Lemef0823852016-06-08 13:43:08 -07002917 fout.println();
2918 }
2919 fout.decreaseIndent();
2920
2921 size = mPowerSaveWhitelistExceptIdleAppIds.size();
2922 if (size > 0) {
2923 fout.println("Power save whitelist (except idle) app ids:");
2924 fout.increaseIndent();
2925 for (int i = 0; i < size; i++) {
2926 fout.print("UID=");
2927 fout.print(mPowerSaveWhitelistExceptIdleAppIds.keyAt(i));
2928 fout.print(": ");
2929 fout.print(mPowerSaveWhitelistExceptIdleAppIds.valueAt(i));
2930 fout.println();
2931 }
2932 fout.decreaseIndent();
2933 }
2934
2935 size = mPowerSaveWhitelistAppIds.size();
2936 if (size > 0) {
2937 fout.println("Power save whitelist app ids:");
2938 fout.increaseIndent();
2939 for (int i = 0; i < size; i++) {
2940 fout.print("UID=");
2941 fout.print(mPowerSaveWhitelistAppIds.keyAt(i));
2942 fout.print(": ");
2943 fout.print(mPowerSaveWhitelistAppIds.valueAt(i));
2944 fout.println();
2945 }
2946 fout.decreaseIndent();
2947 }
2948
Felipe Lemef0823852016-06-08 13:43:08 -07002949 size = mDefaultRestrictBackgroundWhitelistUids.size();
2950 if (size > 0) {
2951 fout.println("Default restrict background whitelist uids:");
2952 fout.increaseIndent();
2953 for (int i = 0; i < size; i++) {
2954 fout.print("UID=");
2955 fout.print(mDefaultRestrictBackgroundWhitelistUids.keyAt(i));
2956 fout.println();
2957 }
2958 fout.decreaseIndent();
2959 }
2960
2961 size = mRestrictBackgroundWhitelistRevokedUids.size();
2962 if (size > 0) {
2963 fout.println("Default restrict background whitelist uids revoked by users:");
2964 fout.increaseIndent();
2965 for (int i = 0; i < size; i++) {
2966 fout.print("UID=");
2967 fout.print(mRestrictBackgroundWhitelistRevokedUids.keyAt(i));
2968 fout.println();
2969 }
2970 fout.decreaseIndent();
2971 }
2972
2973 final SparseBooleanArray knownUids = new SparseBooleanArray();
2974 collectKeys(mUidState, knownUids);
2975 collectKeys(mUidRules, knownUids);
2976
2977 fout.println("Status for all known UIDs:");
2978 fout.increaseIndent();
2979 size = knownUids.size();
2980 for (int i = 0; i < size; i++) {
2981 final int uid = knownUids.keyAt(i);
2982 fout.print("UID=");
2983 fout.print(uid);
2984
2985 final int state = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
2986 fout.print(" state=");
2987 fout.print(state);
2988 if (state <= ActivityManager.PROCESS_STATE_TOP) {
2989 fout.print(" (fg)");
2990 } else {
2991 fout.print(state <= ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE
2992 ? " (fg svc)" : " (bg)");
2993 }
2994
2995 final int uidRules = mUidRules.get(uid, RULE_NONE);
2996 fout.print(" rules=");
2997 fout.print(uidRulesToString(uidRules));
2998 fout.println();
2999 }
3000 fout.decreaseIndent();
3001
3002 fout.println("Status for just UIDs with rules:");
3003 fout.increaseIndent();
3004 size = mUidRules.size();
3005 for (int i = 0; i < size; i++) {
3006 final int uid = mUidRules.keyAt(i);
3007 fout.print("UID=");
3008 fout.print(uid);
3009 final int uidRules = mUidRules.get(uid, RULE_NONE);
3010 fout.print(" rules=");
3011 fout.print(uidRulesToString(uidRules));
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003012 fout.println();
3013 }
3014 fout.decreaseIndent();
Sudheer Shankae7361852017-03-07 11:51:46 -08003015
3016 fout.println("Observed uid state changes:");
3017 fout.increaseIndent();
3018 mObservedHistory.dumpUL(fout);
3019 fout.decreaseIndent();
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003020 }
Jeff Sharkey1b861272011-05-22 00:34:52 -07003021 }
3022 }
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003023
3024 @Override
Felipe Leme50a235e2016-01-15 18:37:06 -08003025 public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err,
Dianne Hackborn354736e2016-08-22 17:00:05 -07003026 String[] args, ShellCallback callback, ResultReceiver resultReceiver) {
Felipe Lemeb1a65ee2016-02-08 10:12:01 -08003027 (new NetworkPolicyManagerShellCommand(mContext, this)).exec(
Dianne Hackborn354736e2016-08-22 17:00:05 -07003028 this, in, out, err, args, callback, resultReceiver);
Felipe Leme50a235e2016-01-15 18:37:06 -08003029 }
3030
3031 @Override
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003032 public boolean isUidForeground(int uid) {
Jeff Sharkey497e4432011-06-14 17:27:29 -07003033 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
3034
Felipe Lemef0823852016-06-08 13:43:08 -07003035 synchronized (mUidRulesFirstLock) {
3036 return isUidForegroundUL(uid);
Jeff Sharkey9599cc52011-05-22 14:59:31 -07003037 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003038 }
3039
Felipe Lemef0823852016-06-08 13:43:08 -07003040 private boolean isUidForegroundUL(int uid) {
3041 return isUidStateForegroundUL(
Felipe Lemef28983d2016-03-25 12:18:23 -07003042 mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY));
3043 }
3044
Felipe Lemef0823852016-06-08 13:43:08 -07003045 private boolean isUidForegroundOnRestrictBackgroundUL(int uid) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003046 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003047 return isProcStateAllowedWhileOnRestrictBackground(procState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003048 }
3049
Felipe Lemef0823852016-06-08 13:43:08 -07003050 private boolean isUidForegroundOnRestrictPowerUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003051 final int procState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3052 return isProcStateAllowedWhileIdleOrPowerSaveMode(procState);
3053 }
3054
Felipe Lemef0823852016-06-08 13:43:08 -07003055 private boolean isUidStateForegroundUL(int state) {
Dianne Hackborn497175b2014-07-01 12:56:08 -07003056 // only really in foreground when screen is also on
Felipe Leme88f40ad2016-08-10 13:00:32 -07003057 return state <= ActivityManager.PROCESS_STATE_TOP;
Dianne Hackborn497175b2014-07-01 12:56:08 -07003058 }
3059
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003060 /**
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003061 * Process state of UID changed; if needed, will trigger
Felipe Lemef0823852016-06-08 13:43:08 -07003062 * {@link #updateRulesForDataUsageRestrictionsUL(int)} and
3063 * {@link #updateRulesForPowerRestrictionsUL(int)}
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003064 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003065 private void updateUidStateUL(int uid, int uidState) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003066 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateUidStateUL");
3067 try {
3068 final int oldUidState = mUidState.get(uid, ActivityManager.PROCESS_STATE_CACHED_EMPTY);
3069 if (oldUidState != uidState) {
3070 // state changed, push updated rules
3071 mUidState.put(uid, uidState);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003072 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState, uidState);
3073 if (isProcStateAllowedWhileIdleOrPowerSaveMode(oldUidState)
3074 != isProcStateAllowedWhileIdleOrPowerSaveMode(uidState) ) {
Sudheer Shanka9e77d232017-08-14 14:43:11 -07003075 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003076 if (mDeviceIdleMode) {
3077 updateRuleForDeviceIdleUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003078 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003079 if (mRestrictPower) {
3080 updateRuleForRestrictPowerUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003081 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003082 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003083 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003084 updateNetworkStats(uid, isUidStateForegroundUL(uidState));
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003085 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003086 } finally {
3087 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003088 }
3089 }
3090
Felipe Lemef0823852016-06-08 13:43:08 -07003091 private void removeUidStateUL(int uid) {
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003092 final int index = mUidState.indexOfKey(uid);
3093 if (index >= 0) {
3094 final int oldUidState = mUidState.valueAt(index);
3095 mUidState.removeAt(index);
3096 if (oldUidState != ActivityManager.PROCESS_STATE_CACHED_EMPTY) {
Felipe Lemef0823852016-06-08 13:43:08 -07003097 updateRestrictBackgroundRulesOnUidStatusChangedUL(uid, oldUidState,
Sudheer Shankac9d94072017-02-22 22:13:55 +00003098 ActivityManager.PROCESS_STATE_CACHED_EMPTY);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003099 if (mDeviceIdleMode) {
Felipe Lemef0823852016-06-08 13:43:08 -07003100 updateRuleForDeviceIdleUL(uid);
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003101 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003102 if (mRestrictPower) {
Felipe Lemef0823852016-06-08 13:43:08 -07003103 updateRuleForRestrictPowerUL(uid);
Felipe Leme011b98f2016-02-10 17:28:31 -08003104 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003105 updateRulesForPowerRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003106 updateNetworkStats(uid, false);
Dianne Hackborn497175b2014-07-01 12:56:08 -07003107 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003108 }
3109 }
3110
Felipe Lemef28983d2016-03-25 12:18:23 -07003111 // adjust stats accounting based on foreground status
3112 private void updateNetworkStats(int uid, boolean uidForeground) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003113 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3114 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3115 "updateNetworkStats: " + uid + "/" + (uidForeground ? "F" : "B"));
3116 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003117 try {
3118 mNetworkStats.setUidForeground(uid, uidForeground);
3119 } catch (RemoteException e) {
3120 // ignored; service lives in system_server
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003121 } finally {
3122 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Lemef28983d2016-03-25 12:18:23 -07003123 }
3124 }
3125
Sudheer Shankac9d94072017-02-22 22:13:55 +00003126 private void updateRestrictBackgroundRulesOnUidStatusChangedUL(int uid, int oldUidState,
3127 int newUidState) {
Felipe Lemeef89c902016-03-30 15:11:31 -07003128 final boolean oldForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003129 isProcStateAllowedWhileOnRestrictBackground(oldUidState);
Felipe Lemeef89c902016-03-30 15:11:31 -07003130 final boolean newForeground =
Sudheer Shankac9d94072017-02-22 22:13:55 +00003131 isProcStateAllowedWhileOnRestrictBackground(newUidState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003132 if (oldForeground != newForeground) {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003133 updateRulesForDataUsageRestrictionsUL(uid);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003134 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003135 }
3136
Felipe Lemef0823852016-06-08 13:43:08 -07003137 void updateRulesForPowerSaveUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003138 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForPowerSaveUL");
3139 try {
3140 updateRulesForWhitelistedPowerSaveUL(mRestrictPower, FIREWALL_CHAIN_POWERSAVE,
3141 mUidFirewallPowerSaveRules);
3142 } finally {
3143 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3144 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003145 }
3146
Felipe Lemef0823852016-06-08 13:43:08 -07003147 void updateRuleForRestrictPowerUL(int uid) {
3148 updateRulesForWhitelistedPowerSaveUL(uid, mRestrictPower, FIREWALL_CHAIN_POWERSAVE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003149 }
3150
Felipe Lemef0823852016-06-08 13:43:08 -07003151 void updateRulesForDeviceIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003152 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForDeviceIdleUL");
3153 try {
3154 updateRulesForWhitelistedPowerSaveUL(mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE,
3155 mUidFirewallDozableRules);
3156 } finally {
3157 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3158 }
Felipe Leme011b98f2016-02-10 17:28:31 -08003159 }
3160
Felipe Lemef0823852016-06-08 13:43:08 -07003161 void updateRuleForDeviceIdleUL(int uid) {
3162 updateRulesForWhitelistedPowerSaveUL(uid, mDeviceIdleMode, FIREWALL_CHAIN_DOZABLE);
Felipe Leme011b98f2016-02-10 17:28:31 -08003163 }
3164
Felipe Lemef28983d2016-03-25 12:18:23 -07003165 // NOTE: since both fw_dozable and fw_powersave uses the same map
3166 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003167 private void updateRulesForWhitelistedPowerSaveUL(boolean enabled, int chain,
Felipe Leme011b98f2016-02-10 17:28:31 -08003168 SparseIntArray rules) {
3169 if (enabled) {
3170 // Sync the whitelists before enabling the chain. We don't care about the rules if
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003171 // we are disabling the chain.
Felipe Leme011b98f2016-02-10 17:28:31 -08003172 final SparseIntArray uidRules = rules;
Jeff Sharkeydc988062015-09-14 10:09:47 -07003173 uidRules.clear();
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003174 final List<UserInfo> users = mUserManager.getUsers();
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003175 for (int ui = users.size() - 1; ui >= 0; ui--) {
3176 UserInfo user = users.get(ui);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003177 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveTempWhitelistAppIds, user.id);
3178 updateRulesForWhitelistedAppIds(uidRules, mPowerSaveWhitelistAppIds, user.id);
3179 if (chain == FIREWALL_CHAIN_POWERSAVE) {
3180 updateRulesForWhitelistedAppIds(uidRules,
3181 mPowerSaveWhitelistExceptIdleAppIds, user.id);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003182 }
3183 }
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003184 for (int i = mUidState.size() - 1; i >= 0; i--) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003185 if (isProcStateAllowedWhileIdleOrPowerSaveMode(mUidState.valueAt(i))) {
Dianne Hackbornfd854ee2015-07-13 18:00:37 -07003186 uidRules.put(mUidState.keyAt(i), FIREWALL_RULE_ALLOW);
3187 }
3188 }
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003189 setUidFirewallRulesUL(chain, uidRules, CHAIN_TOGGLE_ENABLE);
Felipe Lemebc853dd2016-09-08 13:26:55 -07003190 } else {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003191 setUidFirewallRulesUL(chain, null, CHAIN_TOGGLE_DISABLE);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003192 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003193 }
3194
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003195 private void updateRulesForWhitelistedAppIds(final SparseIntArray uidRules,
3196 final SparseBooleanArray whitelistedAppIds, int userId) {
3197 for (int i = whitelistedAppIds.size() - 1; i >= 0; --i) {
3198 if (whitelistedAppIds.valueAt(i)) {
3199 final int appId = whitelistedAppIds.keyAt(i);
3200 final int uid = UserHandle.getUid(userId, appId);
3201 uidRules.put(uid, FIREWALL_RULE_ALLOW);
3202 }
3203 }
3204 }
3205
3206 /**
3207 * @param deviceIdleMode if true then we don't consider
3208 * {@link #mPowerSaveWhitelistExceptIdleAppIds} for checking if the {@param uid} is
3209 * whitelisted.
3210 */
3211 private boolean isWhitelistedBatterySaverUL(int uid, boolean deviceIdleMode) {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003212 final int appId = UserHandle.getAppId(uid);
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003213 boolean isWhitelisted = mPowerSaveTempWhitelistAppIds.get(appId)
3214 || mPowerSaveWhitelistAppIds.get(appId);
3215 if (!deviceIdleMode) {
3216 isWhitelisted = isWhitelisted || mPowerSaveWhitelistExceptIdleAppIds.get(appId);
3217 }
3218 return isWhitelisted;
Felipe Leme46c4fc32016-05-04 09:21:43 -07003219 }
3220
Felipe Lemef28983d2016-03-25 12:18:23 -07003221 // NOTE: since both fw_dozable and fw_powersave uses the same map
3222 // (mPowerSaveTempWhitelistAppIds) for whitelisting, we can reuse their logic in this method.
Felipe Lemef0823852016-06-08 13:43:08 -07003223 private void updateRulesForWhitelistedPowerSaveUL(int uid, boolean enabled, int chain) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003224 if (enabled) {
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003225 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid,
3226 chain == FIREWALL_CHAIN_DOZABLE);
3227 if (isWhitelisted || isUidForegroundOnRestrictPowerUL(uid)) {
Felipe Leme011b98f2016-02-10 17:28:31 -08003228 setUidFirewallRule(chain, uid, FIREWALL_RULE_ALLOW);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003229 } else {
Felipe Leme011b98f2016-02-10 17:28:31 -08003230 setUidFirewallRule(chain, uid, FIREWALL_RULE_DEFAULT);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003231 }
3232 }
3233 }
3234
Felipe Lemef0823852016-06-08 13:43:08 -07003235 void updateRulesForAppIdleUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003236 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForAppIdleUL");
3237 try {
3238 final SparseIntArray uidRules = mUidFirewallStandbyRules;
3239 uidRules.clear();
Jeff Sharkeydc988062015-09-14 10:09:47 -07003240
Felipe Leme873a83a2016-09-07 11:34:10 -07003241 // Fully update the app idle firewall chain.
3242 final List<UserInfo> users = mUserManager.getUsers();
3243 for (int ui = users.size() - 1; ui >= 0; ui--) {
3244 UserInfo user = users.get(ui);
3245 int[] idleUids = mUsageStats.getIdleUidsForUser(user.id);
3246 for (int uid : idleUids) {
3247 if (!mPowerSaveTempWhitelistAppIds.get(UserHandle.getAppId(uid), false)) {
3248 // quick check: if this uid doesn't have INTERNET permission, it
3249 // doesn't have network access anyway, so it is a waste to mess
3250 // with it here.
3251 if (hasInternetPermissions(uid)) {
3252 uidRules.put(uid, FIREWALL_RULE_DENY);
3253 }
Soi, Yoshinaria065da12015-12-22 12:02:18 +09003254 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003255 }
3256 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003257
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07003258 setUidFirewallRulesUL(FIREWALL_CHAIN_STANDBY, uidRules, CHAIN_TOGGLE_NONE);
Felipe Leme873a83a2016-09-07 11:34:10 -07003259 } finally {
3260 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3261 }
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003262 }
3263
Felipe Lemef0823852016-06-08 13:43:08 -07003264 void updateRuleForAppIdleUL(int uid) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003265 if (!isUidValidForBlacklistRules(uid)) return;
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003266
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003267 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3268 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRuleForAppIdleUL: " + uid );
3269 }
3270 try {
3271 int appId = UserHandle.getAppId(uid);
3272 if (!mPowerSaveTempWhitelistAppIds.get(appId) && isUidIdle(uid)
3273 && !isUidForegroundOnRestrictPowerUL(uid)) {
3274 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DENY);
3275 } else {
3276 setUidFirewallRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
3277 }
3278 } finally {
3279 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Dianne Hackborn4a503b12015-08-06 22:19:06 -07003280 }
3281 }
3282
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003283 /**
3284 * Toggle the firewall standby chain and inform listeners if the uid rules have effectively
3285 * changed.
3286 */
Felipe Lemef0823852016-06-08 13:43:08 -07003287 void updateRulesForAppIdleParoleUL() {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003288 boolean paroled = mUsageStats.isAppIdleParoleOn();
3289 boolean enableChain = !paroled;
Felipe Lemef0823852016-06-08 13:43:08 -07003290 enableFirewallChainUL(FIREWALL_CHAIN_STANDBY, enableChain);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003291
3292 int ruleCount = mUidFirewallStandbyRules.size();
3293 for (int i = 0; i < ruleCount; i++) {
3294 int uid = mUidFirewallStandbyRules.keyAt(i);
3295 int oldRules = mUidRules.get(uid);
3296 if (enableChain) {
3297 // Chain wasn't enabled before and the other power-related
3298 // chains are whitelists, so we can clear the
3299 // MASK_ALL_NETWORKS part of the rules and re-inform listeners if
3300 // the effective rules result in blocking network access.
3301 oldRules &= MASK_METERED_NETWORKS;
3302 } else {
3303 // Skip if it had no restrictions to begin with
3304 if ((oldRules & MASK_ALL_NETWORKS) == 0) continue;
3305 }
Sudheer Shanka3af02942017-04-12 14:29:14 -07003306 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldRules, paroled);
3307 if (newUidRules == RULE_NONE) {
3308 mUidRules.delete(uid);
3309 } else {
3310 mUidRules.put(uid, newUidRules);
3311 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003312 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07003313 }
3314
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003315 /**
Dianne Hackborn8ad2af72015-03-17 17:00:24 -07003316 * Update rules that might be changed by {@link #mRestrictBackground},
3317 * {@link #mRestrictPower}, or {@link #mDeviceIdleMode} value.
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003318 */
Felipe Lemef0823852016-06-08 13:43:08 -07003319 private void updateRulesForGlobalChangeAL(boolean restrictedNetworksChanged) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003320 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3321 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3322 "updateRulesForGlobalChangeAL: " + (restrictedNetworksChanged ? "R" : "-"));
3323 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003324 try {
Felipe Leme09700462016-09-08 09:33:48 -07003325 updateRulesForAppIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003326 updateRulesForRestrictPowerUL();
3327 updateRulesForRestrictBackgroundUL();
Felipe Leme03e689d2016-03-02 16:17:38 -08003328
Felipe Leme873a83a2016-09-07 11:34:10 -07003329 // If the set of restricted networks may have changed, re-evaluate those.
3330 if (restrictedNetworksChanged) {
3331 normalizePoliciesNL();
3332 updateNetworkRulesNL();
3333 }
3334 } finally {
3335 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Felipe Leme76010a32016-03-17 13:03:11 -07003336 }
3337 }
3338
Felipe Leme09700462016-09-08 09:33:48 -07003339 // TODO: rename / document to make it clear these are global (not app-specific) rules
Felipe Lemef0823852016-06-08 13:43:08 -07003340 private void updateRulesForRestrictPowerUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003341 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL");
3342 try {
3343 updateRulesForDeviceIdleUL();
Felipe Leme873a83a2016-09-07 11:34:10 -07003344 updateRulesForPowerSaveUL();
3345 updateRulesForAllAppsUL(TYPE_RESTRICT_POWER);
3346 } finally {
3347 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3348 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003349 }
3350
Felipe Lemef0823852016-06-08 13:43:08 -07003351 private void updateRulesForRestrictBackgroundUL() {
Felipe Leme873a83a2016-09-07 11:34:10 -07003352 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictBackgroundUL");
3353 try {
3354 updateRulesForAllAppsUL(TYPE_RESTRICT_BACKGROUND);
3355 } finally {
3356 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3357 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003358 }
3359
3360 private static final int TYPE_RESTRICT_BACKGROUND = 1;
3361 private static final int TYPE_RESTRICT_POWER = 2;
3362 @Retention(RetentionPolicy.SOURCE)
3363 @IntDef(flag = false, value = {
3364 TYPE_RESTRICT_BACKGROUND,
3365 TYPE_RESTRICT_POWER,
3366 })
3367 public @interface RestrictType {
3368 }
3369
3370 // TODO: refactor / consolidate all those updateXyz methods, there are way too many of them...
Felipe Lemef0823852016-06-08 13:43:08 -07003371 private void updateRulesForAllAppsUL(@RestrictType int type) {
Felipe Leme873a83a2016-09-07 11:34:10 -07003372 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3373 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "updateRulesForRestrictPowerUL-" + type);
3374 }
3375 try {
Felipe Leme873a83a2016-09-07 11:34:10 -07003376 // update rules for all installed applications
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003377
3378 final PackageManager pm = mContext.getPackageManager();
3379 final List<UserInfo> users;
3380 final List<ApplicationInfo> apps;
3381
3382 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-users");
3383 try {
3384 users = mUserManager.getUsers();
3385 } finally {
3386 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3387 }
3388 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "list-uids");
3389 try {
3390 apps = pm.getInstalledApplications(
3391 PackageManager.MATCH_ANY_USER | PackageManager.MATCH_DISABLED_COMPONENTS
3392 | PackageManager.MATCH_DIRECT_BOOT_AWARE
3393 | PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
3394 } finally {
3395 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3396 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003397
Felipe Leme873a83a2016-09-07 11:34:10 -07003398 final int usersSize = users.size();
3399 final int appsSize = apps.size();
3400 for (int i = 0; i < usersSize; i++) {
3401 final UserInfo user = users.get(i);
3402 for (int j = 0; j < appsSize; j++) {
3403 final ApplicationInfo app = apps.get(j);
3404 final int uid = UserHandle.getUid(user.id, app.uid);
3405 switch (type) {
3406 case TYPE_RESTRICT_BACKGROUND:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003407 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003408 break;
3409 case TYPE_RESTRICT_POWER:
Sudheer Shankac9d94072017-02-22 22:13:55 +00003410 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme873a83a2016-09-07 11:34:10 -07003411 break;
3412 default:
3413 Slog.w(TAG, "Invalid type for updateRulesForAllApps: " + type);
3414 }
Felipe Lemef3e40642016-06-07 17:28:08 -07003415 }
Jeff Sharkeyd0c6ccb2012-09-14 16:26:37 -07003416 }
Felipe Leme873a83a2016-09-07 11:34:10 -07003417 } finally {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003418 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003419 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003420 }
3421
Felipe Lemef0823852016-06-08 13:43:08 -07003422 private void updateRulesForTempWhitelistChangeUL() {
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003423 final List<UserInfo> users = mUserManager.getUsers();
Felipe Leme03e689d2016-03-02 16:17:38 -08003424 for (int i = 0; i < users.size(); i++) {
3425 final UserInfo user = users.get(i);
Rakesh Iyer4f3fc212016-03-03 20:16:41 -08003426 for (int j = mPowerSaveTempWhitelistAppIds.size() - 1; j >= 0; j--) {
Felipe Leme03e689d2016-03-02 16:17:38 -08003427 int appId = mPowerSaveTempWhitelistAppIds.keyAt(j);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003428 int uid = UserHandle.getUid(user.id, appId);
Felipe Leme781ba142016-05-09 16:24:48 -07003429 // Update external firewall rules.
Felipe Lemef0823852016-06-08 13:43:08 -07003430 updateRuleForAppIdleUL(uid);
3431 updateRuleForDeviceIdleUL(uid);
3432 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003433 // Update internal rules.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003434 updateRulesForPowerRestrictionsUL(uid);
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003435 }
3436 }
3437 }
3438
Felipe Leme70c57c22016-03-29 10:45:13 -07003439 // TODO: the MEDIA / DRM restriction might not be needed anymore, in which case both
3440 // methods below could be merged into a isUidValidForRules() method.
3441 private boolean isUidValidForBlacklistRules(int uid) {
3442 // allow rules on specific system services, and any apps
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003443 if (uid == android.os.Process.MEDIA_UID || uid == android.os.Process.DRM_UID
Felipe Leme70c57c22016-03-29 10:45:13 -07003444 || (UserHandle.isApp(uid) && hasInternetPermissions(uid))) {
Jeff Sharkey5294a2f2012-04-24 17:07:22 -07003445 return true;
3446 }
3447
3448 return false;
3449 }
3450
Felipe Leme70c57c22016-03-29 10:45:13 -07003451 private boolean isUidValidForWhitelistRules(int uid) {
3452 return UserHandle.isApp(uid) && hasInternetPermissions(uid);
3453 }
3454
Amith Yamasani15e472352015-04-24 19:06:07 -07003455 private boolean isUidIdle(int uid) {
3456 final String[] packages = mContext.getPackageManager().getPackagesForUid(uid);
3457 final int userId = UserHandle.getUserId(uid);
3458
songjinshi0655edd2016-05-18 19:55:32 +08003459 if (packages != null) {
Jeff Sharkey377ded0f2016-01-10 13:15:41 -07003460 for (String packageName : packages) {
3461 if (!mUsageStats.isAppIdle(packageName, uid, userId)) {
3462 return false;
3463 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003464 }
3465 }
3466 return true;
3467 }
3468
3469 /**
Felipe Leme47585ba2016-02-09 16:56:32 -08003470 * Checks if an uid has INTERNET permissions.
3471 * <p>
3472 * Useful for the cases where the lack of network access can simplify the rules.
Amith Yamasani15e472352015-04-24 19:06:07 -07003473 */
Felipe Leme47585ba2016-02-09 16:56:32 -08003474 private boolean hasInternetPermissions(int uid) {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003475 try {
Amith Yamasani2a4ac4e2016-02-12 12:43:15 -08003476 if (mIPm.checkUidPermission(Manifest.permission.INTERNET, uid)
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003477 != PackageManager.PERMISSION_GRANTED) {
Felipe Leme47585ba2016-02-09 16:56:32 -08003478 return false;
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003479 }
3480 } catch (RemoteException e) {
3481 }
Felipe Leme47585ba2016-02-09 16:56:32 -08003482 return true;
3483 }
3484
3485 /**
Felipe Leme03e95e22016-09-09 09:25:31 -07003486 * Clears all state - internal and external - associated with an UID.
3487 */
3488 private void onUidDeletedUL(int uid) {
3489 // First cleanup in-memory state synchronously...
3490 mUidRules.delete(uid);
3491 mUidPolicy.delete(uid);
3492 mUidFirewallStandbyRules.delete(uid);
3493 mUidFirewallDozableRules.delete(uid);
3494 mUidFirewallPowerSaveRules.delete(uid);
3495 mPowerSaveWhitelistExceptIdleAppIds.delete(uid);
3496 mPowerSaveWhitelistAppIds.delete(uid);
3497 mPowerSaveTempWhitelistAppIds.delete(uid);
3498
3499 // ...then update iptables asynchronously.
3500 mHandler.obtainMessage(MSG_RESET_FIREWALL_RULES_BY_UID, uid, 0).sendToTarget();
3501 }
3502
3503 /**
Felipe Lemef28983d2016-03-25 12:18:23 -07003504 * Applies network rules to bandwidth and firewall controllers based on uid policy.
Felipe Leme76010a32016-03-17 13:03:11 -07003505 *
Felipe Leme781ba142016-05-09 16:24:48 -07003506 * <p>There are currently 4 types of restriction rules:
Felipe Lemef28983d2016-03-25 12:18:23 -07003507 * <ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003508 * <li>Doze mode
3509 * <li>App idle mode
Felipe Lemef28983d2016-03-25 12:18:23 -07003510 * <li>Battery Saver Mode (also referred as power save).
Felipe Leme46c4fc32016-05-04 09:21:43 -07003511 * <li>Data Saver Mode (The Feature Formerly Known As 'Restrict Background Data').
Felipe Lemef28983d2016-03-25 12:18:23 -07003512 * </ul>
Felipe Leme781ba142016-05-09 16:24:48 -07003513 *
3514 * <p>This method changes both the external firewall rules and the internal state.
Felipe Leme47585ba2016-02-09 16:56:32 -08003515 */
Felipe Leme03e95e22016-09-09 09:25:31 -07003516 private void updateRestrictionRulesForUidUL(int uid) {
Felipe Leme781ba142016-05-09 16:24:48 -07003517 // Methods below only changes the firewall rules for the power-related modes.
Felipe Lemef0823852016-06-08 13:43:08 -07003518 updateRuleForDeviceIdleUL(uid);
3519 updateRuleForAppIdleUL(uid);
3520 updateRuleForRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003521
3522 // Update internal state for power-related modes.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003523 updateRulesForPowerRestrictionsUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003524
3525 // Update firewall and internal rules for Data Saver Mode.
Sudheer Shankac9d94072017-02-22 22:13:55 +00003526 updateRulesForDataUsageRestrictionsUL(uid);
Felipe Lemef28983d2016-03-25 12:18:23 -07003527 }
3528
Felipe Leme70c57c22016-03-29 10:45:13 -07003529 /**
3530 * Applies network rules to bandwidth controllers based on process state and user-defined
3531 * restrictions (blacklist / whitelist).
3532 *
3533 * <p>
3534 * {@code netd} defines 3 firewall chains that govern whether an app has access to metered
3535 * networks:
3536 * <ul>
3537 * <li>@{code bw_penalty_box}: UIDs added to this chain do not have access (blacklist).
3538 * <li>@{code bw_happy_box}: UIDs added to this chain have access (whitelist), unless they're
3539 * also blacklisted.
3540 * <li>@{code bw_data_saver}: when enabled (through {@link #setRestrictBackground(boolean)}),
3541 * no UIDs other those whitelisted will have access.
3542 * <ul>
3543 *
3544 * <p>The @{code bw_penalty_box} and @{code bw_happy_box} are primarily managed through the
3545 * {@link #setUidPolicy(int, int)} and {@link #addRestrictBackgroundWhitelistedUid(int)} /
3546 * {@link #removeRestrictBackgroundWhitelistedUid(int)} methods (for blacklist and whitelist
3547 * respectively): these methods set the proper internal state (blacklist / whitelist), then call
Felipe Lemef0823852016-06-08 13:43:08 -07003548 * this ({@link #updateRulesForDataUsageRestrictionsUL(int)}) to propagate the rules to
Felipe Leme70c57c22016-03-29 10:45:13 -07003549 * {@link INetworkManagementService}, but this method should also be called in events (like
3550 * Data Saver Mode flips or UID state changes) that might affect the foreground app, since the
3551 * following rules should also be applied:
3552 *
3553 * <ul>
3554 * <li>When Data Saver mode is on, the foreground app should be temporarily added to
3555 * {@code bw_happy_box} before the @{code bw_data_saver} chain is enabled.
3556 * <li>If the foreground app is blacklisted by the user, it should be temporarily removed from
3557 * {@code bw_penalty_box}.
3558 * <li>When the app leaves foreground state, the temporary changes above should be reverted.
3559 * </ul>
3560 *
3561 * <p>For optimization, the rules are only applied on user apps that have internet access
3562 * permission, since there is no need to change the {@code iptables} rule if the app does not
3563 * have permission to use the internet.
3564 *
3565 * <p>The {@link #mUidRules} map is used to define the transtion of states of an UID.
Felipe Lemed31a97f2016-05-06 14:53:50 -07003566 *
Felipe Leme70c57c22016-03-29 10:45:13 -07003567 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003568 private void updateRulesForDataUsageRestrictionsUL(int uid) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003569 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3570 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3571 "updateRulesForDataUsageRestrictionsUL: " + uid);
3572 }
3573 try {
3574 updateRulesForDataUsageRestrictionsULInner(uid);
3575 } finally {
3576 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3577 }
3578 }
3579
3580 private void updateRulesForDataUsageRestrictionsULInner(int uid) {
Felipe Leme03e95e22016-09-09 09:25:31 -07003581 if (!isUidValidForWhitelistRules(uid)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003582 if (LOGD) Slog.d(TAG, "no need to update restrict data rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003583 return;
Felipe Leme70c57c22016-03-29 10:45:13 -07003584 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003585
Dianne Hackborn497175b2014-07-01 12:56:08 -07003586 final int uidPolicy = mUidPolicy.get(uid, POLICY_NONE);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003587 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
Felipe Lemef0823852016-06-08 13:43:08 -07003588 final boolean isForeground = isUidForegroundOnRestrictBackgroundUL(uid);
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07003589
Felipe Leme781ba142016-05-09 16:24:48 -07003590 final boolean isBlacklisted = (uidPolicy & POLICY_REJECT_METERED_BACKGROUND) != 0;
Felipe Leme46b451f2016-08-19 08:46:17 -07003591 final boolean isWhitelisted = (uidPolicy & POLICY_ALLOW_METERED_BACKGROUND) != 0;
Felipe Leme781ba142016-05-09 16:24:48 -07003592 final int oldRule = oldUidRules & MASK_METERED_NETWORKS;
3593 int newRule = RULE_NONE;
Felipe Leme76010a32016-03-17 13:03:11 -07003594
Felipe Leme70c57c22016-03-29 10:45:13 -07003595 // First step: define the new rule based on user restrictions and foreground state.
3596 if (isForeground) {
Felipe Leme781ba142016-05-09 16:24:48 -07003597 if (isBlacklisted || (mRestrictBackground && !isWhitelisted)) {
3598 newRule = RULE_TEMPORARY_ALLOW_METERED;
3599 } else if (isWhitelisted) {
3600 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003601 }
3602 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003603 if (isBlacklisted) {
3604 newRule = RULE_REJECT_METERED;
3605 } else if (mRestrictBackground && isWhitelisted) {
3606 newRule = RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003607 }
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07003608 }
Felipe Leme781ba142016-05-09 16:24:48 -07003609 final int newUidRules = newRule | (oldUidRules & MASK_ALL_NETWORKS);
Felipe Leme46c4fc32016-05-04 09:21:43 -07003610
Felipe Lemef28983d2016-03-25 12:18:23 -07003611 if (LOGV) {
Felipe Lemef0823852016-06-08 13:43:08 -07003612 Log.v(TAG, "updateRuleForRestrictBackgroundUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003613 + ": isForeground=" +isForeground
3614 + ", isBlacklisted=" + isBlacklisted
3615 + ", isWhitelisted=" + isWhitelisted
3616 + ", oldRule=" + uidRulesToString(oldRule)
3617 + ", newRule=" + uidRulesToString(newRule)
3618 + ", newUidRules=" + uidRulesToString(newUidRules)
3619 + ", oldUidRules=" + uidRulesToString(oldUidRules));
Felipe Lemef28983d2016-03-25 12:18:23 -07003620 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003621
Felipe Leme46c4fc32016-05-04 09:21:43 -07003622 if (newUidRules == RULE_NONE) {
Jeff Sharkey350083e2011-06-29 10:45:16 -07003623 mUidRules.delete(uid);
3624 } else {
Felipe Leme46c4fc32016-05-04 09:21:43 -07003625 mUidRules.put(uid, newUidRules);
Jeff Sharkey350083e2011-06-29 10:45:16 -07003626 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003627
Felipe Leme70c57c22016-03-29 10:45:13 -07003628 // Second step: apply bw changes based on change of state.
Felipe Leme781ba142016-05-09 16:24:48 -07003629 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003630 if (hasRule(newRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003631 // Temporarily whitelist foreground app, removing from blacklist if necessary
3632 // (since bw_penalty_box prevails over bw_happy_box).
3633
3634 setMeteredNetworkWhitelist(uid, true);
3635 // TODO: if statement below is used to avoid an unnecessary call to netd / iptables,
3636 // but ideally it should be just:
3637 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003638 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003639 setMeteredNetworkBlacklist(uid, false);
3640 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003641 } else if (hasRule(oldRule, RULE_TEMPORARY_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003642 // Remove temporary whitelist from app that is not on foreground anymore.
3643
3644 // TODO: if statements below are used to avoid unnecessary calls to netd / iptables,
3645 // but ideally they should be just:
3646 // setMeteredNetworkWhitelist(uid, isWhitelisted);
3647 // setMeteredNetworkBlacklist(uid, isBlacklisted);
Felipe Leme781ba142016-05-09 16:24:48 -07003648 if (!isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003649 setMeteredNetworkWhitelist(uid, false);
3650 }
Felipe Leme781ba142016-05-09 16:24:48 -07003651 if (isBlacklisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003652 setMeteredNetworkBlacklist(uid, true);
3653 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003654 } else if (hasRule(newRule, RULE_REJECT_METERED)
3655 || hasRule(oldRule, RULE_REJECT_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003656 // Flip state because app was explicitly added or removed to blacklist.
Felipe Leme781ba142016-05-09 16:24:48 -07003657 setMeteredNetworkBlacklist(uid, isBlacklisted);
Hugo Benichi2966c182017-03-28 17:17:13 +09003658 if (hasRule(oldRule, RULE_REJECT_METERED) && isWhitelisted) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003659 // Since blacklist prevails over whitelist, we need to handle the special case
3660 // where app is whitelisted and blacklisted at the same time (although such
3661 // scenario should be blocked by the UI), then blacklist is removed.
Felipe Leme781ba142016-05-09 16:24:48 -07003662 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003663 }
Hugo Benichi2966c182017-03-28 17:17:13 +09003664 } else if (hasRule(newRule, RULE_ALLOW_METERED)
3665 || hasRule(oldRule, RULE_ALLOW_METERED)) {
Felipe Leme70c57c22016-03-29 10:45:13 -07003666 // Flip state because app was explicitly added or removed to whitelist.
Felipe Leme781ba142016-05-09 16:24:48 -07003667 setMeteredNetworkWhitelist(uid, isWhitelisted);
Felipe Leme70c57c22016-03-29 10:45:13 -07003668 } else {
Felipe Leme781ba142016-05-09 16:24:48 -07003669 // All scenarios should have been covered above.
Felipe Leme46c4fc32016-05-04 09:21:43 -07003670 Log.wtf(TAG, "Unexpected change of metered UID state for " + uid
3671 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003672 + ", whitelisted=" + isWhitelisted
3673 + ", blacklisted=" + isBlacklisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003674 + ", newRule=" + uidRulesToString(newUidRules)
3675 + ", oldRule=" + uidRulesToString(oldUidRules));
Felipe Leme70c57c22016-03-29 10:45:13 -07003676 }
Felipe Leme781ba142016-05-09 16:24:48 -07003677
Sudheer Shankac9d94072017-02-22 22:13:55 +00003678 // Dispatch changed rule to existing listeners.
3679 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Felipe Leme781ba142016-05-09 16:24:48 -07003680 }
3681 }
3682
3683 /**
3684 * Updates the power-related part of the {@link #mUidRules} for a given map, and notify external
3685 * listeners in case of change.
3686 * <p>
3687 * There are 3 power-related rules that affects whether an app has background access on
3688 * non-metered networks, and when the condition applies and the UID is not whitelisted for power
3689 * restriction, it's added to the equivalent firewall chain:
3690 * <ul>
3691 * <li>App is idle: {@code fw_standby} firewall chain.
3692 * <li>Device is idle: {@code fw_dozable} firewall chain.
3693 * <li>Battery Saver Mode is on: {@code fw_powersave} firewall chain.
3694 * </ul>
3695 * <p>
3696 * This method updates the power-related part of the {@link #mUidRules} for a given uid based on
3697 * these modes, the UID process state (foreground or not), and the UIDwhitelist state.
3698 * <p>
3699 * <strong>NOTE: </strong>This method does not update the firewall rules on {@code netd}.
3700 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003701 private void updateRulesForPowerRestrictionsUL(int uid) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003702 final int oldUidRules = mUidRules.get(uid, RULE_NONE);
3703
Sudheer Shankac9d94072017-02-22 22:13:55 +00003704 final int newUidRules = updateRulesForPowerRestrictionsUL(uid, oldUidRules, false);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003705
Sudheer Shankac9d94072017-02-22 22:13:55 +00003706 if (newUidRules == RULE_NONE) {
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003707 mUidRules.delete(uid);
3708 } else {
Sudheer Shankac9d94072017-02-22 22:13:55 +00003709 mUidRules.put(uid, newUidRules);
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003710 }
3711 }
3712
3713 /**
3714 * Similar to above but ignores idle state if app standby is currently disabled by parole.
3715 *
3716 * @param uid the uid of the app to update rules for
3717 * @param oldUidRules the current rules for the uid, in order to determine if there's a change
3718 * @param paroled whether to ignore idle state of apps and only look at other restrictions.
3719 *
Sudheer Shankac9d94072017-02-22 22:13:55 +00003720 * @return the new computed rules for the uid
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003721 */
Sudheer Shankac9d94072017-02-22 22:13:55 +00003722 private int updateRulesForPowerRestrictionsUL(int uid, int oldUidRules, boolean paroled) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07003723 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
3724 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
3725 "updateRulesForPowerRestrictionsUL: " + uid + "/" + oldUidRules + "/"
3726 + (paroled ? "P" : "-"));
3727 }
3728 try {
3729 return updateRulesForPowerRestrictionsULInner(uid, oldUidRules, paroled);
3730 } finally {
3731 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
3732 }
3733 }
3734
3735 private int updateRulesForPowerRestrictionsULInner(int uid, int oldUidRules, boolean paroled) {
Felipe Leme781ba142016-05-09 16:24:48 -07003736 if (!isUidValidForBlacklistRules(uid)) {
3737 if (LOGD) Slog.d(TAG, "no need to update restrict power rules for uid " + uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003738 return RULE_NONE;
Felipe Lemed31a97f2016-05-06 14:53:50 -07003739 }
Felipe Lemef28983d2016-03-25 12:18:23 -07003740
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003741 final boolean isIdle = !paroled && isUidIdle(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003742 final boolean restrictMode = isIdle || mRestrictPower || mDeviceIdleMode;
Felipe Lemef0823852016-06-08 13:43:08 -07003743 final boolean isForeground = isUidForegroundOnRestrictPowerUL(uid);
Felipe Leme781ba142016-05-09 16:24:48 -07003744
Sudheer Shanka54a92fd2017-04-26 10:43:23 -07003745 final boolean isWhitelisted = isWhitelistedBatterySaverUL(uid, mDeviceIdleMode);
Felipe Leme781ba142016-05-09 16:24:48 -07003746 final int oldRule = oldUidRules & MASK_ALL_NETWORKS;
3747 int newRule = RULE_NONE;
3748
3749 // First step: define the new rule based on user restrictions and foreground state.
3750
3751 // NOTE: if statements below could be inlined, but it's easier to understand the logic
3752 // by considering the foreground and non-foreground states.
3753 if (isForeground) {
3754 if (restrictMode) {
3755 newRule = RULE_ALLOW_ALL;
3756 }
3757 } else if (restrictMode) {
3758 newRule = isWhitelisted ? RULE_ALLOW_ALL : RULE_REJECT_ALL;
3759 }
3760
3761 final int newUidRules = (oldUidRules & MASK_METERED_NETWORKS) | newRule;
3762
3763 if (LOGV) {
Felipe Leme88f40ad2016-08-10 13:00:32 -07003764 Log.v(TAG, "updateRulesForPowerRestrictionsUL(" + uid + ")"
Felipe Leme781ba142016-05-09 16:24:48 -07003765 + ", isIdle: " + isIdle
3766 + ", mRestrictPower: " + mRestrictPower
3767 + ", mDeviceIdleMode: " + mDeviceIdleMode
3768 + ", isForeground=" + isForeground
3769 + ", isWhitelisted=" + isWhitelisted
3770 + ", oldRule=" + uidRulesToString(oldRule)
3771 + ", newRule=" + uidRulesToString(newRule)
3772 + ", newUidRules=" + uidRulesToString(newUidRules)
3773 + ", oldUidRules=" + uidRulesToString(oldUidRules));
3774 }
3775
Felipe Leme781ba142016-05-09 16:24:48 -07003776 // Second step: notify listeners if state changed.
3777 if (newRule != oldRule) {
Hugo Benichi2966c182017-03-28 17:17:13 +09003778 if (newRule == RULE_NONE || hasRule(newRule, RULE_ALLOW_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003779 if (LOGV) Log.v(TAG, "Allowing non-metered access for UID " + uid);
Hugo Benichi2966c182017-03-28 17:17:13 +09003780 } else if (hasRule(newRule, RULE_REJECT_ALL)) {
Felipe Lemed31a97f2016-05-06 14:53:50 -07003781 if (LOGV) Log.v(TAG, "Rejecting non-metered access for UID " + uid);
3782 } else {
3783 // All scenarios should have been covered above
3784 Log.wtf(TAG, "Unexpected change of non-metered UID state for " + uid
3785 + ": foreground=" + isForeground
Felipe Leme781ba142016-05-09 16:24:48 -07003786 + ", whitelisted=" + isWhitelisted
Felipe Lemed31a97f2016-05-06 14:53:50 -07003787 + ", newRule=" + uidRulesToString(newUidRules)
3788 + ", oldRule=" + uidRulesToString(oldUidRules));
3789 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003790 mHandler.obtainMessage(MSG_RULES_CHANGED, uid, newUidRules).sendToTarget();
Amith Yamasani15e472352015-04-24 19:06:07 -07003791 }
Amith Yamasani0938f2f2016-09-16 12:46:31 -07003792
Sudheer Shankac9d94072017-02-22 22:13:55 +00003793 return newUidRules;
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003794 }
3795
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003796 private class AppIdleStateChangeListener
3797 extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3798
3799 @Override
3800 public void onAppIdleStateChanged(String packageName, int userId, boolean idle) {
3801 try {
Jeff Sharkeyc5967e92016-01-07 18:50:29 -07003802 final int uid = mContext.getPackageManager().getPackageUidAsUser(packageName,
3803 PackageManager.MATCH_UNINSTALLED_PACKAGES, userId);
Felipe Leme781ba142016-05-09 16:24:48 -07003804 if (LOGV) Log.v(TAG, "onAppIdleStateChanged(): uid=" + uid + ", idle=" + idle);
Felipe Lemef0823852016-06-08 13:43:08 -07003805 synchronized (mUidRulesFirstLock) {
3806 updateRuleForAppIdleUL(uid);
Sudheer Shankac9d94072017-02-22 22:13:55 +00003807 updateRulesForPowerRestrictionsUL(uid);
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003808 }
3809 } catch (NameNotFoundException nnfe) {
Amith Yamasani15e472352015-04-24 19:06:07 -07003810 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003811 }
3812
3813 @Override
3814 public void onParoleStateChanged(boolean isParoleOn) {
Felipe Lemef0823852016-06-08 13:43:08 -07003815 synchronized (mUidRulesFirstLock) {
3816 updateRulesForAppIdleParoleUL();
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07003817 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003818 }
3819 }
3820
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003821 private void dispatchUidRulesChanged(INetworkPolicyListener listener, int uid, int uidRules) {
3822 if (listener != null) {
3823 try {
3824 listener.onUidRulesChanged(uid, uidRules);
3825 } catch (RemoteException ignored) {
3826 }
3827 }
3828 }
3829
3830 private void dispatchMeteredIfacesChanged(INetworkPolicyListener listener,
3831 String[] meteredIfaces) {
3832 if (listener != null) {
3833 try {
3834 listener.onMeteredIfacesChanged(meteredIfaces);
3835 } catch (RemoteException ignored) {
3836 }
3837 }
3838 }
3839
3840 private void dispatchRestrictBackgroundChanged(INetworkPolicyListener listener,
3841 boolean restrictBackground) {
3842 if (listener != null) {
3843 try {
3844 listener.onRestrictBackgroundChanged(restrictBackground);
3845 } catch (RemoteException ignored) {
3846 }
3847 }
3848 }
3849
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003850 private void dispatchUidPoliciesChanged(INetworkPolicyListener listener, int uid,
3851 int uidPolicies) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003852 if (listener != null) {
3853 try {
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003854 listener.onUidPoliciesChanged(uid, uidPolicies);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003855 } catch (RemoteException ignored) {
3856 }
3857 }
3858 }
3859
Makoto Onuki8e777332017-03-28 11:25:47 -07003860 private final Handler.Callback mHandlerCallback = new Handler.Callback() {
Jeff Sharkeybfdd6802012-04-09 10:49:19 -07003861 @Override
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003862 public boolean handleMessage(Message msg) {
3863 switch (msg.what) {
3864 case MSG_RULES_CHANGED: {
3865 final int uid = msg.arg1;
3866 final int uidRules = msg.arg2;
Sudheer Shankac9d94072017-02-22 22:13:55 +00003867 final int length = mListeners.beginBroadcast();
3868 for (int i = 0; i < length; i++) {
3869 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
3870 dispatchUidRulesChanged(listener, uid, uidRules);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003871 }
Sudheer Shankac9d94072017-02-22 22:13:55 +00003872 mListeners.finishBroadcast();
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003873 return true;
3874 }
3875 case MSG_METERED_IFACES_CHANGED: {
3876 final String[] meteredIfaces = (String[]) msg.obj;
3877 final int length = mListeners.beginBroadcast();
3878 for (int i = 0; i < length; i++) {
3879 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003880 dispatchMeteredIfacesChanged(listener, meteredIfaces);
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003881 }
3882 mListeners.finishBroadcast();
3883 return true;
3884 }
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003885 case MSG_LIMIT_REACHED: {
3886 final String iface = (String) msg.obj;
3887
Jeff Sharkey684c54a2011-11-16 17:46:30 -08003888 maybeRefreshTrustedTime();
Felipe Lemef0823852016-06-08 13:43:08 -07003889 synchronized (mNetworkPoliciesSecondLock) {
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003890 if (mMeteredIfaces.contains(iface)) {
3891 try {
3892 // force stats update to make sure we have
3893 // numbers that caused alert to trigger.
3894 mNetworkStats.forceUpdate();
3895 } catch (RemoteException e) {
3896 // ignored; service lives in system_server
3897 }
3898
Felipe Lemef0823852016-06-08 13:43:08 -07003899 updateNetworkEnabledNL();
3900 updateNotificationsNL();
Jeff Sharkey7e25b0e2011-11-08 15:43:12 -08003901 }
3902 }
3903 return true;
3904 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003905 case MSG_RESTRICT_BACKGROUND_CHANGED: {
3906 final boolean restrictBackground = msg.arg1 != 0;
3907 final int length = mListeners.beginBroadcast();
3908 for (int i = 0; i < length; i++) {
3909 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003910 dispatchRestrictBackgroundChanged(listener, restrictBackground);
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003911 }
3912 mListeners.finishBroadcast();
Felipe Leme9778f762016-01-27 14:46:39 -08003913 final Intent intent =
3914 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
3915 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
3916 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
3917 return true;
3918 }
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003919 case MSG_POLICIES_CHANGED: {
Felipe Leme9778f762016-01-27 14:46:39 -08003920 final int uid = msg.arg1;
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003921 final int policy = msg.arg2;
Felipe Leme57e3d312016-08-23 14:42:52 -07003922 final Boolean notifyApp = (Boolean) msg.obj;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003923 // First notify internal listeners...
Felipe Leme57e3d312016-08-23 14:42:52 -07003924 final int length = mListeners.beginBroadcast();
3925 for (int i = 0; i < length; i++) {
3926 final INetworkPolicyListener listener = mListeners.getBroadcastItem(i);
Felipe Leme0ecfcd12016-09-06 12:49:48 -07003927 dispatchUidPoliciesChanged(listener, uid, policy);
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003928 }
3929 mListeners.finishBroadcast();
Felipe Leme57e3d312016-08-23 14:42:52 -07003930 // ...then apps listening to ACTION_RESTRICT_BACKGROUND_CHANGED
3931 if (notifyApp.booleanValue()) {
3932 broadcastRestrictBackgroundChanged(uid, notifyApp);
3933 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07003934 return true;
3935 }
Jeff Sharkeye19f39b2012-05-24 10:21:16 -07003936 case MSG_ADVISE_PERSIST_THRESHOLD: {
3937 final long lowestRule = (Long) msg.obj;
3938 try {
3939 // make sure stats are recorded frequently enough; we aim
3940 // for 2MB threshold for 2GB/month rules.
3941 final long persistThreshold = lowestRule / 1000;
3942 mNetworkStats.advisePersistThreshold(persistThreshold);
3943 } catch (RemoteException e) {
3944 // ignored; service lives in system_server
3945 }
3946 return true;
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08003947 }
Amith Yamasani3646cbd2016-04-13 14:04:53 -07003948 case MSG_UPDATE_INTERFACE_QUOTA: {
3949 removeInterfaceQuota((String) msg.obj);
3950 // int params need to be stitched back into a long
3951 setInterfaceQuota((String) msg.obj,
3952 ((long) msg.arg1 << 32) | (msg.arg2 & 0xFFFFFFFFL));
3953 return true;
3954 }
3955 case MSG_REMOVE_INTERFACE_QUOTA: {
3956 removeInterfaceQuota((String) msg.obj);
3957 return true;
3958 }
Felipe Leme03e95e22016-09-09 09:25:31 -07003959 case MSG_RESET_FIREWALL_RULES_BY_UID: {
3960 resetUidFirewallRules(msg.arg1);
3961 return true;
3962 }
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003963 default: {
3964 return false;
Jeff Sharkeyaf11d482011-06-13 00:14:31 -07003965 }
3966 }
3967 }
Makoto Onuki8e777332017-03-28 11:25:47 -07003968 };
3969
3970 private final Handler.Callback mUidEventHandlerCallback = new Handler.Callback() {
3971 @Override
3972 public boolean handleMessage(Message msg) {
3973 switch (msg.what) {
3974 case UID_MSG_STATE_CHANGED: {
3975 final int uid = msg.arg1;
3976 final int procState = msg.arg2;
3977 final long procStateSeq = (Long) msg.obj;
3978
3979 handleUidChanged(uid, procState, procStateSeq);
3980 return true;
3981 }
3982 case UID_MSG_GONE: {
3983 final int uid = msg.arg1;
3984 handleUidGone(uid);
3985 return true;
3986 }
3987 default: {
3988 return false;
3989 }
3990 }
3991 }
Felipe Leme57e3d312016-08-23 14:42:52 -07003992
Jeff Sharkey4414cea2011-06-24 17:05:24 -07003993 };
Jeff Sharkey22c055e2011-06-12 21:13:51 -07003994
Makoto Onuki8e777332017-03-28 11:25:47 -07003995 void handleUidChanged(int uid, int procState, long procStateSeq) {
3996 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidStateChanged");
3997 try {
3998 synchronized (mUidRulesFirstLock) {
3999 // We received a uid state change callback, add it to the history so that it
4000 // will be useful for debugging.
4001 mObservedHistory.addProcStateSeqUL(uid, procStateSeq);
4002 // Now update the network policy rules as per the updated uid state.
4003 updateUidStateUL(uid, procState);
4004 // Updating the network rules is done, so notify AMS about this.
4005 mActivityManagerInternal.notifyNetworkPolicyRulesUpdated(uid, procStateSeq);
4006 }
4007 } finally {
4008 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4009 }
4010 }
4011
4012 void handleUidGone(int uid) {
4013 Trace.traceBegin(Trace.TRACE_TAG_NETWORK, "onUidGone");
4014 try {
4015 synchronized (mUidRulesFirstLock) {
4016 removeUidStateUL(uid);
4017 }
4018 } finally {
4019 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
4020 }
4021 }
4022
Felipe Leme57e3d312016-08-23 14:42:52 -07004023 private void broadcastRestrictBackgroundChanged(int uid, Boolean changed) {
4024 final PackageManager pm = mContext.getPackageManager();
4025 final String[] packages = pm.getPackagesForUid(uid);
4026 if (packages != null) {
4027 final int userId = UserHandle.getUserId(uid);
4028 for (String packageName : packages) {
4029 final Intent intent =
4030 new Intent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
4031 intent.setPackage(packageName);
4032 intent.setFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
4033 mContext.sendBroadcastAsUser(intent, UserHandle.of(userId));
4034 }
4035 }
4036 }
4037
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004038 private void setInterfaceQuotaAsync(String iface, long quotaBytes) {
4039 // long quotaBytes split up into two ints to fit in message
4040 mHandler.obtainMessage(MSG_UPDATE_INTERFACE_QUOTA, (int) (quotaBytes >> 32),
4041 (int) (quotaBytes & 0xFFFFFFFF), iface).sendToTarget();
4042 }
4043
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004044 private void setInterfaceQuota(String iface, long quotaBytes) {
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004045 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004046 mNetworkManager.setInterfaceQuota(iface, quotaBytes);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004047 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004048 Log.wtf(TAG, "problem setting interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004049 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004050 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004051 }
4052 }
4053
Jeff Sharkey64c96ec2017-08-30 16:28:26 -06004054 private void removeInterfaceQuotaAsync(String iface) {
4055 mHandler.obtainMessage(MSG_REMOVE_INTERFACE_QUOTA, iface).sendToTarget();
4056 }
4057
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004058 private void removeInterfaceQuota(String iface) {
4059 try {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004060 mNetworkManager.removeInterfaceQuota(iface);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004061 } catch (IllegalStateException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004062 Log.wtf(TAG, "problem removing interface quota", e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004063 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004064 // ignored; service lives in system_server
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004065 }
4066 }
4067
Felipe Leme70c57c22016-03-29 10:45:13 -07004068 private void setMeteredNetworkBlacklist(int uid, boolean enable) {
4069 if (LOGV) Slog.v(TAG, "setMeteredNetworkBlacklist " + uid + ": " + enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004070 try {
Felipe Leme70c57c22016-03-29 10:45:13 -07004071 mNetworkManager.setUidMeteredNetworkBlacklist(uid, enable);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004072 } catch (IllegalStateException e) {
Felipe Leme70c57c22016-03-29 10:45:13 -07004073 Log.wtf(TAG, "problem setting blacklist (" + enable + ") rules for " + uid, e);
4074 } catch (RemoteException e) {
4075 // ignored; service lives in system_server
4076 }
4077 }
4078
4079 private void setMeteredNetworkWhitelist(int uid, boolean enable) {
4080 if (LOGV) Slog.v(TAG, "setMeteredNetworkWhitelist " + uid + ": " + enable);
4081 try {
4082 mNetworkManager.setUidMeteredNetworkWhitelist(uid, enable);
4083 } catch (IllegalStateException e) {
4084 Log.wtf(TAG, "problem setting whitelist (" + enable + ") rules for " + uid, e);
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004085 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004086 // ignored; service lives in system_server
Jeff Sharkeyb3f19ca2011-06-29 23:54:13 -07004087 }
4088 }
4089
Felipe Lemebc853dd2016-09-08 13:26:55 -07004090 private static final int CHAIN_TOGGLE_NONE = 0;
4091 private static final int CHAIN_TOGGLE_ENABLE = 1;
4092 private static final int CHAIN_TOGGLE_DISABLE = 2;
4093 @Retention(RetentionPolicy.SOURCE)
4094 @IntDef(flag = false, value = {
4095 CHAIN_TOGGLE_NONE,
4096 CHAIN_TOGGLE_ENABLE,
4097 CHAIN_TOGGLE_DISABLE
4098 })
4099 public @interface ChainToggleType {
4100 }
4101
4102 /**
4103 * Calls {@link #setUidFirewallRules(int, SparseIntArray)} and
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004104 * {@link #enableFirewallChainUL(int, boolean)} synchronously.
Felipe Lemebc853dd2016-09-08 13:26:55 -07004105 *
4106 * @param chain firewall chain.
4107 * @param uidRules new UID rules; if {@code null}, only toggles chain state.
4108 * @param toggle whether the chain should be enabled, disabled, or not changed.
4109 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004110 private void setUidFirewallRulesUL(int chain, @Nullable SparseIntArray uidRules,
Felipe Lemebc853dd2016-09-08 13:26:55 -07004111 @ChainToggleType int toggle) {
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004112 if (uidRules != null) {
4113 setUidFirewallRulesUL(chain, uidRules);
4114 }
4115 if (toggle != CHAIN_TOGGLE_NONE) {
4116 enableFirewallChainUL(chain, toggle == CHAIN_TOGGLE_ENABLE);
4117 }
Felipe Lemebc853dd2016-09-08 13:26:55 -07004118 }
4119
Amith Yamasani15e472352015-04-24 19:06:07 -07004120 /**
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004121 * Set uid rules on a particular firewall chain. This is going to synchronize the rules given
4122 * here to netd. It will clean up dead rules and make sure the target chain only contains rules
4123 * specified here.
Amith Yamasani15e472352015-04-24 19:06:07 -07004124 */
Sudheer Shankaaddebcc2017-10-03 09:43:20 -07004125 private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) {
Amith Yamasani15e472352015-04-24 19:06:07 -07004126 try {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004127 int size = uidRules.size();
4128 int[] uids = new int[size];
4129 int[] rules = new int[size];
4130 for(int index = size - 1; index >= 0; --index) {
4131 uids[index] = uidRules.keyAt(index);
4132 rules[index] = uidRules.valueAt(index);
4133 }
4134 mNetworkManager.setFirewallUidRules(chain, uids, rules);
Amith Yamasani15e472352015-04-24 19:06:07 -07004135 } catch (IllegalStateException e) {
4136 Log.wtf(TAG, "problem setting firewall uid rules", e);
4137 } catch (RemoteException e) {
4138 // ignored; service lives in system_server
4139 }
4140 }
4141
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004142 /**
4143 * Add or remove a uid to the firewall blacklist for all network ifaces.
4144 */
Dianne Hackborn4a503b12015-08-06 22:19:06 -07004145 private void setUidFirewallRule(int chain, int uid, int rule) {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004146 if (Trace.isTagEnabled(Trace.TRACE_TAG_NETWORK)) {
4147 Trace.traceBegin(Trace.TRACE_TAG_NETWORK,
4148 "setUidFirewallRule: " + chain + "/" + uid + "/" + rule);
Jeff Sharkeydc988062015-09-14 10:09:47 -07004149 }
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004150 try {
Makoto Onuki0e6e3bd2017-03-20 14:53:00 -07004151 if (chain == FIREWALL_CHAIN_DOZABLE) {
4152 mUidFirewallDozableRules.put(uid, rule);
4153 } else if (chain == FIREWALL_CHAIN_STANDBY) {
4154 mUidFirewallStandbyRules.put(uid, rule);
4155 } else if (chain == FIREWALL_CHAIN_POWERSAVE) {
4156 mUidFirewallPowerSaveRules.put(uid, rule);
4157 }
4158
4159 try {
4160 mNetworkManager.setFirewallUidRule(chain, uid, rule);
4161 } catch (IllegalStateException e) {
4162 Log.wtf(TAG, "problem setting firewall uid rules", e);
4163 } catch (RemoteException e) {
4164 // ignored; service lives in system_server
4165 }
4166 } finally {
4167 Trace.traceEnd(Trace.TRACE_TAG_NETWORK);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004168 }
4169 }
4170
4171 /**
4172 * Add or remove a uid to the firewall blacklist for all network ifaces.
4173 */
Felipe Lemef0823852016-06-08 13:43:08 -07004174 private void enableFirewallChainUL(int chain, boolean enable) {
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004175 if (mFirewallChainStates.indexOfKey(chain) >= 0 &&
4176 mFirewallChainStates.get(chain) == enable) {
4177 // All is the same, nothing to do.
4178 return;
4179 }
Xiaohui Chen8dca36d2015-06-19 12:44:59 -07004180 mFirewallChainStates.put(chain, enable);
Xiaohui Chenb41c9f72015-06-17 15:55:37 -07004181 try {
4182 mNetworkManager.setFirewallChainEnabled(chain, enable);
4183 } catch (IllegalStateException e) {
4184 Log.wtf(TAG, "problem enable firewall chain", e);
4185 } catch (RemoteException e) {
4186 // ignored; service lives in system_server
4187 }
4188 }
4189
Felipe Leme03e95e22016-09-09 09:25:31 -07004190 /**
4191 * Resets all firewall rules associated with an UID.
4192 */
4193 private void resetUidFirewallRules(int uid) {
4194 try {
4195 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT);
4196 mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT);
4197 mNetworkManager
4198 .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT);
4199 mNetworkManager.setUidMeteredNetworkWhitelist(uid, false);
4200 mNetworkManager.setUidMeteredNetworkBlacklist(uid, false);
4201 } catch (IllegalStateException e) {
4202 Log.wtf(TAG, "problem resetting firewall uid rules for " + uid, e);
4203 } catch (RemoteException e) {
4204 // ignored; service lives in system_server
4205 }
4206 }
4207
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004208 private long getTotalBytes(NetworkTemplate template, long start, long end) {
4209 try {
Jeff Sharkeyb52e3e52012-04-06 11:12:08 -07004210 return mNetworkStats.getNetworkTotalBytes(template, start, end);
Jeff Sharkey63abc372012-01-11 18:38:16 -08004211 } catch (RuntimeException e) {
4212 Slog.w(TAG, "problem reading network stats: " + e);
4213 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004214 } catch (RemoteException e) {
Jeff Sharkeyb3d59572011-09-07 17:20:27 -07004215 // ignored; service lives in system_server
4216 return 0;
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004217 }
4218 }
4219
Jeff Sharkey8c1dc722012-05-04 14:49:37 -07004220 private boolean isBandwidthControlEnabled() {
4221 final long token = Binder.clearCallingIdentity();
4222 try {
4223 return mNetworkManager.isBandwidthControlEnabled();
4224 } catch (RemoteException e) {
4225 // ignored; service lives in system_server
4226 return false;
4227 } finally {
4228 Binder.restoreCallingIdentity(token);
4229 }
4230 }
4231
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004232 /**
4233 * Try refreshing {@link #mTime} when stale.
4234 */
Dianne Hackborn497175b2014-07-01 12:56:08 -07004235 void maybeRefreshTrustedTime() {
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004236 if (mTime.getCacheAge() > TIME_CACHE_MAX_AGE) {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004237 mTime.forceRefresh();
4238 }
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004239 }
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004240
Jeff Sharkey684c54a2011-11-16 17:46:30 -08004241 private long currentTimeMillis() {
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -07004242 return mTime.hasCache() ? mTime.currentTimeMillis() : System.currentTimeMillis();
4243 }
4244
Jeff Sharkey3a844fc2011-08-16 14:37:57 -07004245 private static Intent buildAllowBackgroundDataIntent() {
4246 return new Intent(ACTION_ALLOW_BACKGROUND);
4247 }
4248
Jeff Sharkey0e2e5f82012-02-02 16:02:51 -08004249 private static Intent buildSnoozeWarningIntent(NetworkTemplate template) {
4250 final Intent intent = new Intent(ACTION_SNOOZE_WARNING);
4251 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4252 return intent;
4253 }
4254
Wei Liu546cb772016-07-21 16:19:01 -07004255 private static Intent buildNetworkOverLimitIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004256 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004257 intent.setComponent(ComponentName.unflattenFromString(
4258 res.getString(R.string.config_networkOverLimitComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004259 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4260 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4261 return intent;
4262 }
4263
Wei Liu546cb772016-07-21 16:19:01 -07004264 private static Intent buildViewDataUsageIntent(Resources res, NetworkTemplate template) {
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004265 final Intent intent = new Intent();
Wei Liu546cb772016-07-21 16:19:01 -07004266 intent.setComponent(ComponentName.unflattenFromString(
4267 res.getString(R.string.config_dataUsageSummaryComponent)));
Jeff Sharkey41ff7ec2011-07-25 15:21:22 -07004268 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
4269 intent.putExtra(EXTRA_NETWORK_TEMPLATE, template);
4270 return intent;
4271 }
4272
Jeff Sharkey8b2c3a142012-11-12 11:45:05 -08004273 @VisibleForTesting
Jeff Sharkey163e6442011-10-31 16:37:52 -07004274 public void addIdleHandler(IdleHandler handler) {
4275 mHandler.getLooper().getQueue().addIdleHandler(handler);
4276 }
4277
jackqdyulei29c82ab2017-03-10 14:09:16 -08004278 @VisibleForTesting
4279 public void updateRestrictBackgroundByLowPowerModeUL(final PowerSaveState result) {
4280 mRestrictBackgroundPowerState = result;
4281
4282 boolean restrictBackground = result.batterySaverEnabled;
4283 boolean shouldInvokeRestrictBackground;
4284 // store the temporary mRestrictBackgroundChangedInBsm and update it at last
4285 boolean localRestrictBgChangedInBsm = mRestrictBackgroundChangedInBsm;
4286
4287 if (result.globalBatterySaverEnabled) {
4288 // Try to turn on restrictBackground if (1) it is off and (2) batter saver need to
4289 // turn it on.
4290 shouldInvokeRestrictBackground = !mRestrictBackground && result.batterySaverEnabled;
4291 mRestrictBackgroundBeforeBsm = mRestrictBackground;
4292 localRestrictBgChangedInBsm = false;
4293 } else {
4294 // Try to restore the restrictBackground if it doesn't change in bsm
4295 shouldInvokeRestrictBackground = !mRestrictBackgroundChangedInBsm;
4296 restrictBackground = mRestrictBackgroundBeforeBsm;
4297 }
4298
4299 if (shouldInvokeRestrictBackground) {
4300 setRestrictBackground(restrictBackground);
4301 }
4302
4303 // Change it at last so setRestrictBackground() won't affect this variable
4304 mRestrictBackgroundChangedInBsm = localRestrictBgChangedInBsm;
4305 }
4306
Jeff Sharkey1b861272011-05-22 00:34:52 -07004307 private static void collectKeys(SparseIntArray source, SparseBooleanArray target) {
4308 final int size = source.size();
4309 for (int i = 0; i < size; i++) {
4310 target.put(source.keyAt(i), true);
4311 }
4312 }
4313
Stuart Scottf1fb3972015-04-02 18:00:02 -07004314 @Override
4315 public void factoryReset(String subscriber) {
4316 mContext.enforceCallingOrSelfPermission(CONNECTIVITY_INTERNAL, TAG);
4317
Stuart Scotte3e314d2015-04-20 14:07:45 -07004318 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4319 return;
4320 }
4321
Stuart Scottf1fb3972015-04-02 18:00:02 -07004322 // Turn mobile data limit off
Stuart Scott9a9a1d92015-04-20 11:33:06 -07004323 NetworkPolicy[] policies = getNetworkPolicies(mContext.getOpPackageName());
Stuart Scottf1fb3972015-04-02 18:00:02 -07004324 NetworkTemplate template = NetworkTemplate.buildTemplateMobileAll(subscriber);
4325 for (NetworkPolicy policy : policies) {
4326 if (policy.template.equals(template)) {
4327 policy.limitBytes = NetworkPolicy.LIMIT_DISABLED;
4328 policy.inferred = false;
4329 policy.clearSnooze();
4330 }
4331 }
4332 setNetworkPolicies(policies);
4333
4334 // Turn restrict background data off
4335 setRestrictBackground(false);
4336
Stuart Scotte3e314d2015-04-20 14:07:45 -07004337 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_APPS_CONTROL)) {
4338 // Remove app's "restrict background data" flag
4339 for (int uid : getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND)) {
4340 setUidPolicy(uid, POLICY_NONE);
4341 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004342 }
4343 }
Felipe Lemeb85a6372016-01-14 16:16:16 -08004344
Sudheer Shankab8f23162017-08-04 13:30:10 -07004345 @Override
4346 public boolean isUidNetworkingBlocked(int uid, boolean isNetworkMetered) {
4347 mContext.enforceCallingOrSelfPermission(MANAGE_NETWORK_POLICY, TAG);
4348 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
4349 }
4350
4351 private boolean isUidNetworkingBlockedInternal(int uid, boolean isNetworkMetered) {
4352 final int uidRules;
4353 final boolean isBackgroundRestricted;
4354 synchronized (mUidRulesFirstLock) {
4355 uidRules = mUidRules.get(uid, RULE_NONE);
4356 isBackgroundRestricted = mRestrictBackground;
4357 }
4358 if (hasRule(uidRules, RULE_REJECT_ALL)) {
4359 if (LOGV) logUidStatus(uid, "blocked by power restrictions");
4360 return true;
4361 }
4362 if (!isNetworkMetered) {
4363 if (LOGV) logUidStatus(uid, "allowed on unmetered network");
4364 return false;
4365 }
4366 if (hasRule(uidRules, RULE_REJECT_METERED)) {
4367 if (LOGV) logUidStatus(uid, "blacklisted on metered network");
4368 return true;
4369 }
4370 if (hasRule(uidRules, RULE_ALLOW_METERED)) {
4371 if (LOGV) logUidStatus(uid, "whitelisted on metered network");
4372 return false;
4373 }
4374 if (hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED)) {
4375 if (LOGV) logUidStatus(uid, "temporary whitelisted on metered network");
4376 return false;
4377 }
4378 if (isBackgroundRestricted) {
4379 if (LOGV) logUidStatus(uid, "blocked when background is restricted");
4380 return true;
4381 }
4382 if (LOGV) logUidStatus(uid, "allowed by default");
4383 return false;
4384 }
4385
Felipe Lemed17fda42016-04-29 11:12:45 -07004386 private class NetworkPolicyManagerInternalImpl extends NetworkPolicyManagerInternal {
4387
4388 @Override
4389 public void resetUserState(int userId) {
Felipe Lemef0823852016-06-08 13:43:08 -07004390 synchronized (mUidRulesFirstLock) {
4391 boolean changed = removeUserStateUL(userId, false);
4392 changed = addDefaultRestrictBackgroundWhitelistUidsUL(userId) || changed;
Felipe Lemed17fda42016-04-29 11:12:45 -07004393 if (changed) {
Felipe Lemef0823852016-06-08 13:43:08 -07004394 synchronized (mNetworkPoliciesSecondLock) {
4395 writePolicyAL();
4396 }
Felipe Lemed17fda42016-04-29 11:12:45 -07004397 }
4398 }
4399 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004400
4401 /**
4402 * @return true if the given uid is restricted from doing networking on metered networks.
4403 */
4404 @Override
4405 public boolean isUidRestrictedOnMeteredNetworks(int uid) {
4406 final int uidRules;
4407 final boolean isBackgroundRestricted;
4408 synchronized (mUidRulesFirstLock) {
4409 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4410 isBackgroundRestricted = mRestrictBackground;
4411 }
4412 return isBackgroundRestricted
4413 && !hasRule(uidRules, RULE_ALLOW_METERED)
4414 && !hasRule(uidRules, RULE_TEMPORARY_ALLOW_METERED);
4415 }
4416
4417 /**
4418 * @return true if networking is blocked on the given interface for the given uid according
4419 * to current networking policies.
4420 */
4421 @Override
4422 public boolean isUidNetworkingBlocked(int uid, String ifname) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004423 final boolean isNetworkMetered;
Sudheer Shankab8f23162017-08-04 13:30:10 -07004424 synchronized (mNetworkPoliciesSecondLock) {
4425 isNetworkMetered = mMeteredIfaces.contains(ifname);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004426 }
Sudheer Shankab8f23162017-08-04 13:30:10 -07004427 return isUidNetworkingBlockedInternal(uid, isNetworkMetered);
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004428 }
4429 }
4430
4431 private static boolean hasRule(int uidRules, int rule) {
4432 return (uidRules & rule) != 0;
4433 }
4434
4435 private static void logUidStatus(int uid, String descr) {
4436 Slog.d(TAG, String.format("uid %d is %s", uid, descr));
Felipe Lemed17fda42016-04-29 11:12:45 -07004437 }
Sudheer Shankae7361852017-03-07 11:51:46 -08004438
4439 /**
4440 * This class is used for storing and dumping the last {@link #MAX_PROC_STATE_SEQ_HISTORY}
4441 * (uid, procStateSeq) pairs.
4442 */
4443 @VisibleForTesting
4444 public static final class ProcStateSeqHistory {
4445 private static final int INVALID_UID = -1;
4446
4447 /**
4448 * Denotes maximum number of items this history can hold.
4449 */
4450 private final int mMaxCapacity;
4451 /**
4452 * Used for storing the uid information.
4453 */
4454 private final int[] mUids;
4455 /**
4456 * Used for storing the sequence numbers associated with {@link #mUids}.
4457 */
4458 private final long[] mProcStateSeqs;
4459 /**
4460 * Points to the next available slot for writing (uid, procStateSeq) pair.
4461 */
4462 private int mHistoryNext;
4463
4464 public ProcStateSeqHistory(int maxCapacity) {
4465 mMaxCapacity = maxCapacity;
4466 mUids = new int[mMaxCapacity];
4467 Arrays.fill(mUids, INVALID_UID);
4468 mProcStateSeqs = new long[mMaxCapacity];
4469 }
4470
4471 @GuardedBy("mUidRulesFirstLock")
4472 public void addProcStateSeqUL(int uid, long procStateSeq) {
4473 mUids[mHistoryNext] = uid;
4474 mProcStateSeqs[mHistoryNext] = procStateSeq;
4475 mHistoryNext = increaseNext(mHistoryNext, 1);
4476 }
4477
4478 @GuardedBy("mUidRulesFirstLock")
4479 public void dumpUL(IndentingPrintWriter fout) {
4480 if (mUids[0] == INVALID_UID) {
4481 fout.println("NONE");
4482 return;
4483 }
4484 int index = mHistoryNext;
4485 do {
4486 index = increaseNext(index, -1);
4487 if (mUids[index] == INVALID_UID) {
4488 break;
4489 }
4490 fout.println(getString(mUids[index], mProcStateSeqs[index]));
4491 } while (index != mHistoryNext);
4492 }
4493
4494 public static String getString(int uid, long procStateSeq) {
Sudheer Shankadb9aaf032017-06-19 19:05:31 -07004495 return "UID=" + uid + " Seq=" + procStateSeq;
Sudheer Shankae7361852017-03-07 11:51:46 -08004496 }
4497
4498 private int increaseNext(int next, int increment) {
4499 next += increment;
4500 if (next >= mMaxCapacity) {
4501 next = 0;
4502 } else if (next < 0) {
4503 next = mMaxCapacity - 1;
4504 }
4505 return next;
4506 }
4507 }
Chris Wren193ae6b2017-03-31 15:17:11 -04004508
4509 private class NotificationId {
4510 private final String mTag;
4511 private final int mId;
4512
4513 NotificationId(NetworkPolicy policy, int type) {
4514 mTag = buildNotificationTag(policy, type);
4515 mId = type;
4516 }
4517
4518 @Override
4519 public boolean equals(Object o) {
4520 if (this == o) return true;
4521 if (!(o instanceof NotificationId)) return false;
4522 NotificationId that = (NotificationId) o;
4523 return Objects.equals(mTag, that.mTag);
4524 }
4525
4526 @Override
4527 public int hashCode() {
4528 return Objects.hash(mTag);
4529 }
4530
4531 /**
4532 * Build unique tag that identifies an active {@link NetworkPolicy}
4533 * notification of a specific type, like {@link #TYPE_LIMIT}.
4534 */
4535 private String buildNotificationTag(NetworkPolicy policy, int type) {
4536 return TAG + ":" + policy.template.hashCode() + ":" + type;
4537 }
4538
4539 public String getTag() {
4540 return mTag;
4541 }
4542
4543 public int getId() {
4544 return mId;
4545 }
4546 }
Jeff Sharkeyd5cdd592011-05-03 20:27:17 -07004547}